How To Do Algorithmic Trading On Dukascopy JForex?

In this post I start from the very beginning and show you how to start developing algorithmic trading strategies on Dukascopy JForex platform. Do you read my Forex Signals 2.0 Blog regularly? Have you ever tried Dukascopy JForex platform? In this post I will discuss in detail how to build algorithmic trading strategies on Dukascopy JForex platform using Java. Java is a very powerful modern object oriented language that is being widely used all over the industry. Java provides us with most powerful machine learning and artificial intelligence tools that we lack in MQL5. Java is a being widely used in the industry. It is an enterprise level language. It has many libraries that we can use in our algorithmic trading strategies. Deep learning is a piece of cake when it comes to Java. It has powerful deep learning library DLJ4 that can be used for building very powerful algorithmic trading strategies. Java has multi threading available with it. Multi threading means you can use parallel programming when building algorithmic trading strategies. Java is a very powerful language that will allow you to build robust trading strategies.

If you are new to Java, I have developed a few courses on Java especially for traders. First is the basic Java For Traders. In this Java For Traders course, I teach you the basics of Java. In the second course, Java Machine Learning For Traders, I teach you how to build machine learning predictive algorithms using Java. Third course is Java Deep Learning For Traders. Deep learning is the most important development that has taken place in the filed of Artificial Intelligence. It has revolutionized what can be done with Artificial Intelligence. Today deep learning is being used extensively in computer vision, robotics, autonomous car driving, health care etc. Deep ;learning has a lot of potential for traders. I recommend that you learn deep learning. This course Java Deep Learning For Traders will teach you how to do it. The last course is Java For Algorithmic Trading. This course ties everything that you learned in the previous three courses. We build algorithmic trading strategies using Java in this course. Learning Java will help you a lot as a trader. You can use Java in other fields as well that includes Android App Development which is another big field.

What Is Dukascopy Visual Forex?

Dukascopy has a flash program Visual Forex that allows you to build algorithmic trading strategies for its JForex platofrm without knowing any Java. According to Dukascopy, Visual JForex is a comprehensive solution to designing, building running and testing algorithmic trading strategies. Front end is a web based flash user interface with Java backend. You connect different blocks to build your automated forex trading system. You need to have flash plugin installed on your browser for using Visual JForex. Now you can well imagine the limitations of using Visual JForex. Using Visual JForex, you can only build simple forex trading strategies using standard indicators like moving averages, MACD, RSI etc. But if you want to use machine learning and deep learning, then there is no possibility of doing that on this platform. As said above it is a good idea to learn Java. Take my course Java For Traders. I take you by hand and teach you the basics of Java in very simple terms. You don’t need any previous programming experience. Our ultimate goal is to use Artificial Intelligence algorithms in building powerful algorithmic trading strategies. You can download Visual JForex Guide which is a 50 page PDF and go through it and see what you can do with it.

Visual JForex

How To Build A Trading Strategy on Dukascopy JForex?

First you should download Java Run Time environment JRE. Now if you don’t have JForex platform installed, you should first download it. Opening Dukascopy demo account is very easy. Just do that and download JForex and then install it on your computer. It will take hardly 5 minutes. Power of JForex lies in its Java backend. Open the JForex platform. Open Tools menu and click on Strategy Editor. This will open a second window in JForex platform. Click on new and a new strategy window opens. Below is the code that is pre-populating the strategy window.

package jforex;   // A

import java.util.*; //B

import com.dukascopy.api.*; //C

public class Strategy implements IStrategy {  //D
    private IEngine engine;
    private IConsole console;
    private IHistory history;
    private IContext context;
    private IIndicators indicators;
    private IUserInterface userInterface;  //D
    
    public void onStart(IContext context) throws JFException { //E
        this.engine = context.getEngine();
        this.console = context.getConsole();
        this.history = context.getHistory();
        this.context = context;
        this.indicators = context.getIndicators();
        this.userInterface = context.getUserInterface();  //E
    }

    public void onAccount(IAccount account) throws JFException {  //F
    }

    public void onMessage(IMessage message) throws JFException {  //G
    }

    public void onStop() throws JFException { //H
    }

    public void onTick(Instrument instrument, ITick tick) throws JFException { //I
    }
    
    public void onBar(Instrument instrument, Period period, IBar askBar, IBar bidBar) 
throws JFException {   //J
    }
}

Above is the general template for JForex Trading Strategy Java Code. I need to discuss the above code and explain it in detail so that we can start developing new strategies. So let’s start. A has package  jforex. First what is a package. Package is a collection of similar java classes, sub-packages and interfaces also known as GUIs. Packages can be 2 types built-in and user defined. For example Swing is a built-in package that allows you design and build latest types of GUIs on different devices. Using this package jforex statement ensures that our trading strategy is included in this package. So package jforex is a user defined package that we can modify, delete and edit according to our needs.

In B, we use this statement import java.util.* where * is a wild card that tells the compiler to import all the classes of java.util package. This package java.util contains a number of utility classes and interfaces. Important classes included in this package are AbstractList, HashMap, Vector, Date, Timezone etc. It also contains the Random class. This Random class is very important when we want to introduce randomness in our models. It can be used to build monte carlo trading simulation models. This is a built-in class. By importing java.util.* we are infact importing all the classes and interfaces that are included in this package. In C, we import com.dukascopy.api.* where * is the wild card once again that allows us to import all the classes and interfaces in this package.

In D, we define IStrategy Inferface. IStrategy interface has six call methods that you can check in D. All strategies should implement this interface. First method that this interface calls is OnStart() as in E. In OnStart(), all variables are initialized. In F, we update the onAccount(). Interface IAccount() provides us with a number of methods that allow us to update the current account equity, leverage etc. We can use getAccount(), getEquity(), getUseOfLeverage(), getCreditLine() methods etc.

In G, onMessage() callback method is invoked whenever there is a new order or a change in existing open order. Using onMessage() callback method allows us to manage Order State which can be OPENED, CREATED, CLOSED, FILLED and CANCELLED. You can check the Market Order State Diagramm in Strategy API. In H, onStop() callback method is invoked. This callback method is invoked when the trading strategy is stopped depending on the logic used in the trading strategy which means closing all active orders, removing the created objects and GUI.

In I, onTick() callback method is invoked. In an EA, onTick() event triggers the trading strategy on receiving each incoming tick. You will need to invoked tick filtering so that you can avoid it. Tick filtering will allows you to use specific time period instead of each tick. In J, onBar() event is triggered at the end when each bar is finished for that time period. Just like tick filtering you will need bar filtering.

How To Build An Indicator On Dukcascopy JForex?

You can also build custom indicator on JForex. As said above Visual JForex can also be used to build custom indicators. If you want to use machine learning and deep learning than you will have to use the following indicator template code to build custom indicators. Below is the java template for building an indicator on JForex.

package jforex;

import com.dukascopy.api.indicators.*;

public class Indicator implements IIndicator { //A
    private IndicatorInfo indicatorInfo;
    private InputParameterInfo[] inputParameterInfos;
    private OptInputParameterInfo[] optInputParameterInfos;
    private OutputParameterInfo[] outputParameterInfos;
    private double[][] inputs = new double[1][];
    private int timePeriod = 2;
    private double[][] outputs = new double[1][]; //A
    
    public void onStart(IIndicatorContext context) { //B
        indicatorInfo = new IndicatorInfo("EXAMPIND", "Sums previous values", "My indicators",
                false, false, false, 1, 1, 1);
        inputParameterInfos = new InputParameterInfo[] { //C
            new InputParameterInfo("Input data", InputParameterInfo.Type.DOUBLE)
        };
        optInputParameterInfos = new OptInputParameterInfo[] { //D
            new OptInputParameterInfo("Time period", OptInputParameterInfo.Type.OTHER,
                new IntegerRangeDescription(2, 2, 100, 1))
        };
        outputParameterInfos = new OutputParameterInfo[] { //E
            new OutputParameterInfo("out", OutputParameterInfo.Type.DOUBLE,
                OutputParameterInfo.DrawingStyle.LINE)
        };
    }

    public IndicatorResult calculate(int startIndex, int endIndex) { //F
        //calculating startIndex taking into account lookback value
        if (startIndex - getLookback() < 0) { startIndex = getLookback(); } 
if (startIndex > endIndex) {
            return new IndicatorResult(0, 0);
        }
        int i, j;
        for (i = startIndex, j = 0; i <= endIndex; i++, j++) { double value = 0; 
for (int k = timePeriod; k > 0; k--) {
                value += inputs[0][i - k];
            }
            outputs[0][j] = value;
        }
        return new IndicatorResult(startIndex, j);
    }

    public IndicatorInfo getIndicatorInfo() { //G
        return indicatorInfo;
    }

    public InputParameterInfo getInputParameterInfo(int index) { //H
        if (index < inputParameterInfos.length) {
            return inputParameterInfos[index];
        }
        return null;
    }

    public int getLookback() {  //I
        return timePeriod;
    }

    public int getLookforward() { //J
        return 0;
    }

    public OptInputParameterInfo getOptInputParameterInfo(int index) { //K
        if (index < optInputParameterInfos.length) {
            return optInputParameterInfos[index];
        }
        return null;
    }

    public OutputParameterInfo getOutputParameterInfo(int index) { //L
        if (index < outputParameterInfos.length) {
            return outputParameterInfos[index];
        }
        return null;
    }

    public void setInputParameter(int index, Object array) { //M
        inputs[index] = (double[]) array;
    }

    public void setOptInputParameter(int index, Object value) { //N
        timePeriod = (Integer) value;
    }

    public void setOutputParameter(int index, Object array) { //O
        outputs[index] = (double[]) array;
    }
}

Above is the general java template for building indicators on JForex. I am interested in developing a type 2 fuzzy logic indicator using Java library Juzzy. Fuzzy logic is a powerful mathematical model that allows you to model imprecise and vague information. This is precisely what we have when we are dealing. We have price and a number of indicators that are based on price. We have to use them and decide when to buy/sell. So we have very vague and im precise information. If you are new to fuzzy logic, you can take a look at my course, Fuzzy Logic For Traders. Candlestick patterns are imprecise and vague. We can combine fuzzy logic with data mining and develop a predicting algorithm that can predict the turning points in the market. You can read this post on how to develop a candlestick patterns fuzzy logic indicators.

Coming back to the above code, we start with package jforex which I have explained above. Then we import com.dukascopy.api.indicators.*. In A, we implement IIndicator Interface. In this indicator class we initialize functions plus set inout and output arrays. In B, we call onStart() method which is used to create and fill methods.

How To Use Eclipse With JForex?

Eclipse is a powerful IDE (Integrated Development Environment). Download JForex SDK. It is a zip file. Unzip it. Now open Eclipse. Click on New Project and select an existing Maven Project. Import the JForex SDK. This is as simple as that. Just look for the main.java file and change the username and password. Now when the code in Eclipse, it will automatically connect with the JForex platform.

How To Use NetBeans With JForex?

You can also use NetBeans which is another powerful IDE. NetBeans is provided by Oracle the owner of Java programming language. Just click on New Project and import the JForex unzipped SDK. NetBeans is a bit resource intensive. You need to at least 4 GB RAM if you want to use it. I have only 2 GB RAM on my laptop. When other programs are open, I find NetBeans a bit slow and sluggish. Maven project allows java projects to have similar file structures. JForex SDK is a maven project. It means that things are standardized.

How To Connect Java With R and Python?

R is a powerful language developed solely for the purpose of doing statistical analysis and data science. It has now over  10,000 statistics and data science packages. Sometimes you will find limited working in Java when it comes to doing statistical analysis. In this case we can use rJava package. rJava package allows us to call R functions right from within Java code. Java can do many things. It can build powerful android apps and many other things but it is catching up when it comes to data science and statistics. In this year alone, I have seen more than a dozen new ebook on how to do data science, machine learning and deep learning with Java. So it is catching up fast with R and Python. We can also use Jython. Jython allows you to integrate Python with Java platform. When you cannot find a java library on some statistical algorithm, you can always switch to R. Now you need to install rJava package in R. You have to include JRI as part of the Java Maven Package. Let’s try to call R from within Java.

// put this in Maven project pom.xml file
<dependency>
<groupid>com.dukascopy.api</groupid>
<artifactid> JRI<artifactid>
<version>0.9-6</version>
</dependency>

// Call R from within Java 
public interface RMainLoopCallBacks{
public void rWriteConsole(Rengine rngn, String string, int i);
public void rBusy(Rengine rngin, int i):
public String rReadConsole( Rening rngn, String string, int i);
public void rShowMessage( Rengine rngn, String string);
public String rChooseFile(Rengine rngn, int i);
public void rFlushConsole(Rengine rngn);
public void rSaveHistory(Rengine rngn, String string);
public void rLoadHistory(Rengine rngn, String string);
}

// embed the R script in Java
Path path=Paths.get("D:/R/AR1.R");
List<String> Lines=Files.ReadAllLines(path);
lines.stream().forEach(Line)->{
re.eval(Line);
}

In the above code first we JRI in the Maven Project pom.xml. Then we start Rengine. After that we tell Java to read R script and execute. We can use many powerful R packages in Java using the above method. In the next post I will try to build an algorithmic trading system using both Java and R.

Leave A Response