executor.TesterMain.java Source code

Java tutorial

Introduction

Here is the source code for executor.TesterMain.java

Source

package executor;/*
                 * Copyright (c) 2009 Dukascopy (Suisse) SA. All Rights Reserved.
                 *
                 * Redistribution and use in source and binary forms, with or without
                 * modification, are permitted provided that the following conditions are met:
                 *
                 * -Redistribution of source code must retain the above copyright notice, this
                 *  list of conditions and the following disclaimer.
                 *
                 * -Redistribution in binary form must reproduce the above copyright notice,
                 *  this list of conditions and the following disclaimer in the documentation
                 *  and/or other materials provided with the distribution.
                 * 
                 * Neither the name of Dukascopy (Suisse) SA or the names of contributors may
                 * be used to endorse or promote products derived from this software without
                 * specific prior written permission.
                 *
                 * This software is provided "AS IS," without a warranty of any kind. ALL
                 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
                 * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
                 * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. DUKASCOPY (SUISSE) SA ("DUKASCOPY")
                 * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
                 * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
                 * DERIVATIVES. IN NO EVENT WILL DUKASCOPY OR ITS LICENSORS BE LIABLE FOR ANY LOST
                 * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
                 * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
                 * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
                 * EVEN IF DUKASCOPY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
                 */

import accessories.PropertyHandler;
import accessories.StrategyProperties;
import com.dukascopy.api.IStrategy;
import com.dukascopy.api.Instrument;
import com.dukascopy.api.LoadingProgressListener;
import com.dukascopy.api.system.ISystemListener;
import com.dukascopy.api.system.ITesterClient;
import com.dukascopy.api.system.ITesterClient.DataLoadingMethod;
import com.dukascopy.api.system.TesterFactory;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.Future;

/**
 * This small program demonstrates how to initialize Dukascopy tester and start
 * a strategy
 */
public class TesterMain {
    private static final Logger LOGGER = LoggerFactory.getLogger(Main.class);
    private List<Instrument> instrumentsToAdd = new ArrayList<Instrument>();

    public void start(IStrategy strategy) throws Exception {
        // get the instance of the IClient interface
        final ITesterClient client = TesterFactory.getDefaultInstance();
        // set the listener that will receive system events

        if (StringUtils.isNotEmpty(PropertyHandler.getProperty(StrategyProperties.HISTORY_DATE_START))) {
            final SimpleDateFormat dateFormat = new SimpleDateFormat(
                    PropertyHandler.getProperty(StrategyProperties.HISTORY_DATE_FORMAT));
            dateFormat.setTimeZone(
                    TimeZone.getTimeZone(PropertyHandler.getProperty(StrategyProperties.HISTORY_DATE_TIMEZONE)));

            Date dateFrom = dateFormat.parse(PropertyHandler.getProperty(StrategyProperties.HISTORY_DATE_START));
            Date dateTo = dateFormat.parse(PropertyHandler.getProperty(StrategyProperties.HISTORY_DATE_END));
            client.setDataInterval(DataLoadingMethod.DIFFERENT_PRICE_TICKS, dateFrom.getTime(), dateTo.getTime());
        }

        final String strategyName = strategy.getClass().getName();
        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);
                SimpleDateFormat sdf = new SimpleDateFormat(
                        PropertyHandler.getProperty(StrategyProperties.REPORTER_CURRENT_REPORT_FORMAT));
                String propertyFolder = PropertyHandler
                        .getProperty(StrategyProperties.REPORTER_CURRENT_REPORT_OUTPUT_DIRECTORY);
                File reportFile;

                if (Boolean.parseBoolean(
                        PropertyHandler.getProperty(StrategyProperties.REPORTER_CURRENT_REPORT_OVERWRITABLE))) {
                    reportFile = new File(propertyFolder + strategyName + ".html");
                } else {
                    reportFile = new File(
                            propertyFolder + sdf.format(GregorianCalendar.getInstance().getTime()) + ".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("https://www.dukascopy.com/client/demo/jclient/jforex.jnlp",
                PropertyHandler.getProperty(StrategyProperties.CLIENT_USERNAME),
                PropertyHandler.getProperty(StrategyProperties.CLIENT_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);
        }

        // set instruments that will be used in testing
        for (String anInstrument : PropertyHandler.getProperty(StrategyProperties.CLIENT_INSTRUMENTS_USED)
                .split(",")) {
            instrumentsToAdd.add(Instrument.fromString(anInstrument));
        }

        final Set<Instrument> instruments = new HashSet<>();
        instruments.addAll(instrumentsToAdd);

        LOGGER.info("Subscribing instruments...");
        client.setSubscribedInstruments(instruments);
        // setting initial deposit
        client.setInitialDeposit(
                Instrument
                        .fromString(PropertyHandler.getProperty(StrategyProperties.CLIENT_DEPOSIT_INITIAL_CURRENCY))
                        .getSecondaryJFCurrency(),
                Double.parseDouble(PropertyHandler.getProperty(StrategyProperties.CLIENT_DEPOSIT_INITIAL_AMOUNT)));
        // 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");
        // executor.MA_Play strategy = new executor.MA_Play();
        // OrderLifeManagement strategy = new OrderLifeManagement();
        // WinnerStrategy strategy = new WinnerStrategy();
        // ModifiedWinnerStrategy strategy = new ModifiedWinnerStrategy();

        // HourToCsv strategy = new HourToCsv(dateFrom, dateTo);
        client.startStrategy(strategy, new LoadingProgressListener() {
            @Override
            public void dataLoaded(long startTime, long endTime, long currentTime, String information) {
                LOGGER.info(information);
            }

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

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