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.

getBars error
 Post subject: getBars error Post rating: 0   New post Posted: Wed 01 Jun, 2011, 19:29 

User rating: -
For several weeks I have been testing a robot which uses getBars to load historical data. It was working fine until Monday this week (May 30), when it suddendly refused to run.
I cleaned out my cache, and even set up a new demo account, but keep getting the same error.

I have tried different time parameters etc but keep getting the same error no matter what I try. To eliminate all possible coding errors, I even tried using the function in your demonstration "MA_Play" code example (included in the JForex download), but it still fails:

List<IBar> askBars = MA_Play.history.getBars(Instrument.EURUSD, Period.ONE_MIN, OfferSide.BID, Filter.NO_FILTER, 10, 1306951548128L, 0);
(the 1306951548128L time parameter is from today - I have tried many different times but always the same result)

raises the exception:
Exception in thread "main" java.lang.NullPointerException
at singlejartest.Main.main(Main.java:138)


Again, getBars WAS WORKING a few days ago - I made no changes to it!


 
 Post subject: Re: getBars error Post rating: 0   New post Posted: Thu 02 Jun, 2011, 12:11 

User rating: -
Dear Support,

In trying to find a workaround for this bug, I tried the asynchronous readBars method. It turns out that BOTH getBars and readBars only work if the requested data is within the same calendar day. As soon as I try to read across two calendar days in the same method calls, they both fail.
The workaround works - it's not difficult to code reading data one day at a time - although annoying.

I wonder if this is a deliberate feature to limit load on busy history servers, or a bug?

Thank you
Hecate


 
 Post subject: Re: JFOREX-3027 getBars error Post rating: 0   New post Posted: Mon 06 Jun, 2011, 13:47 
User avatar

User rating:
Joined: Fri 31 Aug, 2007, 09:17
Posts: 6139
There are multiple preconditions for MA_Play.history.getBars to work from strategy tester:
    a) MA_Play has to have a public field history that has to be assigned in the onStart method (I believe you have already done such a modification of MA_Play).
    b) The instance of MA_Play has to have onStart already executed.
    c) Your time value has to be greater than the current time of the running strategy and within the timeframe of the strategy. Say timeOfLastBar= 1306951548128L has to meet time restrictions: startTime < currentTime < timeOfLastBar < endTime.
So the idea is that you call MA_Play.history.getBars from LoadingProgressListener's method dataLoaded once the check of c) succeeds.

Consider the following modification of TesterMain:

package singlejartest;

import com.dukascopy.api.*;
import com.dukascopy.api.system.ISystemListener;
import com.dukascopy.api.system.ITesterClient;
import com.dukascopy.api.system.TesterFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.TimeZone;
import java.util.concurrent.Future;

/**
 * This small program demonstrates how to initialize Dukascopy tester and start a strategy
 */
@RequiresFullAccess
public class TesterMainHistoryBars {
   private static final Logger LOGGER = LoggerFactory.getLogger(Main.class);

   // url of the DEMO jnlp
   private static String jnlpUrl = "https://www.dukascopy.com/client/demo/jclient/jforex.jnlp";
   // user name
   private static String userName = "USERNAME";
   // password
   private static String password = "PASSWORD";

   public static void main(String[] args) throws Exception {
      // get the instance of the IClient interface
      final ITesterClient client = TesterFactory.getDefaultInstance();
      // set the listener that will receive system events
      client.setSystemListener(new ISystemListener() {
         @Override
         public void onStart(long processId) {
            LOGGER.info("Strategy started: " + processId);
         }

         @Override
         public void onStop(long processId) {
            LOGGER.info("Strategy stopped: " + processId);
            File reportFile = new File("C:\\temp\\report.html");
            try {
               client.createReport(processId, reportFile);
            } catch (Exception e) {
               LOGGER.error(e.getMessage(), e);
            }
            if (client.getStartedStrategies().size() == 0) {
               System.exit(0);
            }
         }

         @Override
         public void onConnect() {
            LOGGER.info("Connected");
         }

         @Override
         public void onDisconnect() {
            // tester doesn't disconnect
         }
      });

      LOGGER.info("Connecting...");
      // connect to the server using jnlp, user name and password
      // connection is needed for data downloading
      client.connect(jnlpUrl, userName, password);

      // wait for it to connect
      int i = 10; // wait max ten seconds
      while (i > 0 && !client.isConnected()) {
         Thread.sleep(1000);
         i--;
      }
      if (!client.isConnected()) {
         LOGGER.error("Failed to connect Dukascopy servers");
         System.exit(1);
      }

      // custom historical data
      String dateFromStr = "05/25/2011 00:00:00";
      String dateToStr = "05/26/2011 00:00:00";
      String dateOfLastBar = "05/25/2011 12:00:00";

      final SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
      dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));

      Date dateFrom = dateFormat.parse(dateFromStr);
      Date dateTo = dateFormat.parse(dateToStr);
      final Date dateMid = dateFormat.parse(dateOfLastBar);

      client.setDataInterval(Period.THIRTY_MINS, OfferSide.BID, ITesterClient.InterpolationMethod.CLOSE_TICK, dateFrom.getTime(),
            dateTo.getTime());

      // set instruments that will be used in testing
      Set<Instrument> instruments = new HashSet<Instrument>();
      instruments.add(Instrument.EURUSD);
      LOGGER.info("Subscribing instruments...");
      client.setSubscribedInstruments(instruments);
      // setting initial deposit
      client.setInitialDeposit(Instrument.EURUSD.getSecondaryCurrency(), 50000);
      // load data
      LOGGER.info("Downloading data");
      Future<?> future = client.downloadData(null);
      // wait for downloading to complete
      future.get();
      // start the strategy
      LOGGER.info("Starting strategy");

      client.startStrategy(new MA_Play(), new LoadingProgressListener() {

         private boolean barsPrinted = false;

         @Override
         public void dataLoaded(long startTime, long endTime, long currentTime, String information) {
            LOGGER.info(information);
            //we cannot retrieve bars from future and we don't want to print the bars twice
            if (currentTime < dateMid.getTime() || barsPrinted)
               return;

            MA_Play maPlay = getStartedStrategy(MA_Play.class);
            if (maPlay == null)
               return;

            try {
               List<IBar> bars = maPlay.history.getBars(Instrument.EURUSD, Period.ONE_MIN, OfferSide.BID, Filter.NO_FILTER, 10,
                     dateMid.getTime(), 0);
               LOGGER.info("___________________");
               for (IBar bar : bars) {
                  LOGGER.info("Bar time: " + dateFormat.format(bar.getTime()) + ", close price: " + bar.getClose());
               }
               LOGGER.info("___________________");
               barsPrinted = true;
            } catch (JFException e) {
               LOGGER.error("Exception on dataLoaded: " + e.getMessage());
            }
         }

         /**
          * @param T class of the strategy
          * @return ITesterClient's first started strategy of type T or null
          */
         private <T extends IStrategy> T getStartedStrategy(Class<T> T) {
            if (client.getStartedStrategies().size() == 0)
               return null;
            for (IStrategy s : client.getStartedStrategies().values()) {
               @SuppressWarnings("unchecked")
               T strategy = (T) s;
               if (strategy != null)
                  return strategy;
            }
            return null;
         }

         @Override
         public void loadingFinished(boolean allDataLoaded, long startTime, long endTime, long currentTime) {

         }

         @Override
         public boolean stopJob() {
            return false;
         }
      });
      // now it's running

   }
}

If this example doesn't help you solve your problem, please do provide a code fragment which is making the call of MA_Play.history.getBars.


 

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