Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

opposite of Initialize()

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

    opposite of Initialize()

    I am using the following code to communicate with another process written in J (www.jsoftware.com) over a socket connection. The problem I have is that after running the simulation once, the socket remains connected but the reference to the socket is lost (i.e. the object JSocket is destroyed?).

    Is there a function somewhere in NT which gets called at the end of a simulation where I can put the code to close the socket connection before the JSocket object gets destroyed?

    What I am after is the opposite of Initialize(), something that is called right at the end of the simulation/session?

    Thanks,
    Matthew.

    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;
    
    using System.Net;
    using System.Net.Sockets;
    
    #endregion
    
    // This namespace holds all strategies and is required. Do not change it.
    namespace NinjaTrader.Strategy
    {
        /// <summary>
        /// </summary>
        [Description("")]
        public class connectJ : Strategy
        {
            #region Variables
                Socket JSocket = null;
                const string server = "127.0.0.1";
                const int port = 1500;
                const int bufferLength = 1024*10; // 10M ought to be enough!
            #endregion
            private string messageJ(string message)
            {
                // Send a message to J on server:port and return the string based output.
                // Algo is: Connect if not connected, send message, return reply.
                // Socket code based on:
                // http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.aspx
                bool connected = false;
                if (JSocket == null) {
                        connected = false;
                } else {
                    connected = JSocket.Connected;
                }
                if (! connected) {
                    Print("Not connected, connecting...");
                    IPHostEntry hostEntry = null;
                    hostEntry = Dns.GetHostEntry(server);
                    foreach(IPAddress address in hostEntry.AddressList)
                    {
                        IPEndPoint ipe = new IPEndPoint(address, port);
                        Socket tempSocket = 
                            new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                        tempSocket.Connect(ipe);
                        if(tempSocket.Connected)
                        {
                            JSocket = tempSocket;
                            break;
                        }
                        else
                        {
                            continue;
                        }
                    }
                }
                Byte[] byData = System.Text.Encoding.ASCII.GetBytes(message);
                JSocket.Send(byData);
                Byte[] buffer = new Byte[bufferLength];
                string reply = "";
                int bytes = 0;
                // do {
                    try {
                        bytes = JSocket.Receive(buffer, buffer.Length, 0);
                        reply = reply + System.Text.Encoding.ASCII.GetString(buffer, 0, bytes);
                        // Print("reply was:" + reply);
                    }
                    catch (System.Net.Sockets.SocketException ex) {
                        Print("Socket exception on read:" + ex.SocketErrorCode);
                    }
    
                   // } while (bytes > 0); Loop causes a hang. Do not know why! So made buffer huge.
                return reply;
            }
    
        
            /// <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 = true;
                // disconnect from the socket if it is connected
                bool connected = false;
            }
    
            /// <summary>
            /// Called on each bar update event (incoming tick)
            /// </summary>
            protected override void OnBarUpdate()
            {
                Print(messageJ("hello!"));
            }
    
            #region Properties
            #endregion
        }
    }
    FYI, Jcode for the server is:
    load'socket'
    coinsert 'jsocket'

    connect =: 3 : 0
    NB. close all open sockets
    sdcleanup ''
    NB. create a socket to LISTEN
    SKLISTEN =: 0 pick sdcheck sdsocket''
    NB. bind an address to the SKLISTEN socket
    sdcheck sdbind SKLISTEN ; AF_INET_jsocket_ ; '' ; y
    NB. tell the socket to listen for 1 message at a time
    sdcheck sdlisten SKLISTEN , 1
    NB. poll until connection recieved (must be a better way?)
    smoutput ''
    smoutput ''
    smoutput ''
    smoutput 'Waiting for client to connect...'
    while. ((3$a -: sdc =. sdcheck sdselect'') do. end.
    smoutput 'Connected.'
    NB. accept the connection
    skserver=: 0 pick sdcheck sdaccept SKLISTEN
    NB. close the listening socket
    sdcheck sdclose SKLISTEN
    )

    messageLoop =: 3 : 0
    NB. wait for and echo messages
    NB. if connection drops then try to reestablish
    msg =. ''
    while. msg -.@:-: 'exit' do.
    try. smoutput msg =. ; sdcheck sdrecv skserver,1000,0
    catch.
    smoutput 'Client not connected.'
    connect 1500 NB. go to reconnect if any problems
    end.
    try. sdcheck ('You said:', msg) sdsend skserver , 0
    catch.
    connect 1500
    end.
    end.
    NB. kill the socket
    smoutput 'Client sent exit command ... closing socket.'
    sdcleanup '' NB. only if msg was exit.
    )

    messageLoop ''

    #2
    Hi Matthew - not 100% sure but perhaps Dispose() to clean up resources is what you're after?

    BertrandNinjaTrader Customer Service

    Comment


      #3
      Thanks Betrand, that is exactly what I was looking for :-).

      Comment

      Latest Posts

      Collapse

      Topics Statistics Last Post
      Started by funk10101, Today, 12:02 AM
      1 response
      11 views
      0 likes
      Last Post NinjaTrader_LuisH  
      Started by GLFX005, Today, 03:23 AM
      1 response
      6 views
      0 likes
      Last Post NinjaTrader_Erick  
      Started by nandhumca, Yesterday, 03:41 PM
      1 response
      13 views
      0 likes
      Last Post NinjaTrader_Gaby  
      Started by The_Sec, Yesterday, 03:37 PM
      1 response
      11 views
      0 likes
      Last Post NinjaTrader_Gaby  
      Started by vecnopus, Today, 06:15 AM
      0 responses
      1 view
      0 likes
      Last Post vecnopus  
      Working...
      X