示例#1
0
        void ReconnectToGateway(object p_object)
        {
            Gateway gateway = (Gateway)p_object;
            int nMaxRetry = 3;
            int nConnectionRetry = 0;
            do
            {
                try
                {
                    nConnectionRetry++;
                    IBrokerWrapper ibWrapper = null;
                    if (!Controller.IsRunningAsLocalDevelopment())
                    {
                        ibWrapper = new BrokerWrapperIb();      // recreate IB wrapper at every Connection try. It is good this way.
                    }
                    else
                    {
                        if (Utils.IsInRegularUsaTradingHoursNow(TimeSpan.FromDays(3)))
                            ibWrapper = new BrokerWrapperIb();    // when USA market is open
                        else
                            ibWrapper = new BrokerWrapperYF();     // Before market open, or After market close. Simulated real time price is needed to determine current portfolio $size.
                    }
                    if (!ibWrapper.Connect(gateway.SocketPort, gateway.BrokerConnectionClientID))
                    {
                        Utils.Logger.Error($"Timeout or other Error (like serverVersion=14). Cannot connect to IbGateway {gateway.GatewayUser} on port { gateway.SocketPort}. Trials: {nConnectionRetry}/{nMaxRetry}");
                        continue;
                    }

                    StrongAssert.Equal(ibWrapper.IbAccountsList, gateway.VbAccountsList, Severity.ThrowException, $"Expected IbAccount {gateway.VbAccountsList} is not found: { ibWrapper.IbAccountsList}.");

                    // after this line, we are really connected
                    gateway.BrokerWrapper = ibWrapper;
                    gateway.IsConnected = true;

                    string warnMessage = (ibWrapper is BrokerWrapperIb) ? "" : "!!!WARNING. Fake Broker (YF!). ";
                    Utils.Logger.Info($"{warnMessage}Gateway {ibWrapper} is connected. User {gateway.GatewayUser} acc {gateway.VbAccountsList}.");
                    Console.WriteLine($"*{warnMessage}Gateway user {gateway.GatewayUser} acc {gateway.VbAccountsList} connected.");
                    return;

                    //client.reqAccountSummary(9001, "All", AccountSummaryTags.GetAllTags());
                    /*** Subscribing to an account's information. Only one at a time! ***/
                    //Thread.Sleep(6000);

                }
                catch (Exception e)
                {
                    //If IBGateways doesn't connect: Retry the connection about 3 times, before Exception. So, so this problem is an Expected problem if another try to reconnect solves it.
                    Utils.Logger.Info(e, $"Exception in ReconnectToGateway()-user:{gateway.GatewayUser}: nRetry:{nConnectionRetry} : Msg:{e.Message}");
                    if (nConnectionRetry >= nMaxRetry)
                    {
                        Utils.Logger.Info("GatewaysWatcher:ReconnectToGateway(). This gateway failed after many retries. We can send HealthMonitor message here, but better at a higher level if the second Gateway fails too.");
                        //HealthMonitorMessage.SendException($"ReConnectToGateway Thread: nMaxRetry: {nMaxRetry}", e, HealthMonitorMessageID.ReportErrorFromVirtualBroker);  // the higher level ReconnectToGateways() will send the Error to HealthMonitor
                        throw; // without IB connection, we can crash the App. No point to continue. we cannot recover.
                    }
                    else
                    {
                        // if we do retry, wait 10 seconds here. Maybe IB Gateway is will reconnect later
                        Thread.Sleep(10000);
                    }
                }
            } while (nConnectionRetry < nMaxRetry);
        }
示例#2
0
        internal void TestVbGatewayConnection()
        {

            Utils.Logger.Debug("TestVbGatewayConnection() BEGIN");
            // start c:\Jts\StartIBGateway.bat 
            // IBGateway this version works: Build 952.1a, Aug 18, 2015 3:38:07 PM  // c:\Jts\StartIBGateway.bat 
            // this works too. Stable: Build 952.2h, Jan 29, 2016 4:40:48 PM        // c:\Jts\952\jars\StartIBGateway.bat , or simple "javaw.exe -cp jts.jar;total.jar ibgateway.GWClient" command line works
            // Latest (not Stable) doesn't work c:\Jts\955\jars\StartIBGateway.bat  or simple "javaw.exe -cp jts4launch.jar;total.jar ibgateway.GWClient" command line doesn't work, although the ibgateway.GWClient is there. Buggy.

            // see for samples:  "g:\temp\_programmingTemp\TWS API_972.12(2016-02-26)\samples\CSharp\IBSamples\Program.cs" 

            BrokerWrapperIb testImpl = new BrokerWrapperIb();
            EClientSocket client = testImpl.ClientSocket;
            
            int portID = (int)GatewayUserPort.GyantalMain;      // the IBGateways ports on Release Linux and Developer Windows local should be the same.
            client.eConnect("127.0.0.1", portID, 0, false);     // it uses connectionID=0, which may be not good. Real VBroker uses 41 and 42 userIDs.

            //Create a reader to consume messages from the TWS. The EReader will consume the incoming messages and put them in a queue
            var reader = new EReader(client, testImpl.Signal);
            reader.Start();
            //Once the messages are in the queue, an additional thread need to fetch them
            new Thread(() =>
            {
                while (client.IsConnected())
                {
                    testImpl.Signal.waitForSignal();
                    reader.processMsgs();
                }
            })
            { IsBackground = true }.Start();

            /*************************************************************************************************************************************************/
            /* One (although primitive) way of knowing if we can proceed is by monitoring the order's nextValidId reception which comes down automatically after connecting. */
            /*************************************************************************************************************************************************/
            while (testImpl.NextOrderId <= 0) { }

            Console.WriteLine("Connection seems to be OK. Requesting Account Summary...");

            /*** Requesting managed accounts***/
            client.reqManagedAccts();
            /*** Requesting accounts' summary ***/
            Thread.Sleep(2000);
            client.reqAccountSummary(9001, "All", AccountSummaryTags.GetAllTags());
            /*** Subscribing to an account's information. Only one at a time! ***/

            Thread.Sleep(6000);
            Console.WriteLine("Disconnecting...");
            client.eDisconnect();
        }