More trouble with JForex IIndicators

JFUtil offers [an elegant way of requesting indicators from the JForex IIndicators interface][]. But the new design for JForex IIndicators through JFUtil is only fixing one side of the problem. There is still the question of what to do with the multiple return types from the calculations. In JForex, indicators like RSI returns a one-dimensional array. Other indicators like Stochastic Oscillator returns a two-dimensional array. And some other ones return three or more dimensional arrays. Java doesn't allow overloading a method with multiple return types, as the program wouldn't know what to expect. So how can we get rid of coding mess like this in our JForex strategy? [java] Stochastic stochBean = IndicatorBeanFactory.getStochastic(); Object[] objs = Indicating.calculateMultiDimension(instrument, Period.ONE_MIN, stochBean, 1); double[][] sto = new double[2][]; sto[0] = (double[])objs[0]; // %K values sto[1] = (double[])objs[1]; // %D values [/java] The default calculation method in JForex returns a generic Object array. It's up to the programmer to know what to expect from the call and cast the Object into something useful. Obviously, this is a recipe for programming headaches and runtime errors. Having said this, one of the biggest benefits of JForex is that it uses a standard programming language like Java. So if there's something that you don't like about the API, you can probably change it (e.g. Facade pattern). This is the purpose of JFUtil to some extent, to simplify the JForex API behaviour. In any case, I'm sure other Java programmers have faced this problem before and have come up with good solutions for it. A search on doesn't yield a quick fix solution at first glimpse. My guess is that this require leveraging the knowledge about the program structure. We know in advance what dimension of the calculation result we can expect based on the indicator itself, perhaps I can use something like a Command pattern to choose a calculation sub-routine and then return a Map object with named values? I have yet to try implementing this. I am open to design suggestions to encapsulate multiple return values through a single interface. So that any indicator bean can use the same calculation interface with an easy to use output. In the mean time, getting multi-dimensional indicators results through JFUtil 2.1.2 isn't pretty.

[an elegant way of requesting indicators from the JForex IIndicators interface]:

Conjuring beans to simplify JForex IIndicators

The JForex API is not perfect. Like any application programming interface (API), some parts of the JForex API is better designed than others. One of the most gripping problems with JForex is its use of technical analysis (TA) indicators. Here's an example of using an exponential moving average, one of the most simplest indicators. ema(instrument, Period.TEN_SECS, OfferSide.BID, IIndicators.AppliedPrice.MEDIAN_PRICE, 14, 0); And the corresponding javadoc explaining the parameters, Parameters: instrument instrument of the bar period period of the bar side bid or ask side of the bar appliedPrice type of input data timePeriod time period value shift number of candle back in time staring from current bar. 0 - current bar (currently generated from ticks), 1 - previous bar (last formed bar), 2 - current bar minus 2 bars and so on It's not intuitive but it's usable. Recall that in my JForex programming tutorial, I suggested using the JForex API javadoc to find out information about the API. However, for the case of IIndicators, if you take a look at its javadoc, you will only be led to more confusion by the hundred or so mysterious indicator methods with cryptic parameter names. In JForex API, if you want to calculate an indicator, you need to look through a long list of abbreviated method names in the javadoc. Many of which are not easy to decipher. Secondly, you need to figure out the generic parameters and set them correctly, which is different for almost every indicator. Lastly, as there is no standard interface for indicators, you need to hardcode these into your strategy with little flexibility. In contrast, here's the same call using JFUtil 2.1.0 to get an EMA value. It has notably more lines of code. It is designed deliberately so using an object oriented approach by encapsulating the indicator parameters into a bean object and abstracting the calculation into a single generic function call. [java] // get an EMA indicator value by building an indicator bean MovingAverage maBean = IndicatorBeanFactory.getMovingAverage(); // then sets its parameters with obvious method names maBean.setAppliedPrice(IIndicators.AppliedPrice.MEDIAN_PRICE) .setMAType(IIndicators.MaType.EMA) .setWidth(14); // all of these are optional parameters // feed the bean into a generic calculation method to get the result double ema = Indicating.calculate(instrument, Period.ONE_MIN, maBean); [/java] With JFUtil, to calculate an indicator, you create an indicator bean with the intuitive bean name that corresponds with the full name of an indicator. For example, a moving average will be MovingAverage. Then you set the indicator-specific parameters using clearly defined methods with useful javadoc descriptions. One method for one parameter. Lastly, you feed this indicator bean into a generic calculation function to get your value. It took some thinking to abstract and generalize such a rigidly structured API. I am quite pleased with this new design as the current JFUtil opens up a lot of design flexibility. Such as dynamic indicator selection with genetic algorithm and interchangeable indicators use for runtime adaptive algorithms.

JFUtil 2.0 alpha demonstration

Rather than talk about how much better JFUtil 2.0 is and all, I'll just show you a demonstration strategy illustrating the features of this JForex utilities library. Download the latest JFUtil from the project page. As this is an alpha release, I need your help in finding bugs and look for improvements. Leave me a message if you have any comment or suggestion please. It's best if you copy and paste the following demo strategy source code into your IDE or text editor for viewing.

import java.util.\*; import com.dukascopy.api.\*;
import com.quantisan.JFUtil.\*; @Library("JFQuantisan.jar") // place
this file in your ../JForex/Strategy/files folder public class
jfutilDemo implements IStrategy { private int counter = new
Random().nextInt(100); // notice the lack of fields to manage JForex
objects @Override public void onStart(IContext context) throws
JFException { // \*\* Essential steps \*\* // must initialize objects
once and for all JForexContext.setContext(context);
JForexAccount.setAccount(context.getAccount()); Set\<Instrument\> set =
new HashSet\<Instrument\>(context.getSubscribedInstruments()); set =
context.getSubscribedInstruments(); // get list of subscribed
instruments // subscribe to transitional instruments for currency
conversion calculations Pairer.subscribeTransitionalInstruments(set); //
\*\* End of essential steps \*\* Printer.println("--
JFUtil v2.0 alpha: Usage demo --"); Printer.println(""); } @Override
public void onBar(Instrument instrument, Period period, IBar askBar,
IBar bidBar) throws JFException { if (period != Period.TEN\_SECS)
return; // only run every 10 sec. // \*\*\* 1. access IContext and
IAccount from anywhere \*\*\* Printer.println("Account equity = " +
JForexAccount.getEquity()); // get an EMA indicator value double ema =
JForexContext.getIndicators().ema(instrument, Period.TEN\_SECS,
OfferSide.BID, IIndicators.AppliedPrice.MEDIAN\_PRICE, 14, 1);
Printer.println(instrument.toString() + " EMA = " + ema); // printing
the EMA value // \*\*\* 2. Profit/loss calculation to account currency
before placing your order \*\*\* // Demonstrating currency conversion
double risk = 100 \* Pairer.convertPipToAccountCurrency(instrument);
String symbol = JForexAccount.getAccountCurrency().getSymbol();
Printer.println(symbol + risk + " risked in for 1,000 units and 100 pips
move in " + instrument.toString()); // \*\* 3. Simplify order parameters
with order ticket builder \*\*\* // Demonstrating trade ordering String
label = instrument.toString().substring(0,2) + ++counter; OrderTicket
mktBuyTicket = new OrderTicket // order ticket .Builder(label, //
setting required ticket info instrument, IEngine.OrderCommand.BUY, 0.1)
.build(); // build ticket Orderer.placeOrder(mktBuyTicket); // placing
order // market buy order with a 100 pips stop and 100 pips target
double stopPrice = JForexContext.getPrice(instrument) - (100 \*
instrument.getPipValue()); double targetPrice =
JForexContext.getPrice(instrument) + (100 \* instrument.getPipValue());
label = instrument.toString().substring(0,2) + ++counter; OrderTicket
buySpTicket = new OrderTicket .Builder(label, instrument,
IEngine.OrderCommand.BUY, 0.1) .setStopLossPrice(stopPrice) // set stop
price to ticket .setTakeProfitPrice(targetPrice) // set target .build();
// \*\* 4. Single method to placing orders for all order types and
parameters \*\*\* Orderer.placeOrder(buySpTicket); } @Override public
void onAccount(IAccount account) throws JFException {
JForexAccount.setAccount(account); // update IAccount to latest }
@Override public void onStop() throws JFException { for (IOrder order :
Orderer.getOrders()) // close all orders Orderer.close(order); } }

JFUtil: An open-source JForex utilities library

JFUtil is a open-source project focused on reusable JForex trading strategy components. Latest version is 2.1.3 released on April 8, 2011. Please keep your local JFUtil library up to date for the latest patches and features.

Main Features

1. Access to IContext and IAccount from anywhere in your project files. The one and only JForexContext object in JFUtil is a thread-safe, singleton object which can be called from anywhere within your projects, across any class file. No need to declare global IContext variables. No need to pass it around in parameters.

2. Simplify order submission with ticket builder. Set your trade order parameters with an order ticket object using a builder constructor. You can build ticket with as few or as many parameters as you like. All with intuitive method names in the same ticket class.

buySpTicket = new OrderTicket.Builder(label, instrument,IEngine.OrderCommand.BUY, 0.1)
                .setStopLossPrice(stopPrice)     // set stop price to ticket
                .setTakeProfitPrice(targetPrice) // set target

3. No more confusion about indicator methods. Indicators are encapsulated into their own bean object with their full function name and parameters are set using intuitive, clearly described methods.

// get an EMA indicator value by building an indicator bean
MovingAverage maBean = IndicatorBeanFactory.getMovingAverage();
// then sets its parameters with obvious method names
    .setMAType(IIndicators.MaType.EMA) .setWidth(14);
// all of these are optional parameters
// feed the bean into a generic calculation method to get the result
double ema = Indicating.calculate(instrument, Period.ONE\_MIN, maBean);

4. Implicit multi-threading for ordering. Ease your main thread's workload for processing incoming data and avoid your order manager holding up the traffic. All automatically performed in the background without extra coding for you. 5. Built-in popular numerical functions for forex trading. Calculate expected profit or loss in your account currency. Saves you from writing boilerplate codes and reinventing the wheel. 6. Continuous improvements! JFUtil is continuously being improved based on feedback from traders like you. See the changelog below for major changes since the initial release in November 2010.


To best illustrate how JFUtil can make your JForex programming life easier, see this JForex strategy source code example.


Download the latest JFUtil library jar file including the javadoc for your own use (use the @Library annotation in your strategy) or fork the project at Github to participate in this open-source project to make programming trading strategies in JForex easier for everyone.


Please report any issue or discuss your question or recommendation in the [comments section below][]. Alternatively, you can contact me directly.

Major Releases:

v2.1.0 - March 22, 2011 - indicator bean, label maker v2.0.0 - March 8, 2011 - singleton access to JForex objects, order ticket building, global currency conversion, global printer utility. v1.0 - November 24, 2010 - JFUtil 1.0