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

XML Serialization revisited

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

    XML Serialization revisited

    I have a problem with XML Serialization. In a strategy, I am referencing the CCI_Forecaster_DE I developed which has 17 parameters. In the A/T I am again revisiting, there are another bazillion parameters. That is far too many to re-enter each and every time. I have gotten them to serialize to an XML file to save them.

    My questions are:

    1) On initial startup, what is the sequence of events that occur so that I can deserialize those parameters back into the strategy so the saved values appear in the Strategy dialog box rather than the default values?

    2) When the strategy script is reloaded, again, what sequence of events occur and can I capture a reload event somehow so I can direct another serialization event?

    Basically, I need to retrieve them at the beginning and save them anytime they are changed.

    Thanks,
    Snap

    #2
    Hello,

    I will have someone respond to your post in more detail by Monday. However strategy is reloaded with the default settings that you have them initialized to in the Variables section and I do not believe there is a way around this. I will have someone confirm this.
    DenNinjaTrader Customer Service

    Comment


      #3
      Thanks. I knew it was a weekend and wasn't expecting a quick response.

      I got a kludge working, anyway. It is under OnBarUpdate() and calls SerializeSettings() and DeserializeSettings().

      There are two shortcomings. First, I must tell the strategy to save the settings through a bool that is immediately reset to false on completion of serialization. It is not an automatic thing on closure of the Strategy dialog. Second, the file path is hard coded and cannot be retrieved by deserialization and must be manually changed on each startup to point to the correct file.

      If anyone can help with these two problems, Id love to hear from you.

      Pertinent code snippets for anyone else struggling with this.

      public class CCIAutoTraderBasic : Strategy
      {

      #region Variables
      ....
      ....
      ....
      private bool deserialized = false;
      private bool saveSettings = false;
      private string filePath = @Cbi.Core.UserDataDir.ToString() + "CCIAutoTraderBasic.xml";


      protected override void OnBarUpdate()
      {
      if(SaveSettings)//Save Parameters for later retrieval
      {
      SerializeSettings();
      saveSettings = false;
      }

      if(File.Exists(@FilePath) && !Deserialized)//Retrieve saved parameters at initialization
      {
      DeserializeSettings();
      Deserialized = true;
      }
      ......
      ......
      ......
      }

      protected void SerializeSettings()
      {
      Print("Serializing");
      CCIAutoTraderBasic cciat = new CCIAutoTraderBasic();
      cciat.TypeEntry = typeEntry;
      cciat.T1_Target = t1;
      cciat.T2_Target = t2;
      .....
      .....
      .....
      XmlSerializer mySerializer = new XmlSerializer(typeof(CCIAutoTraderBasic));
      StreamWriter sw = new StreamWriter(@FilePath);
      mySerializer.Serialize(sw, cciat);
      sw.Close();
      }


      protected void DeserializeSettings()
      {
      Print("Deserializing");
      CCIAutoTraderBasic cciat = new CCIAutoTraderBasic();
      XmlSerializer mySerializer = new XmlSerializer(typeof(CCIAutoTraderBasic));
      using (FileStream fs = File.OpenRead(@FilePath))
      {
      cciat = (CCIAutoTraderBasic)mySerializer.Deserialize(fs);

      typeEntry = cciat.TypeEntry;
      t1 = cciat.T1_Target;
      t2 = cciat.T2_Target;
      ......
      ......
      ......
      }
      }
      Last edited by snaphook; 04-25-2009, 01:05 PM.

      Comment


        #4
        Hi snaphook,

        had to solve a task which sounds somehow similar to what you described. I saved a market profile setup to a file and reloaded it from a file. I initialised that by a context menu extension from the chart window (right button click). I wrote an own syntax parser instead of using the serialisation interface. But that is just an implementation detail. Not sure if such an approach is something you are looking for.

        Regard
        Ralph

        Comment


          #5
          The problem with strategies is that they are removed from the chart and not stored in the workspace the way indicators are. Does your implementation save the market profile with all indicator AND strategy settings intact and retrieve it using the context menu extension? If so, I would be very interested i taking a look.

          thanks.

          Comment


            #6
            No snaphook, the save option is not an automatic approach. To save a setup I call an extended context menu (right-click), a file dialog appears to select a file name, then the setup is written to the selected file. I save some of the public properties and some of the internal variables (i.e. profile splitting informations).

            For an automated approach you could have a look at the Dispose()-method. It is the last activity for an indicator class before it dies and I guess it is true for strategies too. To find out whether it behaves to your desire you could implement it with just a print statement.

            Regards
            Ralph

            Comment


              #7
              Hi Snapshook,

              actually I had the same need as you , and I did the following:
              only briefly today as I am off the desk.

              1. put DeserializeSettings() in Initialize()
              2. put SerializeSettings() in Dispose()
              3. xml filename: The filename contains also the instrument used and therefore the settings are relative to the instrument used.

              It works, but there is one problem if I remember well:
              Initialize() is called after the Strategy Parameters are set.
              So basically calling DeserializeSettings() will overwrite eventual settings changed in the Strategy Parameters dialog.
              I resolved this by having my own parameter form (opened in OnBarUpdate)

              The big problem is that Initialize() is called when the instrument is already defined, e.g. after the strategy parameter dialog. Remember that you can choose the instrument in there.

              andreas

              Comment


                #8
                Here some new findings,

                would be nice if someone could chime in as I feel to be in no mans land
                and NT support keeps very vague (instead of doumenting properly)


                1. Routing of getter / setter of strategy in the own code.
                This seems to work also for some default parameters that are set by strategybase.

                Example:

                ExitOnCloseSeconds is defined by strategy base.

                I would like to ovveride the default value in my strategy, so I do the following


                1. I define the get set functions in my strategy:e.g.

                [Description(
                "")]
                [Category(
                "Order Handling")]
                publicint ExitOnCloseSeconds {
                get {
                Print(
                "getExitOnCloseSeconds");
                // Don't do: Print(ExitOnCloseSeconds.ToString())
                // as this will cause stack overflow for obvious reasons
                return12;}
                set {
                base.ExitOnCloseSeconds=value;
                }
                }

                2. In above case my strategy sets the default to 12.
                3. In the setter I route to the base strategy.

                4. Remember that the getter/setters can be called before initialize,
                therefore it would be best to call Deserialize already from within the getter/setters if you want to reload saved values.


                Any comments or suggestions?

                Did Someone try this already?

                Andreas

                Comment


                  #9
                  Andreas,

                  For ExitOnCloseSeconds just follow this post: http://www.ninjatrader-support2.com/...06&postcount=5
                  Josh P.NinjaTrader Customer Service

                  Comment


                    #10
                    Josh,

                    your approach has the "huge" drawback that the strategy properties that you see in the dialog are not the same as the properties the strategy is running with because you ovveride them only in Initialize()
                    Thank you however because the parameters you indicate in your link should be dynamically modifiable.

                    ---------------------------


                    It is getting better:

                    One can also ovveride Data series.Instrument
                    In this way one hooks into changes of the selected instruments and one can load the parameter relative to the instruments.

                    See below:


                    [Description("")]
                    [Category(
                    "Data series")]
                    public Instrument Instrument {
                    get {
                    Print(
                    "Andreas1.getInstruments");
                    //Print("ExitOnCloseSeconds="+ExitOnCloseSeconds.ToS tring());
                    returnbase.Instrument;}
                    set {
                    Print(
                    "Andreas1.setInstruments");
                    base.Instrument=value;
                    //pyramide=value;
                    }
                    }

                    Comment


                      #11
                      Dynamically modifying strategy settings is not supported or recommended. You should only do them once in Initialize(). Especially something like ExitOnCloseSeconds. There should be no reason you would even need to do this dynamically. If you still wish to proceed down this path unfortunately you guys are on your own since it is beyond the level of support we can offer. Thank you for understanding.
                      Josh P.NinjaTrader Customer Service

                      Comment


                        #12
                        There seems to be a lot of discussion on this and I hope NT v7.0 will resolve the issue.

                        For now, it seems my approach works about as well as any, and since I understand it and it is not a huge imposition, I think I'll stick to what little I understand of C#.

                        I want to thank everyone for all the great input and am glad to hear I am not the only one struggling with this problem.

                        Comment


                          #13
                          Hi snapshot,

                          actually I do all this because I run my -very simple - strategy on different instruments. ES has different settings than FDAX and FGBL ot 6E is has different settings again.

                          I open several positions a day (today I did 6 trades) and I would like to keep my parameters associated with each instrument. So once I select an instrument in the strategy I want it to reload all the parameters last used for that instrument.
                          Unforutnately this feature is missing in NT, and priority for NT to develop this is low.

                          And I want to see what parameters I have loaded.
                          Therefore my approach. Actually the idea of hooking into the getter/setters is only 1 hour old, but it will load the parameters BEFORE Initialize(), hence there are no problems with setting parameters late or dynamically. My question concerning dynamical changes of the parameters is in another thread and should be treated seperately.

                          I am sorry to be so annoyingly precise here, but when I have positions open I must keep the situation under control, and a NT strategy that behaves differently than what I see in the properties is not helpful.
                          In 99% of the times it will work and I will pay attention, but there will be the one day with fast market or whatsoever and I could make a trading mistake because I forget that for the strategy the actual parameters are different, and usually it ends with a big loss of money.
                          The better solution for me is to sit down 2 to 3 hours and find a clean coded solution.

                          (this is to make NT people understand what I as a trader need!)

                          end
                          Last edited by zweistein; 04-27-2009, 04:54 PM.

                          Comment


                            #14
                            Thank you for your detailed input zweistein.
                            BertrandNinjaTrader Customer Service

                            Comment


                              #15
                              zweistein,

                              So if I want to load the same Parameters as I had on the prior Strategy Close such as a target exit price, how would I go about altering the getter setter? Here is what I currently have.

                              [Description("Target 1in ticks")]
                              [Gui.Design.DisplayName("\tT1 Target")]
                              [Category("Parameters")]
                              public int T1_Target
                              {
                              get { return t1; }
                              set { t1 = Math.Max(1, value); }
                              }

                              Thanks.
                              snaphook

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by DT215, 01-14-2023, 07:59 PM
                              4 responses
                              132 views
                              1 like
                              Last Post NinjaTrader_BrandonH  
                              Started by ETFVoyageur, Yesterday, 12:52 AM
                              2 responses
                              32 views
                              0 likes
                              Last Post NinjaTrader_BrandonH  
                              Started by Skifree, Yesterday, 02:50 PM
                              1 response
                              12 views
                              0 likes
                              Last Post NinjaTrader_Kimberly  
                              Started by owen5819, Yesterday, 02:24 PM
                              2 responses
                              16 views
                              0 likes
                              Last Post NinjaTrader_BrandonH  
                              Started by ETFVoyageur, Yesterday, 10:13 PM
                              2 responses
                              20 views
                              0 likes
                              Last Post NinjaTrader_BrandonH  
                              Working...
                              X