Maven tutorial

Use with Maven in NetBeans

This article describes how to create a JForex-SDK project as an Apache Maven project in NetBeans IDE. The main advantage of using Maven is that in order to switch to the latest JForex-SDK version one only needs to change the DDS2-jClient-JForex version number in the pom.xml configuration file rather than download the zip file and import it as a new project. See Strategy development in NetBeans for more information on working with NetBeans and JForex-SDK.

Check configuration

Before creating a Maven project in NetBeans, one needs to verify if NetBeans already has Maven plugin installed. For the latest versions of NetBeans the Maven plugin comes bundled in by default, as it is in our case. For older NetBeans versions one can install the plugin by choosing Tools -> Plugins -> Available Plugins. If you are using proxy to access the internet, then the proxy settings should be configured in NetBeans through Tools -> Options -> General -> Proxy Settings.

Create a Maven Project

In order to create a Maven project in the NetBeans, we need only one file, namely, a project object model (POM) file. The POM file used in this tutorial includes all necessarily properties to build the JForex-SDK project and work with the public Dukascopy Maven repository. Here are the contents of POM file we are using in this example:

<?xml version="1.0" encoding="UTF-8"?>

<project>
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.dukascopy.dds2</groupId>
    <artifactId>JForex-SDK-Local-Maven</artifactId>
    <version>1.0</version>
    <name>JForex-SDK-MAVEN</name>
    <description></description>
    <organization>
        <name>DUKASCOPY (Suisse) SA</name>
        <url>http://www.dukascopy.com</url>
    </organization>
    <repositories>
        <repository>
            <id>dc_public</id>
            <name>Dukascopy public repository</name>
            <url>http://www.dukascopy.com/client/jforexlib/publicrepo/</url>
        </repository>
    </repositories>
    <dependencies>
        <dependency>
            <groupId>com.dukascopy.dds2</groupId>
            <artifactId>DDS2-jClient-JForex</artifactId>
            <version>2.18</version>
        </dependency>
    </dependencies>
    <build>
        <sourceDirectory>src</sourceDirectory>
        <finalName>JForex-SDK</finalName>
    </build>
</project>

Consider the following steps:

  • Make a new file, name it pom.xml and paste the to it the upper given contents. Put this file in an empty directory.

  • Open NetBeans and press Ctrl+Shift+O (or choose File -> Open Project) to open a new project. Locate for the directory in which the pom.xml file is located. NetBeans will automatically recognize this directory as a Maven project. Select the project and choose Open Project. NetBeans will create a new Maven project called JForex-SDK-Maven.

  • Right-click the project in the Projects window and choose Clean and Build. NetBeans will build the project.

    1

  • One can expand the project node and see that the project already has dependencies. These dependencies (libraries) are stored in the public Maven repository of Dukascopy.

    2

Create and Run a Program

To create a program follow these steps:

  • We need to create a folder where to store java packages and files for the project. Right-click the root node of the project and choose New-Other. NetBeans will open a New File wizard. Choose Other from Categories and Folder from File Types.

    3

  • In the next step of the wizard name the folder src. Choose Finish to create the folder.

    4

  • Expand the root node of the project in the Projects window. One can see that the NetBeans has added a new folder called Source Packages where one can create java packages and files.

    5

  • To run a strategy in NetBeans we will create a new java class called Main. At first, create a package where to store the Main.java class. Right-click the Source Packages node of the project and choose New-Java Package. Give a name utils for the package and choose Finish. A new package is created.

    6

  • Now, create a class which will be used to run jForex strategies (demo). Right-click the utils package node in the Projects window and choose New-Java Class. Type Main for a Class Name and choose Finish.

    7

  • NetBeans opens the Main.java class file in the editor. Replace the default code with the following one and save the class file:

/*
 * 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.
 */
package utils;

import com.dukascopy.api.*;
import com.dukascopy.api.system.ClientFactory;
import com.dukascopy.api.system.IClient;
import com.dukascopy.api.system.ISystemListener;
import java.util.HashSet;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * This small program demonstrates how to initialize Dukascopy client and start a strategy
 */
public class Main {
    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 = "MY_USERNAME";
    //password
    private static String password = "MY_PASSWORD";

    public static void main(String[] args) throws Exception {
        //get the instance of the IClient interface
        final IClient client = ClientFactory.getDefaultInstance();
        //set the listener that will receive system events
        client.setSystemListener(new ISystemListener() {
            private int lightReconnects = 3;

            @Override
            public void onStart(long processId) {
                LOGGER.info("Strategy started: " + processId);
            }

            @Override
            public void onStop(long processId) {
                LOGGER.info("Strategy stopped: " + processId);
                if (client.getStartedStrategies().size() == 0) {
                    System.exit(0);
                }
            }

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

            @Override
            public void onDisconnect() {
                LOGGER.warn("Disconnected");
                if (lightReconnects > 0) {
                    client.reconnect();
                    --lightReconnects;
                } else {
                    try {
                        //sleep for 10 seconds before attempting to reconnect
                        Thread.sleep(10000);
                    } catch (InterruptedException e) {
                        //ignore
                    }
                    try {
                        client.connect(jnlpUrl, userName, password);
                    } catch (Exception e) {
                        LOGGER.error(e.getMessage(), e);
                    }
                }
            }
        });

        LOGGER.info("Connecting...");
        //connect to the server using jnlp, user name and password
        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);
        }

        //subscribe to the instruments
        Set<Instrument> instruments = new HashSet<Instrument>();
        instruments.add(Instrument.EURUSD);
        LOGGER.info("Subscribing instruments...");
        client.setSubscribedInstruments(instruments);

        //workaround for LoadNumberOfCandlesAction for JForex-API versions > 2.6.64
        Thread.sleep(5000);

        //start the strategy
        LOGGER.info("Starting strategy");
        client.startStrategy(new IStrategy() {
            public void onStart(IContext context) throws JFException {
                context.getConsole().getOut().println("Hello World!");
            }
            public void onTick(Instrument instrument, ITick tick) throws JFException {}
            public void onBar(Instrument instrument, Period period, IBar askBar, IBar bidBar) throws JFException {}
            public void onMessage(IMessage message) throws JFException {}
            public void onAccount(IAccount account) throws JFException {}
            public void onStop() throws JFException {}
        } );
        //now it's running
    }
}
  • Find and replace MY_USERNAME and MY_PASSWORD with real ones.
//user name
private static String userName = "MY_USERNAME";
//password
private static String password = "MY_PASSWORD";
  • Right-click the project node in the Projects window and choose Clean and Build.

Test the Program

Now, when the project is built, run the strategy by right-clicking the Main.java class' node in the Projects window and choosing Run File. Consider the following output:

8

Keep Dependencies up to Date

As mentioned in the introduction, the main goal of using Maven projects is to keep the dependencies of a Maven project up to date. Till this point of the tutorial, we used version 2.18 of JForex-SDK.

9

Now we will try to update the version to 2.20. To do this, open the pom.xml file and change the content of a version tag to 2.20:

...
<dependency>
    <groupId>com.dukascopy.dds2</groupId>
    <artifactId>DDS2-jClient-JForex</artifactId>
    <version>2.20</version>
</dependency>
...

One can check for the latest versions of JForex-SDK and JForex API in the public Maven repository of Dukascopy: http://www.dukascopy.com/client/jforexlib/publicrepo/com/dukascopy/dds2/DDS2-jClient-JForex/ http://www.dukascopy.com/client/jforexlib/publicrepo/com/dukascopy/api/JForex-API/

The information on this web site is provided only as general information, which may be incomplete or outdated. Click here for full disclaimer.