Announcement

Collapse

Looking for a User App or Add-On built by the NinjaTrader community?

Visit NinjaTrader EcoSystem and our free User App Share!

Have a question for the NinjaScript developer community? Open a new thread in our NinjaScript File Sharing Discussion Forum!
See more
See less

Partner 728x90

Collapse

Reverse Position

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

    Reverse Position

    Hello,

    I wrote 2 strategies one is only going long and other is only short.

    First, I test separately this strategies with EntryHandleing = AllEntries & PerDirection = 1.
    Suppose long strategy is profit 100$ and short strategy is profit 150$.

    Second, I test 2 strategies on the same chart and same parameters. Result is as expected 250$ profit.

    And now i'm trying to combine this strategies in one strategy. After combine i test it with EntryHandleing = UniqueEntries & PerDirection = 1 parameters. Because after combine i use different entry names for long and for shorts. i see results are not same. When i examine test result i see some positions are not opening.

    For example suppose we have open long position 5 bars later strategy see there is short signal. Strategy don't close long and open new short position immediately. Instead setting profit target one tick above current price and try to open short same level(again one tick above current price) with EnterShortLimit order. If next bar don't hit this level ShortLimit order cancels and long position profit target setting bigger value. When i look at trade list i see target level hiting, long position closing with profit target but short trade not opening.

    1.Am i using right parameters? EntryHandleing = UniqueEntries & PerDirection = 1
    2. Is there more simple way for my reverse scenario?

    Thanks.
    Attached Files
    Last edited by aytacasan; 08-07-2013, 07:03 PM.

    #2
    aytacasan, when you run the combined script with TraceOrders added - do you see any ignored orders happening via the output window?

    BertrandNinjaTrader Customer Service

    Comment


      #3
      I'm sending output when related orders sending, trace ouput below. But not important where is my fault. More important is how can i write my strategy properly. Shortly i want to write strategy that never using market orders. For enter or exit trade, reverse position, i want to use limit orders or whatever it's name. So are you have any sample code or suggestion for do this. Ninjatrader help is not bad, forum is value of gold but in my opinion these are not enough. Especially hard to undestand who one english is not his/her main language like me.

      For clarification;

      1.If i set EntriesPerDirection = 0 & EntryHandling = EntryHandling.AllEntries, strategy can not process entry orders(EnterLong, EnterShort, EnterLongLimit, EnterShortLimit etc.) when we have active position. Strategy start process entry orders after close position, shortly when market position is flat.

      2.If i set EntriesPerDirection = 1 & EntryHandling = EntryHandling.AllEntries, strategy can process entry orders for only plus 1 entry order. If strategy execute 2 entry order, next entry order will be ignore. Even if the names are different.

      3.Shortly we can suppose EntriesPerDirection is a counter for executed orders count. If EntryHandling.AllEntries platform order processor keeping only one counter, other case (EntryHandling.UniqueEntries) order processor keeping many counter (for each different entry name). And when we exceed limit (EntriesPerDirection + 1) our entry order not execute.

      Am i right?

      04.06.2013 04:20:00 Entered internal SetStopTarget() method: Type=Target FromEntrySignal='LongEntry' Mode=Price Value=1633,5 Currency=0 Simulated=False
      04.06.2013 04:20:00 Amended target order: Order='NT-00008/Replay101' Name='Profit target' State=Working Instrument='ES 09-13' Action=Sell Limit price=1633,5 Stop price=0 Quantity=1 Strategy='MomentumStrategy' Type=Limit Tif=Gtc Oco='NT-00000-1195' Filled=0 Fill price=0 Token='955bc67133e6456e8d97da9c9c83bebf' Gtd='01.12.2099 00:00:00'
      04.06.2013 04:20:00 Entered internal SetStopTarget() method: Type=Stop FromEntrySignal='ShortEntry' Mode=Price Value=1883,5 Currency=0 Simulated=False
      04.06.2013 04:20:00 Entered internal SetStopTarget() method: Type=Target FromEntrySignal='ShortEntry' Mode=Price Value=1383,5 Currency=0 Simulated=False
      04.06.2013 04:20:00 Entered internal PlaceOrder() method at 04.06.2013 04:20:00: BarsInProgress=0 Action=SellShort OrderType=Limit Quantity=1 LimitPrice=1633,50 StopPrice=0 SignalName='ShortEntry' FromEntrySignal=''
      04.06.2013 04:20:00 Cancelled pending exit order, since associated position is closed: Order='NT-00007/Replay101' Name='Stop loss' State=Working Instrument='ES 09-13' Action=Sell Limit price=0 Stop price=1384,25 Quantity=1 Strategy='MomentumStrategy' Type=Stop Tif=Gtc Oco='NT-00000-1195' Filled=0 Fill price=0 Token='08a2832efad94bc38ef533950767b4de' Gtd='01.12.2099 00:00:00'
      04.06.2013 04:20:00 Cancelled OCO paired order: BarsInProgress=0: Order='NT-00007/Replay101' Name='Stop loss' State=Cancelled Instrument='ES 09-13' Action=Sell Limit price=0 Stop price=1384,25 Quantity=1 Strategy='MomentumStrategy' Type=Stop Tif=Gtc Oco='NT-00000-1195' Filled=0 Fill price=0 Token='08a2832efad94bc38ef533950767b4de' Gtd='01.12.2099 00:00:00'
      Last edited by aytacasan; 08-08-2013, 07:30 AM.

      Comment


        #4
        aytacasan, I can understand this is a challenge especially for a non native speaker. Perhaps this link would help clarify the EntryHandling options of the managed approach a bit further :



        EnterPerDirection will have a minimum of 1, with .AllEntries there be only one entry triggered at any time, if you are in a position already and your rule would additionally trigger > NT will ignore it. Only if the current trade would be flat and then your entry retriggered, another fresh entry would be done.

        With .UniqueEntries this count would be done for each uniquely named entry. So lets say if you have 3 entries and EntrierPerDirection to 1 you could still have 3 entries overall in one direction, one for each unique entry.

        You also want to closely review this link here on the managed approach in general : http://www.ninjatrader.com/support/h...d_approach.htm

        Any non market order would expire on the next OnBarUpdate() call, so it would be important here to either

        a) resubmit it if not filled and your entry still valid
        b) set it to liveUntilCancelled in the advanced overload and then CancelOrder() as needed.
        (http://www.ninjatrader.com/support/h...r_handling.htm)

        The issue for your script here is likely the working profit target at the same level as the limit order reverse, so running into one of the rules of the managed approach -

        Methods that generate orders to enter a position will be ignored if:

        > A position is open and an order submitted by a set method (SetProfitTarget() here) is active and the order is used to open a position in the opposite direction
        BertrandNinjaTrader Customer Service

        Comment


          #5
          Bertrand, thanks for your fully informative response. Now i clearly understand EnterPerDirection and Handling options. I use before both unmanaged and managed approach. managed is simple and unmanaged is more flexible. I'm writing my new idea with managed approach first and if i see good profit i'll write it unmanaged approach too for live trading. Also yes i know that ninjatrader limit order lifetime management. My code is compatible with this. But i understand that from your response my short entry limit order and long position take profit orders are overlap and ninjatrader order processor is ignoring my short entry limit order. I'm starting explore your links but at the same time could you please tell me there is a command that reverse my long position to short with limit order. I mean i using SetProfitTarget only for close long position with possible future price and at the same level i want to go short at the same time. I'm using this approach because maybe this level not hit next bar, there is no guaranty about that. Are there any command for this? If so i don't send two order that one is set open position take profit level and other is opening reverse position. I'll send one order close position completely and open reverse position for me.
          Last edited by aytacasan; 08-08-2013, 11:57 AM.

          Comment


            #6
            could you please tell me there is a command that reverse my long position to short with limit order
            With the managed approach you can place an entry order in the opposite direction to reverse the position.

            For example, if you're currently short and call

            EnterLong();

            this will first exit the short order by market, and then enter long with the above specified quantity/order type

            Let me know if I can be of further assistance.
            LanceNinjaTrader Customer Service

            Comment


              #7
              I think there is misunderstanding. I can't use EnterLong when already in short position or EnterShort when i have long position, these are market order. I need reverse X ticks later.

              if (Position.MarketPosition == MarketPosition.Long)
              {
              if (FirstTickOfBar)
              {
              if (GoShort)
              {
              Reverse(Close[0] + X Ticks later);
              }
              }

              Also i read all help documents again about managed approach and compare unmanaged approach, except very very very specific conditions. Unmanaged approach according to managed approach, not as a superior. This is my opinion simplicity vs flexibility? of course simplicity Mean more effective more managed code less bug etc.

              Could you please give an example that can do with unmanaged approach and can't do with managed approach?
              Last edited by aytacasan; 08-08-2013, 02:38 PM.

              Comment


                #8
                In that case you could use a limit or stop order

                if (Position.MarketPosition == MarketPosition.Long)
                {
                if (FirstTickOfBar)
                {
                if (GoShort)
                {
                EnterShortLimit(0, true, 1, Close[0] + X Ticks later, "");//would place a liveUntilCancelled order to short X ticks above the market
                }
                }



                Let me know if I'm misunderstanding
                LanceNinjaTrader Customer Service

                Comment


                  #9
                  Thanks Lance,

                  After your response i change my code like you said but nothing changed.

                  Then i try to write simple sample strategy(only using limit orders) and i see this is working; if account flat then enterlonglimit opening new long position else if account is short then enterlonglimit closing short position and open new long position.

                  But in my orginal strategy i'm using dynamic setstoploss and setprofittarget commands. Then i change sample strategy works with static setstoploss and setprofittarget(i mean only once calling this command in initialize method), and i see still working as expected.

                  Then i change sample strategy with works dynamic setstoploss and setprofittarget (i mean call this method before call enterlonglimit/entershortlimit all time in onupdatebar method. And stil working as expected.

                  There is one thing; in my original strategy if necessery i changing take profit level with call setprofittarget for current position. Now i try to test sample strategy like this approach. Could you please tell me is there problem about this approach in ninjatrader process this commands terms and for clerify;

                  1) if i'm flat and if i call setprofittarget(X) means hereafter for all open new position's profit target is X. Until i call setprofittarget with different parameter.
                  2) if I have position already now, and if i call setprofittarget(X) means set current position ptofit taget X also hereafter for all open new position's profit target is X. Until i call setprofittarget with different parameter.

                  Am i right?
                  Last edited by aytacasan; 08-08-2013, 06:56 PM.

                  Comment


                    #10
                    Forget my previous replay(but please answer my questions). Not working; i'm sending strategy code and screenshot please look at these. For testing purpose i'm using liberal fill type. If i delete SetStopLoss and SetProfitTarget commands at that time working. I'm very very very confused.

                    Also output have this;

                    **NT** An Enter() method to submit an entry order at '04.06.2013 03:14:00' has been ignored. Please search on the term 'Internal Order Handling Rules' in the Help Guide for detailed explanation.

                    what is that mean? Also please don't consider, Why set fixed SL and TP before all entry order. Actually in my orginal strategy setting variable SL&TP for each order.

                    Code------------------------------------------------------------------------------------------

                    #region Using declarations
                    using System;
                    using System.ComponentModel;
                    using System.Diagnostics;
                    using System.Drawing;
                    using System.Drawing.Drawing2D;
                    using System.Xml.Serialization;
                    using NinjaTrader.Cbi;
                    using NinjaTrader.Data;
                    using NinjaTrader.Indicator;
                    using NinjaTrader.Gui.Chart;
                    using NinjaTrader.Strategy;
                    #endregion

                    // This namespace holds all strategies and is required. Do not change it.
                    namespace NinjaTrader.Strategy
                    {
                    /// <summary>
                    /// SampleStrategy
                    /// </summary>
                    [Description("SampleStrategy")]
                    public class SampleStrategy : Strategy
                    {
                    private int stopLossTicks = 8;
                    private int takeProfitTicks = 24;

                    /// <summary>
                    /// This method is used to configure the strategy and is called once before any strategy method is called.
                    /// </summary>
                    protected override void Initialize()
                    {
                    CalculateOnBarClose = false;
                    ExitOnClose = false;
                    }

                    /// <summary>
                    /// Called on each bar update event (incoming tick)
                    /// </summary>
                    protected override void OnBarUpdate()
                    {
                    var macd = MACD(12,26,9);
                    var barOffset = Historical || CalculateOnBarClose ? 0 : 1;
                    if (FirstTickOfBar)
                    {
                    if (Position.MarketPosition == MarketPosition.Long)
                    {
                    if (macd.Diff[barOffset + 1] >= 0 && macd.Diff[barOffset] < 0)
                    {
                    var entryLevel = Close[barOffset] + TickSize;
                    SetStopLoss("ShortEntry", CalculationMode.Price, entryLevel + stopLossTicks * TickSize, false);
                    SetProfitTarget("ShortEntry", CalculationMode.Price, entryLevel - takeProfitTicks * TickSize);
                    EnterShortLimit(1, entryLevel, "ShortEntry");
                    }
                    }
                    else if (Position.MarketPosition == MarketPosition.Short)
                    {
                    if (macd.Diff[barOffset + 1] <= 0 && macd.Diff[barOffset] > 0)
                    {
                    var entryLevel = Close[barOffset] - TickSize;
                    SetStopLoss("LongEntry", CalculationMode.Price, entryLevel - stopLossTicks * TickSize, false);
                    SetProfitTarget("LongEntry", CalculationMode.Price, entryLevel + takeProfitTicks * TickSize);
                    EnterLongLimit(1, entryLevel, "LongEntry");
                    }
                    }
                    else if (Position.MarketPosition == MarketPosition.Flat)
                    {
                    if (macd.Diff[barOffset + 1] <= 0 && macd.Diff[barOffset] > 0)
                    {
                    var entryLevel = Close[barOffset] - TickSize;
                    SetStopLoss("LongEntry", CalculationMode.Price, entryLevel - stopLossTicks * TickSize, false);
                    SetProfitTarget("LongEntry", CalculationMode.Price, entryLevel + takeProfitTicks * TickSize);
                    EnterLongLimit(1, entryLevel, "LongEntry");
                    }
                    else if (macd.Diff[barOffset + 1] >= 0 && macd.Diff[barOffset] < 0)
                    {
                    var entryLevel = Close[barOffset] + TickSize;
                    SetStopLoss("ShortEntry", CalculationMode.Price, entryLevel + stopLossTicks * TickSize, false);
                    SetProfitTarget("ShortEntry", CalculationMode.Price, entryLevel - takeProfitTicks * TickSize);
                    EnterShortLimit(1, entryLevel, "ShortEntry");
                    }
                    }
                    }
                    }
                    }
                    }
                    Attached Files
                    Last edited by aytacasan; 08-09-2013, 09:09 AM.

                    Comment


                      #11
                      Hello aytacasan,

                      May I have an export of this strategy?

                      This is just to ensure that the complete code is there for me to run.

                      To export your script do the following:
                      1. Click File -> Utilities -> Export NinjaScript
                      2. Enter a unique name for the file in the value for 'File name:'
                      3. Select the strategy from the objects list on the left -> click the right facing arrow ">" to add the strategy to the export
                      4. Click the 'Export' button -> click 'yes' to add any referenced indicators to the export -> click OK to clear the export location message


                      By default your exported file will be in the following location:
                      • (My) Documents/NinjaTrader 7/bin/Custom/ExportNinjaScript/<export_file_name.zip>


                      Below is a link to the help guide on Exporting NinjaScripts.




                      If you would like to keep the strategy private you may send this to me at support[at]ninjatrader[dot]com.
                      Chelsea B.NinjaTrader Customer Service

                      Comment


                        #12
                        Hello,

                        I don't understand why you want exported file. Already i send all code with copy paste. Could you please tell me why?

                        I try to export and i receive below errors. I also attach source file that path is "C:\Users\Pro\Documents\NinjaTrader 7\bin\Custom\Strategy"

                        10.08.2013 02:03:11 Default See Help Guide section 'Export Problems' (http://www.ninjatrader.com/support/h...t_problems.htm) for additional instructions
                        10.08.2013 02:05:49 Default Error compiling export sources: c:\Users\Pro\Documents\NinjaTrader 7\bin\Custom\Tmp\AssemblyInfo.cs(12,12) : error CS0579: Yinelenen 'AssemblyProduct' özniteliği
                        10.08.2013 02:05:49 Default Error compiling export sources: c:\Users\Pro\Documents\NinjaTrader 7\bin\Custom\Tmp\AssemblyInfo.cs(11,12) : error CS0579: Yinelenen 'AssemblyCompany' özniteliği
                        10.08.2013 02:05:49 Default Error compiling export sources: c:\Users\Pro\Documents\NinjaTrader 7\bin\Custom\Tmp\AssemblyInfo.cs(10,12) : error CS0579: Yinelenen 'AssemblyConfiguration' özniteliği
                        10.08.2013 02:05:49 Default Error compiling export sources: c:\Users\Pro\Documents\NinjaTrader 7\bin\Custom\Tmp\AssemblyInfo.cs(9,12) : error CS0579: Yinelenen 'AssemblyDescription' özniteliği
                        10.08.2013 02:05:49 Default Error compiling export sources: c:\Users\Pro\Documents\NinjaTrader 7\bin\Custom\Tmp\AssemblyInfo.cs(8,12) : error CS0579: Yinelenen 'AssemblyTitle' özniteliği
                        Attached Files

                        Comment


                          #13
                          Is there any process?

                          Comment


                            #14
                            Hello aytacasan,

                            I would like you to export the script so that I can ensure two things. First, I'd like to make sure you do not have any compile errors that can indicate mistakes in programming and/or missing files.

                            Second, I would like the export to ensure that there is not any code that has been left out of what was pasted in your post.

                            Also, while it doesn't look like there are any custom indicators referenced, an export will ensure that if there are any, the referenced indicators are included.

                            Exporting a script helps to ensure that everything is whole and that there are no compile errors. This can prevent a lot of extra work on my end while trying to test your script.

                            It does seem that you are having compile errors.

                            Please follow the instructions below to see where the errors are coming from after compiling the indicator. This will allow you to debug the indicator/strategy or remove it from your PC. If you are wondering why you receive an error when compiling only one indicator, it is because NinjaTrader always compiles all indicators and strategies - not just one. This is done to give you the highest runtime performance possible.
                            • Open NinjaTrader
                            • From the Control Center select the Tools menu--> select the Edit NinjaScript menu item--> select Indicator
                            • Select any indicator and double click on it (we need only to open and compile one script to see all compile errors for all files).
                            • A new window will appear and you will need to right click in the window and select Compile to compile the indicators.
                            • At the bottom of the window a new section will appear where you can find the error locations.
                            • From there you have the option to comment out offending code sections, remove the complete indicator or debug it to be able to compile again.
                            • If you are unsure as to what the error is indicating, please send me a screenshot of the error with the error column fully expanded so that I may read the full error message.


                            To send a screenshot press Alt + PRINT SCREEN to take a screen shot of the selected window. Then go to Start--> Accessories--> Paint, and press CRTL + V to paste the image. Lastly, save as a jpeg file and send the file as an attachment.

                            We have also collected more comprehensive steps for resolving NinjaScript programming errors in this tip on our forums - http://www.ninjatrader.com/support/f...ead.php?t=4678
                            Chelsea B.NinjaTrader Customer Service

                            Comment


                              #15
                              Hello Chelsea,

                              Sory but maybe i'll talk a bit harsh. I have simple problem and a few questions i tell my problem 3 different person. But in the event i don't have any solution and any answer. Plus all person saying do this do that. For to make your job easier i write simple strategy too.

                              I'm software developer 18 years, i'm using c# for 10 years. What compiler error? I have many indicators and strategies already now. And i'm compiling them without any error. I'm using and testing them. Like your said ninja compiling all indicators/strategies when we compile any. I don't have any sytax error.

                              Forget all so write this simple strategy yourself. This take your max 5 minutes. I think this will be good rather then i'm waiting solution for a few days. Rules;

                              1.Go long 1 tick belove close[0] when Macd.Dif series crossabove zero level, otherwise go short 1 tick above close[0]

                              2. Use SetStopLoss and TakeProfitTarget orders for each order in OnBarUpdate not in initialize method (In my strategy this levels will be dynamic but you can use static values for test, for example 2 points SL 6 points tp)

                              3.When you have long signal if strategy flat go long like 1, if strategy already long do nothing, if strategy short then reverse via limit order LongLimitOrder from level that close[0] + 1 tick.

                              4. Macd is standart Macd indicator, use any periods for it.

                              The choice is yours;

                              1. Use my source code that i copy paste direcly in my post
                              2. Use my source code that attached it in my post. I think this is simplest way copy attached file to your ninja trader custom strategies folder.
                              3. Write your own sample for see what is my problem.

                              There is no compiler error, there is no bug in ninjatrader. Only problem is i don't have any experiance about reverse position via Limit orders. Actually i know i have break ninjatrader one of rule about order processing (there is overlap position takeprofit level and new position entry level). But i don't know how can i solve this wit avalible my strategy scenerio. And i don't see any sample code in your library & help document reverse via limit order.

                              Sory about have a rough tongue.

                              Best Regards.

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by Tim-c, Today, 03:54 AM
                              0 responses
                              3 views
                              0 likes
                              Last Post Tim-c
                              by Tim-c
                               
                              Started by FrancisMorro, Today, 03:24 AM
                              0 responses
                              2 views
                              0 likes
                              Last Post FrancisMorro  
                              Started by Segwin, 05-07-2018, 02:15 PM
                              10 responses
                              1,771 views
                              0 likes
                              Last Post Leafcutter  
                              Started by Rapine Heihei, 04-23-2024, 07:51 PM
                              2 responses
                              31 views
                              0 likes
                              Last Post Max238
                              by Max238
                               
                              Started by Shansen, 08-30-2019, 10:18 PM
                              24 responses
                              945 views
                              0 likes
                              Last Post spwizard  
                              Working...
                              X