77z3-FX

Dukascopy's Introducing Agent & External Account Manager

jForex order.getComission() not compiling

Bummer, the jForex order.getComission() is not compiling. After some research in Dukascopy support boards (http://www.dukascopy.com/swiss/english/forex/jforex/forum/viewtopic.php?f=85&t=43119) their response is following:

Of course you cannot compile; these methods are introduced in an api
version far above that what is currently in use in jforex. You can
use them with the standalone api. Or you can calculate the values
yourself.

Thank you very much! Something, that could be easily set from their side, why do each person has to calculate it?!

Not any more!

I just coded a simple commission calculation function based on the commission tables and samples posted on the Dukascopy website: http://www.dukascopy.com/swiss/english/forex/forex_trading_accounts/commission-policy/

 

HERE IS THE CODE: Feel free to use it in your strategy :-)

private double calcComissionUSD(double Deposit, double Equity, double Lots) {
            double amount_array[]={0,5000,10000,25000,50000,250000,500000,1000000,5000000,10000000};
            double com_array[]={48,38,32,25,18,16,14,12,9,5};
            int comD=0,comE=0;
            ///Based on Deposit
            for (int i=0; i<10; i++) {
                if (Deposit>=amount_array[i]) {
                    comD=i;
                }
            }
            ///Based on Equity
            for (int i=0; i<10; i++) {
                if (Equity>=amount_array[i]) {
                    comE=i;
                }
            }
            int minvalue=Math.max(comD,comE);
            return Math.ceil(com_array[minvalue]*Lots*100)/100;
}

jForex Indicator with multiple inputs & outputs

Some things to keep in mind with when coding an indicator with multiple inputs & outputs.

indicator with multiple outputs

1. Define correct number of arrays

I will need 2 time periods and 4 outputs, so first I have to make sure I start the arrays correctly:

private int[] timePeriod = new int[2];
private double[][] outputs = new double[4][];

2. Defining the correct parameter info for each item

I need to define 2 periods and 4 ouputs

indicatorInfo = new IndicatorInfo("maCross", "Moving Average Cross",
"My indicators",true, false, false, 1, 2, 4);

optInputParameterInfos = new OptInputParameterInfo[] {
   new OptInputParameterInfo("Time period 1:",
       OptInputParameterInfo.Type.OTHER,
       new IntegerRangeDescription(5, 2, 100, 1)),
   new OptInputParameterInfo("Time period 2:",
       OptInputParameterInfo.Type.OTHER,
       new IntegerRangeDescription(8, 2, 100, 1))
};

outputParameterInfos = new OutputParameterInfo[] {
   new OutputParameterInfo("MA1", OutputParameterInfo.Type.DOUBLE,
       OutputParameterInfo.DrawingStyle.LINE),
   new OutputParameterInfo("MA2", OutputParameterInfo.Type.DOUBLE,
       OutputParameterInfo.DrawingStyle.LINE),
   new OutputParameterInfo("UP", OutputParameterInfo.Type.DOUBLE,
       OutputParameterInfo.DrawingStyle.ARROW_SYMBOL_UP),
   new OutputParameterInfo("DOWN", OutputParameterInfo.Type.DOUBLE,
       OutputParameterInfo.DrawingStyle.ARROW_SYMBOL_DOWN)};

3. Calculating the Output Values

You need to use arrays for input values. In my case for the “time Period 1″ I have to use the first array value which is 0, and for the “time Period 2″ I use the second array value which is 1

outputs[0][j] = value/timePeriod[0];
outputs[1][j] = value2/timePeriod[1];
outputs[2][j] = 0;
outputs[3][j] = 0;

Also make sure you find values for all outputs. I have 4 outputs, so I need values for outputs[0], outputs[1], outputs[2] and outputs[3].

4. Download Sample Source code

Here is a sample source code for a maCross indicator I just coded for practice.


Click  to download: maCross.java

Coding jForex Indicators with no Previous JAVA experience

I’ve been coding for MT4 for a while, and the mql4 coding was relatively easy to pick up since there’s so many samples, and good documentation to help you. My next challenge is to code an Indicator for Dukascopy jForex. Since I do not have any previous java knowledge and the documentation is not explaining much, I’ll have to experiment a lot, and see what works.

 

So far I got started with a simple template provided in the jForex. Just right click on Strategies and open a New Indicator

jforex - new inidcator

You will end up with a small sample code, which helps to get a head start..

1. Naming the Indicator

One thing I did not know when I started my very first code for jForex is that the class name of your indicator or strategy MUST match the file name. Otherwise it will not compile without giving you errors.

public class Indicator implements IIndicator {

I will try to make a Simple Moving Average Indicator as my first lesson. So I will name my indicator to myMA

public class myMA implements IIndicator {

2. Defining the parameters

This is what is already defined in the template:

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][];

and since I won’t be needing any more parameters for the Moving Average indicator, I will leave this part untouched and move on to the next part

3. Defining the Indicator info

Moving on to the part with the following code:

public void onStart(IIndicatorContext context) {

This is where I define all setting (inputs and outputs) for the indicator. This is the code you see:

indicatorInfo = new IndicatorInfo("EXAMPIND", "Sums previous values",
                "My indicators",
                false, false, false, 1, 1, 1);
inputParameterInfos = new InputParameterInfo[] {
      new InputParameterInfo("Input data",
      InputParameterInfo.Type.DOUBLE)};
optInputParameterInfos = new OptInputParameterInfo[] {
      new OptInputParameterInfo("Time period",
      OptInputParameterInfo.Type.OTHER,
      new IntegerRangeDescription(2, 2, 100, 1))};
outputParameterInfos = new OutputParameterInfo[] {
      new OutputParameterInfo("out", OutputParameterInfo.Type.DOUBLE,
      OutputParameterInfo.DrawingStyle.LINE)};

Let me explain a bit what these lines of codes do. I searched for the info from different sources and have compiled here my understanding of the code. IndicatorInfo set the following things:

indicatorInfo = new IndicatorInfo("EXAMPIND", "Sums previous values",
                "My indicators",false, false, false, 1, 1, 1);

“EXAMPIND” = indicator name – gives a name by which you will be able to call it from strategy (should be simple);
“Sums previous values” = indicator title – gives a title to this indicator – more detailed name which are used in JForex “add indicator” dialog window;
“My indicators” =   Indicator groupName – specifies directory where it would be accessible thru JForex in “add indicator” dialog window;
false =    overChart – true if indicator should be drawn over candles/ticks on the main chart (e.g. SMA); set it false if you want the indicator to show its values in a separate window;
false =    overVolumes – true if indicator should be drawn over volume information;
false =    unstablePeriod – true if indicator has unstable period (like EMA or SAR). This will add more candles in every call to stabilize function;
1 =    numberOfInputs – number of inputs that user should provide (e.g. price: open or close);
1 =    numberOfOptionalInputs – number of optional inputs (e.g. time period for SMA);
1 =    numberOfOutputs – number of outputs, that function returns (these are usually the number lines on the chart);

 

So here is my line of code for the Simple Moving average:

indicatorInfo = new IndicatorInfo("myMA", "Moving Average",
                "My indicators",true, false, false, 1, 1, 1);

Notice that I changed the overChart value to be true since the Moving Average needs to draw over the candles.

4. Setting up the inputs and outputs for the indicator (what data goes in and what/how needs to come out)

The next lines will define what will be displayed in the “edit indicator” properties when launching the indicator.

inputParameterInfos = new InputParameterInfo[] {
          new InputParameterInfo("Input data",  InputParameterInfo.Type.DOUBLE)};

“Input data” = name for the input to display
InputParameterInfo.Type.DOUBLE = type of data

 

Here are the input data types (InputParameterInfo.Type) that can be used according to Dukascopy documentation:

PRICE = Indicates that this input is price. Price includes open, close, high, low, volume
DOUBLE = Indicates that this input is any double data
BAR = Indicates that this input is IBar array

 

We just have one data input for the Moving Average, so I’ll just change the name to the following:

inputParameterInfos = new InputParameterInfo[] {
         new InputParameterInfo("Price:",
         InputParameterInfo.Type.DOUBLE)};

What if you need to define 2 or more input variables?

First, make sure your indicatorInfo in previous code line defines 2 inputs, or the number of inputs you need to define, in this sample it will be 3

indicatorInfo = new IndicatorInfo("EXAMPIND", "Sums previous values",
                "My indicators",
                false, false, false, 3, 1, 1);

Then just keep adding inputs to this array. In this sample I will add 3 inputs, not that each new InputParameterInfo(..) is separated by commas in a list.

inputParameterInfos = new InputParameterInfo[] {
    new InputParameterInfo("Price1:", InputParameterInfo.Type.DOUBLE),
    new InputParameterInfo("Price2:", InputParameterInfo.Type.DOUBLE),
    new InputParameterInfo("Price3:", InputParameterInfo.Type.DOUBLE)
};

It works identically for the optInputParameterInfos and outputParameterInfos.

 

Next I check the OptionalInputs, which will be the Time period for the Moving average. In this case I can leave the code untouched as the sample already defines it as a time period.

optInputParameterInfos = new OptInputParameterInfo[] {
new OptInputParameterInfo("Time period",
OptInputParameterInfo.Type.OTHER,
new IntegerRangeDescription(2, 2, 100, 1))};

OptInputParameterInfo.Type can be following:
CURRENCY = Optional input is currency
DEGREE = Optional input is degree
OTHER = Optional input is something other
PERCENT = Optional input is percent

 

Here is explanation for the IntegerRangeDescription:

public IntegerRangeDescription(int defaultValue,
                               int min,
                               int max,
                               int suggestedIncrement)

defaultValue – default value, that is user if used doesn’t set optional input
min – minimal value
max – maximal value
suggestedIncrement – suggested step to change this input

 

The following step will be to check the Indicator outputs, which is the following code:

outputParameterInfos = new OutputParameterInfo[] {
new OutputParameterInfo("out",
OutputParameterInfo.Type.DOUBLE,
OutputParameterInfo.DrawingStyle.LINE)};

Where:
“out” = name for the indicator output
OutputParameterInfo.Type.DOUBLE = output type (double in this case)
OutputParameterInfo.DrawingStyle.LINE = drawing style

 

OutputParameterInfo.Type can be following:
DOUBLE
= Output is array of doubles, Double.NaN values means there is no value at that point
INT = Output is array of integers, Integer.MIN_VALUE values means there is no value at that point
OBJECT = Any object, outputs with this type can be only interpreted by strategies or drawn by selfdrawing indicators

 

OutputParameterInfo.DrawingStyle can be set to following:
ARROW_SYMBOL_DOWN
= Draw arrow symbol at non NaN or no Integer.MIN_VALUE values
ARROW_SYMBOL_UP = Draws arrow symbol at non NaN or no Integer.MIN_VALUE values
DASH_LINE = Show output as dashed line
DASHDOT_LINE = Show output as dashed and dotted line
DASHDOTDOT_LINE = Show output as dashed and double dotted line
DOT_LINE = Show output as dotted line
DOTS = Show output as dots
HISTOGRAM = Show output as histogram
LEVEL_DASH_LINE = Show output as dashed level.
LEVEL_DASHDOT_LINE = Show output as dashed and dotted level.
LEVEL_DASHDOTDOT_LINE = Show output as dashed and double dotted level.
LEVEL_DOT_LINE = Show output as dotted level.
LEVEL_LINE = Show output as level.
LINE = Show output as line
NONE = Don’t draw anything
PATTERN_BOOL = If value is not zero, then draw pattern
PATTERN_BULL_BEAR = If value: == 0 – no pattern > 0 – bullish < 0 – bearish
PATTERN_STRENGTH = If value: == 0 – neutral ]0..100] getting bullish ]100..


I’ll just change the output parameter name from “out” to “MA” for this indicator, so it will be following:

outputParameterInfos = new OutputParameterInfo[] {
new OutputParameterInfo("MA",
OutputParameterInfo.Type.DOUBLE,
OutputParameterInfo.DrawingStyle.LINE)};

 5. Calculating The indicator Value

The indicator value is calculated in this part of the code:

public IndicatorResult calculate(int startIndex, int endIndex) {
        //calculating startIndex taking into account lookback value
        if (startIndex - getLookback() < 0) {
            startIndex -= startIndex - getLookback();
        }
        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);
}

The sample code just adds the input values up into one big sum. As you can see it loops though the candles i=startIndex until i<=endIndex and then loops again from k=TimePeriod to k>0 to collect the sum of timePeriod inputs. For moving average, we just need to find the average, meaning we need to divide the value with the number of variables we added together which is the timePeriod. The code will look like this:

public IndicatorResult calculate(int startIndex, int endIndex) {
        //calculating startIndex taking into account lookback value
        if (startIndex - getLookback() < 0) {
            startIndex -= startIndex - getLookback();
        }
        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/timePeriod;
        }
        return new IndicatorResult(startIndex, j);
}

6. Compile & Test

Now we just need to compile the indicator, and put it on the charts. Here is the comparison with the built in SMA indicator. The red line is myMA and the green line is SMA

myMA and SMA comparison

 

 

 

YES! – I just created my first indicator!

7. Download the sample source code



If you wish to see the full source code of the myMA indicator, you can download it here: myMA.java

Filtering out Flat candles in jForex Strategy

In my last post “jForex Moving average Strategy not giving the results seen on the charts” I have explained how my SMA results on the Strategy and chart were different.

I was using the following simple code:

indicators.ma(instrument,MAPERIOD,OfferSide.BID,IIndicators.AppliedPrice.CLOSE,maPeriod,IIndicators.MaType.SMA,0);

 


How to filter out flat candles in the jForex Strategy:

First we need to define what kind of filtering do we want to use. In the very beginning of your strategy where you define all variable, insert the following code:

private static final Filter indFilter = Filter.WEEKENDS;

The Filter values can be also following:

ALL_FLATS = filter all flats (weekend, and other flat candles during trading hours)

NO_FILTER = don’t filter anything

WEEKENDS = Filter flats at the weekends (21:00 or 22:00 Friday – 21:00 or 22:00 Sunday)

Note that the default filter you see on your charts is the Weekends filter, unless you change it from the settings.

 

Then we replace the simple ma function I used before with this one:

indicators.ma(instrument,MAPERIOD,OfferSide.BID,IIndicators.AppliedPrice.CLOSE,maPeriod,IIndicators.MaType.SMA,indFilter,1,bidBar.getTime(),0)[0];

And that does the trick!

jForex Moving average Strategy not giving the results seen on the charts

I was writing a simple strategy in jForex when I notice the SMA results in the strategy did not match the charts.

I was using the following code to find the SMA value:

indicators.ma(instrument,MAPERIOD,OfferSide.BID,IIndicators.AppliedPrice.CLOSE,maPeriod,IIndicators.MaType.SMA,0);

This is the results that I got on the test. As you can notice the MA-s do not cross, but yet the jForex Strategy entered a trade.

jforex MAs no cross


After a few hours of cracking my head, I found out why is this happening: Jforex default setting filter out all weekend flat candles (Settings -> Charts)

jforex default chart settings

After changing the Flat filters “disabled”, you will see the following results, which now match with the Strategy results.

jforex flats filter disabled


jforex chart with flats filter disabled

As seen on the above image, the strategy entered after the 2 MA-s crossed.

 

What does this mean?

This means that the simple ma function in jForex does not filter out the weekend flat candles. I will be showing how to filter out the flat candles in the jForex strategy in the next post “Filtering out Flat candles in jForex Strategy“.