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

i need abundant help to use email alerts and streamwriter correctly in nt.

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

    i need abundant help to use email alerts and streamwriter correctly in nt.




    regards to everyone,



    i think this kind of indicators i'm trying to create should be quite interesting for the expert programmers with nt support.


    i have been using an inferior and failed platform (ts) for several years, it does a decent job creating visually passable charts but their backtesting, optimization and automated trading engines are all colossal failures. non minute charts (range, momentum, kase and others) will draw one way when they have been created from real time data but then if one copies or closes and reopens these kind of charts the bars will be drawn quite differently from historical data (erroneously), and this will cause all indicators and strategies in that chart to redraw and recalculate erroneously as well. this makes backtesting or optimizing on ts a complete waste of time as these processes all run on historical data. in fact, to be able to determine if any particular strategy would really be competitive - profitable in the real world i realized that i would have to create indicators that would be exact equivalents to my strategies but instead of sending orders to market would generate either email alerts or text files using streamwriter. as both the email messages and the text files exist outside of ts and it is impossible to modify them once they have been created i can use the information in these logs to determine with certainty the profits or losses that these trades would have generated trading in real time in the real world.


    i have been evaluating nt for a couple of weeks and i would like to create indicators that did the very same thing in this platform. that is, replicate my strategies to perfection but instead of sending orders to the market send email alerts or create text files using streamwriter. it is important for me to be able to generate these external logs so that i can have determine how good nt is at executing automated strategies in real time and how profitable my strategies would be if i used nt to trade them automated.


    i have never used email alerts with nt but i think i should be able to figure out by myself how to send email messages every time an uptrend or downtrend begins and ends. i think i will start by using the strategy builder to see how the code to send emails looks like and go from there.


    email messages are adequate for this objective, but one has to open several messages and go through their contents to be able to know how a group of trades would have performed in the real world. however, streamwriter can create much more useful and practical text files as one can evaluate the profitability of an strategy just by taking a glance at these logs.


    this below is an example of the code i'm using in ts. this script generates one individual file for every event (start or end of a downtrend or uptrend, which a strategy would have processed as entry or exit orders). streamwriter creates the names for the files dynamically and they include the symbol ticker one is monitoring, the kind of event (casnum), date and time information and the price for the instrument at the time of the event. i have tried to convert this script to ninjascript - c# but this is as far as i was able to get and the samples that i have found to use streamwriter with nt all create one single file and then append it endlessly, which is not useful for me. i will insert some comments throughout this piece of code using * *. it is quite important for me to be able to generate these logs using nt, so i will be grateful if the people with nt support can assist me in fully converting this indicator to ninjascript.


    Code:
    
    using elsystem;   
    using elsystem.collections;   
    using elsystem.io;  
    using tsdata.common;
    using tsdata.marketdata;
    using tsdata.trading;
    
    
    inputs:
    price(close),
    smap01(20),
    nc(white),
    uc(darkblue),
    dc(darkred),
    rounum(5),
    poioff(10),
    string iprimarydirectory("c:\ntlogs"),
    string symtic("aapl"),
    string filnamplusymtic("logs_aapl"),  
    string gronam("aaplg01");
    
    * the indicator draws a moving average that changes color from neutral to uptrend or downtrend color if the appropriate conditions are present, it also generates a text file to log all the requested information.  *
    
    variables:
    smav01(0),
    utc(false),
    dtc(false),
    cc(white),
    casnum(0),
    tarpriu(0),
    tarprid(0),
    streamwriter sw(null);
    
    
    
    
    //    pass in a string containing line to be written to the file         
    method void recordevent(string msg)     
    variables:     
    string filepath;     
    begin     
        //    create file name, including a directory based upon the symbol     
        //     
        //    note:   symbol should not contain characters that are not valid in file names     
        //            indicator name should not contain invalid characters for a file name     
        //            add whatever other parameters desired         
        filepath = string.format("{0}\{1}_{2}_{3:yyyyMMddhhmmss}_{4}_{5}.txt",     
            iprimarydirectory,     
            filnamplusymtic, //orderticket.gettradingsymbolfor(symbol, category),     
            gronam,     
            datetime.now,
            casnum,
            numtostr(price,2));
    
        print(filepath);
        sw = streamwriter.create(filepath);  
        sw.autoflush = true;    
        sw.writeline(msg);      
        sw.close();     
    end;
    
    
    * this fragment above generates file names dynamically, one per event. having all the relevant information in the file name itself is immensely convenient. *
    
    
    
    
    smav01 = sma( price, smap01 ) ;
    
    
    
    plot1 ( smav01, "sm crossover colors tf" );
    
    
    tarpriu = ( ( rounum * ( Math.Floor  ( price / rounum ) ) ) - poioff ) ;
    
    tarprid = ( ( rounum * ( Math.Ceiling  ( price / rounum ) ) ) + poioff ) ;
    
    
    * these are some target prices i calculate based on the price of the instrument at the time of the event. *
    
    
    
    if smav01[0] > close[0] then begin
        utc = true;
    casnum = 1;
        cc = uc;
    end
    else if smav01[0] < close[0] then begin
        utc = false;
    casnum = 2;
        if cc = uc then
            cc = nc;  
    end;
    
    
    if smav01[0] < close[0] then begin
        dtc = true;
    casnum = 3;
        cc = dc;
    end
    else if smav01[0] > close[0] then begin
        dtc = false;
    casnum = 4;
        if cc = dc then
            cc = nc;  
    end;
    
    * i use boolean variables to determine if a downtrend or uptrend is currently active. the four different types are indeed necessary if i want to use all the components in my strategies.  *
    
    
    setplotcolor(1, cc);
    
    
    if utc=true and utc[1]=false and lastbaronchart and barstatus( 1 ) = 2 then begin  
    recordevent(
    
    "group "+ gronam + newline +
    
    "symbol:" + spaces(1) + symtic + spaces(1) + “started uptrend” + spaces(1) + “case 1” + spaces(1) + numtostr(price,2)" + newline
    
    );    
    end;
    
    * i only want real time events to be recorded, if i don't use the last bar on chart and bar status completed commands then the indicator would create alerts or files for every event in the historical data in a chart which would be useless. i don't know if the streamwriter syntax for the information to be written inside each file would be different in the case of ninjascript - c#, i would think it must be the same or pretty similar. *
    
    if utc=false and utc[1]=true and lastbaronchart and barstatus( 1 ) = 2 then begin  
    recordevent(
    
    "group "+ gronam + newline +
    
    "symbol:" + spaces(1) + symtic + spaces(1) + “ended uptrend” + spaces(1) + “case 2” + spaces(1) + numtostr(price,2)" + newline
    
    );    
    end;
    if dtc=true and dtc[1]=false and lastbaronchart and barstatus( 1 ) = 2 then begin  
    recordevent(
    
    "group "+ gronam + newline +
    
    "symbol:" + spaces(1) + symtic + spaces(1) + “started downtrend” + spaces(1) + “case 3” + spaces(1) + numtostr(price,2)" + newline
    
    );    
    end;
    if dtc=false and dtc[1]=true and lastbaronchart and barstatus( 1 ) = 2 then begin  
    recordevent(
    
    "group "+ gronam + newline +
    
    "symbol:" + spaces(1) + symtic + spaces(1) + “ended downtrend” + spaces(1) + “case 4” + spaces(1) + numtostr(price,2)" + newline
    
    );    
    end;

    very well, this is the situation. it took me and the ineffective people with ts support more than two weeks to create this code and get it to work to perfection to accomplish my objectives (nothing like this had ever been done in ts). however, i have no doubts that it won't be a challenge to create an equivalent indicator for nt. excellent, thanks, regards.

    #2
    Hello rtwave, thanks for your post.

    Unfortunately, it's against our policy to convert or develop custom scripts. This is to ensure we give a high level of service to all of our clients. You may hire a consultant from the publicly available NinjaTrader ecosystem website to do this.

    I created this indicator which emails the user when an execution occurs on the selected account, so this is a good example on how to use email alerts in NinjaScript:

    This indicator will email the specified email address when an execution occurs on the selected account.


    You should also use a lock on the streamwriter object to prevent multiple threads from accessing the file like so:

    Code:
    private object lockObj = new object();
    
    private void WriteFile()
    {
      // lock a generic object to ensure only one thread is accessing the following code block at a time
      lock (lockObj)
      {
          string filePath = @"C:\sample.txt";
          using (System.IO.FileStream file = new System.IO.FileStream(filePath, FileMode.Append, FileAccess.Write, FileShare.None)
          {
            // write something to the file...
    
            // be sure to flush the buffer so everything is written to the file.
            file.Flush();
    
            // The "using" block implicitly closes the FileStream object,
            // giving other threads access to the file
          }
      }
    }
    On the subject of making a new file, the File class has a Create method, this can be used to create a new file (ensure it has a unique name):



    Please let us know if we can assist any further.

    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 add-ons 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.
    Chris L.NinjaTrader Customer Service

    Comment


      #3



      Chris L.,



      thanks.


      i strongly disagree with the notion that i have asked nt for help to develop a custom script. there's nothing custom about the code i posted previously, it is nothing but a price - sma crossover indicator, it is the most ordinary and nondescript indicator that exists.


      i'm just asking nt to provide a working sample of any kind of indicator that:


      - uses streamwriter to conditionally generate a new and unique text file only when certain particular conditions are true.

      - uses information from the instrument name, price at close, date and time at close from year all the way down to seconds, plus other string inputs to create a unique file name dynamically for every file it generates.


      the streamwriter sample nt has made available is not helpful in the least in this particular case and i could read extensively in the internet about c# and streamwriter but that would never help me to learn how to create code that would work with the very peculiar structure full of different protected override voids that ninjatrader and ninjascript use.


      this below is the only streamwriter sample that is available:

      - ¿how could i modify this sample so that it will conditionally generate a new and unique text file only when certain particular conditions are true? i imagine this kind of commands should be included in the onbarupdate void.

      - ¿how should i modify this sample so that it will generate a new and unique file name for every file? ¿in which section of the indicator should this excerpt be inserted?

      - ¿how could i get this indicator to write different kinds of text messages inside the text files it generates? i'm most interested in including variables like date and time, price, user defined variables and special characters like line breaks and spaces.


      Code:
      public class SampleStreamWriter : Indicator
          {
              private string path;
              private StreamWriter sw; // a variable for the StreamWriter that will be used
      
              protected override void OnStateChange()
              {
                  if(State == State.SetDefaults)
                  {
                      Calculate         = Calculate.OnBarClose;
                      Name            = "Sample stream writer";
                      path             = NinjaTrader.Core.Globals.UserDataDir + "MyTestFile.txt"; // Define the Path to our test file
                  }
                  // Necessary to call in order to clean up resources used by the StreamWriter object
                  else if(State == State.Terminated)
                  {
                      if (sw != null)
                      {
                          sw.Close();
                          sw.Dispose();
                          sw = null;
                      }
                  }
              }
      
              protected override void OnBarUpdate()
              {
                  sw = File.AppendText(path);  // Open the path for writing
                  sw.WriteLine(Time[0] + "," + Open[0] + "," + High[0] + "," + Low[0] + "," + Close[0]); // Append a new line to the file
                  sw.Close(); // Close the file to allow future calls to access the file again.
              }
          }

      very well, i think that if nt can be helpful by making the most elementary working sample possible available i then should be able to make the necessary changes to create indicators that would create an external and reliable log for all the trading events that my strategies generate in real time. thanks, regards.



      Comment


        #4
        Hi rtwave, thanks for your reply.

        I attached an example that will write a new file on every odd bar (as a sample condition) it also uses string concatenation to create "unique" file names. It appends the current second to the file name, this is contrived so a real unique file name will need to be used instead. You can get information on an instrument through any of the price series arrays, to get the timestamp of a bar you can use the Time array. Time[0] will hold the timestamp of the most current tick down to the milliseconds, assuming Calculate == Calculate.OnEachTick.

        Please let me know if I can assist any further.
        Attached Files
        Chris L.NinjaTrader Customer Service

        Comment


          #5



          Chris, people with nt,



          over the past few days i have devoted a lot of time to creating an indicator in nt that will log trading events to text files. i have to say i haven't been able to make any progress at all. i have read all the internet guides i could find on how to use streamwriter with c# and those had no relevance to the kind of logs i'm trying to have generated.


          this is an objective of the utmost importance for me, so i will create an account in stackoverflow and ask the experts there for help. i'll see if i find more helpful assistance there.

          Comment


            #6



            Chris, people with nt,


            today i was able to make great progress but i still need decisive help to create an indicator or strategy that will create text files as logs for every event that i'm monitoring for.


            this is the code i have at the moment:


            Code:
            protected override void OnBarUpdate()
                    {
            
                    if (BarsInProgress != 0)
                        return;
            
                    if (CurrentBars[0] < 1)
                        return;
            
                    if (CurrentBars[0] <= BarsRequiredToPlot) return;
            
                    Clostr = Close[0].ToString("0.##########");
            
                     // Set 1
                    if (CurrentBar % 2 == 0)
                        {
                            WriteFile(    
            
                                        $"group {Gronam}" + Environment.NewLine +
            
                                        $"symbol: {Symtic} started downtrend {Castyp} {Clostr}" + Environment.NewLine
            
                                        );
                        }
            
                     // Set 2
                    if (CurrentBar % 2 == 1)
                        {
                            WriteFile(    
            
                                        $"group {Gronam}" + Environment.NewLine +
            
                                        $"symbol: {Symtic} ended downtrend {Castyp} {Clostr}" + Environment.NewLine
            
                                        );
                        }
                    }
            
                        private object lockObj = new object();
            
                    private void WriteFile(string text)
                    {
                      // lock a generic object to ensure only one thread is accessing the following code block at a time
                      lock (lockObj)
                      {
                          string filePath = string.Format(@"{0}ntlogs {1} {2} {3} {4} {5}.txt", Pridir, Symtic, Gronam, DateTime.Now.ToString("yyyyMMdd HHmmss"), Castyp, Clostr);
                          using (System.IO.FileStream file = new System.IO.FileStream(filePath, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None))
                          {
            
                            byte[] tempstring = new UTF8Encoding(true).GetBytes(text);
            
                            file.Write(tempstring, 0, tempstring.Length);  
            
                            // be sure to flush the buffer so everything is written to the file.
                            file.Flush();
            
                            // The "using" block implicitly closes the FileStream object,
                            // giving other threads access to the file
                          }
                      }
            
                    }



            this indicator does create a unique file with a unique filename some of the times the conditions that have been defined are observed. i'm still testing whether it will create the files consistently or not.



            i could still use some help with the two WriteFile sections. below is the text that is being written to the files with this code as i have it:


            group {Gronam}

            symbol: {Symtic} started downtrend {Castyp} {Clostr}


            as it should be obvious, i don't want the names of the variables i'm trying to use to be written to the text files, i want the values for said variables. ¿how could i get nt to write the values for these variables? i used the $ command to try and interpolate these values but then nt wouldn't compile the code.

            also, i tried to create a private variable Clostr = Close[0].ToString("0.########"); which i want to use to transform the price at close to string. ¿how could i get nt to print the value with the number of decimals as an input - parameter the user could define (sometimes 2, sometimes 4, 6 or 8)?

            very well, thanks, regards.
            Last edited by rtwave; 11-04-2019, 01:22 AM.

            Comment


              #7



              Chris, people with nt,


              after extensive testing yesterday and today, i have found a very significant problem. this indicator will only create text files as i intend it to do if the chart where it has been deployed is active (that is to say, it is the one window on top, or currently selected or active of all the the other nt windows and other programs i can have running). if i select any other window to work on anything else, the indicator will stop creating the files.


              Click image for larger version

Name:	nt logs screengrab 002.JPG
Views:	501
Size:	110.5 KB
ID:	1076814

              my objective is to create text files as logs for every trading signal that my strategies - indicators generate and i would have strategies or indicators running on several charts for a number of different symbols on my remote dedicated server. it would be impossible for me to have all the charts that i want to create logs for selected at the same time and at all times because i use my server to run numerous other programs and get other work done. so, unless it was possible to have nt code that could generate these files even if the windows where it was running were on the background then this indicator would be useless for me.


              i have put an enormous amount of work and effort into this code as these external logs will be decisive in helping me make the decision over whether to use the nt platform and brokerage to trade with real funds or not. i hope there are ways to make this code work as intended and nt support can assist me to solve this.



              very well, thanks, regards.

              Last edited by rtwave; 11-05-2019, 03:39 PM.

              Comment


                #8
                Hi rtwave, thanks for your reply.

                Writing files is a general C# topic that could be implemented in many different ways, so it's out of the scope of support we are able to provide. The OnBarUpdate method still runs even if a chart is not focused, so this problem seems to be a problem with threading. It could be worth it to try writing the file in a Dispatcher.

                To add variables to a string you can use the + operator on the string.

                e.g.

                var tempstring = "The Close is " + Close[0];
                Chris L.NinjaTrader Customer Service

                Comment


                  #9
                  Originally posted by rtwave View Post


                  Chris, people with nt,


                  after extensive testing yesterday and today, i have found a very significant problem. this indicator will only create text files as i intend it to do if the chart where it has been deployed is active (that is to say, it is the one window on top, or currently selected or active of all the the other nt windows and other programs i can have running). if i select any other window to work on anything else, the indicator will stop creating the files.


                  Click image for larger version

Name:	nt logs screengrab 002.JPG
Views:	501
Size:	110.5 KB
ID:	1076814

                  my objective is to create text files as logs for every trading signal that my strategies - indicators generate and i would have strategies or indicators running on several charts for a number of different symbols on my remote dedicated server. it would be impossible for me to have all the charts that i want to create logs for selected at the same time and at all times because i use my server to run numerous other programs and get other work done. so, unless it was possible to have nt code that could generate these files even if the windows where it was running were on the background then this indicator would be useless for me.


                  i have put an enormous amount of work and effort into this code as these external logs will be decisive in helping me make the decision over whether to use the nt platform and brokerage to trade with real funds or not. i hope there are ways to make this code work as intended and nt support can assist me to solve this.



                  very well, thanks, regards.
                  From the literature: https://ninjatrader.com/support/help...leinactive.htm

                  Use the correct command so that execution is not suspended when the chart is not in the foreground.

                  Comment


                    #10




                    people with nt,




                    after a long time, i decided to try once again to use nt to keep logs of events of interest for some symbols i monitor.



                    i have made some good progress, but i'm having a lot of trouble with historical data.



                    i created some nt ninjascript code that will indeed create text files following some events of interest, but when i activate this script on a chart it will create hundreds of text files for all the cases that were observed on historical data. obviously, this is useless and a waste of processing power.



                    ¿how can i create conditions such that plots and logical evaluations will continue to work normally on all data but text files like the ones below will only be generated on real time data? i have these commands inside the onbarupdate void.




                    if (CurrentBar % 2 == 0)
                    {
                    Castyp = "c";
                    message = string.Format(@"ntlogs\{0} {1}symbol: {2} case type c {3} {4}", Environment.NewLine, Symtic, Castyp[0], Close[0], Environment.NewLine);
                    recordevent(message);
                    Print(message);
                    }


                    if (CurrentBar % 2 == 1)
                    {
                    Castyp = "d";
                    message = string.Format(@"ntlogs\{0} {1}symbol: {2} case type d {3} {4}", Environment.NewLine, Symtic, Castyp[0], Close[0], Environment.NewLine);
                    recordevent(message);
                    Print(message);
                    }




                    very well, regards.

                    Comment


                      #11
                      Hi rtwave, you can ignore or process historical only code within this condition in OnBarUpdate:

                      if(State == State.Historical)
                      {
                      return;
                      }
                      Chris L.NinjaTrader Customer Service

                      Comment


                        #12




                        NinjaTrader_ChrisL,




                        thanks.



                        as i mentioned, i have numerous logical conditions to evaluate and indicators to plot that i do want to work on historical data.



                        it is only the log files i want to run exclusively on real time data.


                        i'm thinking of using an inverse condition and place the code for the files in here.


                        if (State == State.Realtime)
                        {

                        }




                        i will have to see how that goes.



                        oks, regards.

                        Comment

                        Latest Posts

                        Collapse

                        Topics Statistics Last Post
                        Started by cre8able, Today, 03:20 PM
                        0 responses
                        5 views
                        0 likes
                        Last Post cre8able  
                        Started by Fran888, 02-16-2024, 10:48 AM
                        3 responses
                        47 views
                        0 likes
                        Last Post Sam2515
                        by Sam2515
                         
                        Started by martin70, 03-24-2023, 04:58 AM
                        15 responses
                        114 views
                        0 likes
                        Last Post NinjaTrader_Jesse  
                        Started by The_Sec, Today, 02:29 PM
                        1 response
                        7 views
                        0 likes
                        Last Post NinjaTrader_Jesse  
                        Started by jeronymite, 04-12-2024, 04:26 PM
                        2 responses
                        31 views
                        0 likes
                        Last Post NinjaTrader_BrandonH  
                        Working...
                        X