Dukascopy
 
 
Wiki JStore Search Login

Attention! Read the forum rules carefully before posting a topic.

    Try to find an answer in Wiki before asking a question.
    Submit programming questions in this forum only.
    Off topics are strictly forbidden.

Any topics which do not satisfy these rules will be deleted.

How to detect lost connection fast
 Post subject: How to detect lost connection fast Post rating: 0   New post Posted: Wed 16 Nov, 2011, 19:52 

User rating: 3
Joined: Mon 23 May, 2011, 16:06
Posts: 17
Location: Hungary,
Dear Support Team,

It seems that API invokes IClient.ISystemListener.onDisconnect() approx 60 s after the outage actually started. The following questions are related to possible earlier detection of disconnection and early re-connection trials.

1. Can a trader program check whether the broker connection is actually up or down – prior to 'official' connection status change event (IClient.ISystemListener.onDisconnect())? What would you suggest (e.g. IEngine.getOrders() can't work without a live connection)?

2. What happens if a trader program calls IClient.reconnect() before API invoking onDisconnect(), when connection is still up officially?

Thank you. Regards,
Argiris


 
 Post subject: Re: How to detect lost connection fast Post rating: 0   New post Posted: Thu 17 Nov, 2011, 18:01 
User avatar

User rating:
Joined: Fri 31 Aug, 2007, 09:17
Posts: 6139
Argiris wrote:
It seems that API invokes IClient.ISystemListener.onDisconnect() approx 60 s after the outage actually started.
In general it is not the case - it depends on the disconnection reason.
Argiris wrote:
1. Can a trader program check whether the broker connection is actually up or down – prior to 'official' connection status change event (IClient.ISystemListener.onDisconnect())? What would you suggest (e.g. IEngine.getOrders() can't work without a live connection)?
As an alternative to handling IClient.onDisconnect you can check if some action executes in time. You can also consider calling IHistory.getLastTick. Consider the following strategy which checks if particular tasks get executed on time:
package jforex.test;

import com.dukascopy.api.*;

public class HistoryThreadTest4 implements IStrategy {

   private IConsole console;
   private IHistory history;
   private IEngine engine;

   @Configurable("patience (in seconds)")
   public int patience = 3;

   @Override
   public void onStart(IContext context) throws JFException {
      this.console = context.getConsole();
      this.history = context.getHistory();
      this.engine = context.getEngine();

      print("test success (execute immediately)");

      boolean onTime1= launchTask(new IFunction() {

         @Override
         public void execute() throws InterruptedException {
            try {
               console.getOut().println(" last tick: " + history.getLastTick(Instrument.EURUSD)
                     + " active order count: " + engine.getOrders().size());               
            } catch (JFException e) {
               console.getErr().println("-1 " + e);
            }
         }

      }, patience);

      print("test fail (execute for patience + 2 secs)");

      boolean onTime2 = launchTask(new IFunction() {

         @Override
         public void execute() throws InterruptedException {
            for (int i = 0; i < patience + 3; i++) {
               Thread.sleep(1000);
               try {
                  console.getOut().println(i + " last tick: " + history.getLastTick(Instrument.EURUSD)
                        + " active order count: " + engine.getOrders().size());
               } catch (JFException e) {
                  console.getErr().println("-1 " + e);
               }
            }
         }

      }, patience);

      print("Task 1 on time: "+onTime1 +". Task 2 on time: " + onTime2);
      context.stop();

   }

   private interface IFunction {
      public void execute() throws InterruptedException;
   }

   /**
    * Launches a task in a separate thread with expiry time
    *
    * @param function
    *            task
    * @param expiryTime
    *            expiry time in seconds
    * @return true if task succeeded to execute before the expiration time
    */
   private boolean launchTask(final IFunction function, int expiryTime) {

      long startTime = System.currentTimeMillis();
      Thread t = new Thread(new Runnable() {
         @Override
         public void run() {
            try {
               function.execute();
            } catch (InterruptedException e) {
               console.getErr().println(Thread.currentThread().getName() + " got interrupted!");
            }
         }
      });
      t.start();

      // loop until MessageLoop thread exits
      while (t.isAlive()) {
         // Wait maximum of 1 second for function thread to finish.
         try {
            t.join(1000);
         } catch (InterruptedException e) {
            console.getErr().println(e);
         }
         if (((System.currentTimeMillis() - startTime) > expiryTime * 1000) && t.isAlive()) {
            print(Thread.currentThread().getName() + " expired!");
            t.interrupt();
            // wait indefinitely for the thread to get interrupted
            try {
               t.join();
            } catch (InterruptedException e) {
               console.getErr().println(e);
            }
            return false;
         }

      }
      return true;
   }

   @Override
   public void onTick(Instrument instrument, ITick tick) throws JFException {
   }

   @Override
   public void onBar(Instrument instrument, Period period, IBar askBar, IBar bidBar) throws JFException {
   }

   @Override
   public void onMessage(IMessage message) throws JFException {
   }

   @Override
   public void onAccount(IAccount account) throws JFException {
   }

   @Override
   public void onStop() throws JFException {
   }

   private void print(Object o) {
      console.getOut().println(o);
   }

}

Attachment:
HistoryThreadTest4.java [3.36 KiB]
Downloaded 268 times

Argiris wrote:
2. What happens if a trader program calls IClient.reconnect() before API invoking onDisconnect(), when connection is still up officially?
This will create no negative effect - if the connection is there then it will take no action, if not - will try to reconnect.


 
 Post subject: Re: How to detect lost connection fast Post rating: 0   New post Posted: Fri 18 Nov, 2011, 10:37 

User rating: 3
Joined: Mon 23 May, 2011, 16:06
Posts: 17
Location: Hungary,
Guys,

I've thought that IHistory.getLastTick() turns to local cache. In fact, it must turn to the remote rate server instead, as it is not sure that the most recent tick found in the local cache is the last tick. So, you are right, getLastTick() is suitable for checking the connection.

Thank you for the answer, it's informative, and the attached code too.

Regards,
Argiris

PS. Could you also take a look at the other 'how-to' topic regarding connection I've recently launched.


 

Jump to:  

  © 1998-2025 Dukascopy® Bank SA
On-line Currency forex trading with Swiss Forex Broker - ECN Forex Brokerage,
Managed Forex Accounts, introducing forex brokers, Currency Forex Data Feed and News
Currency Forex Trading Platform provided on-line by Dukascopy.com