Dukascopy
 
 
Wiki JStore Search Login

Attention! Read the forum rules carefully before posting a topic.

    Try to find an answer in Wiki before asking a question.
    Submit programming questions in this forum only.
    Off topics are strictly forbidden.

Any topics which do not satisfy these rules will be deleted.

Price Structure - inputs example please?
 Post subject: Price Structure - inputs example please? Post rating: 0   New post Posted: Thu 14 Oct, 2010, 23:07 

User rating: 0
Joined: Thu 14 Oct, 2010, 22:52
Posts: 12
Hello, I'm sorry to ask a very basic question - but I am having trouble visualizing how prices are stored in the two-dimensional arrays.

Is there example code of an indicator that prints price? I want to understand the logic flow on a basic level before doing anything more involved.

I've had limited success, been able to add a new indicator and strategy. I've been able to plot a price-based line with a test indicator, but I don't think I have the structure right. That is why I ask.

So, for [row, column] are prices stored like this?

[0][0] Open
[0][1] Close
[0][2] High
[0][3] Low

I've also checked the API docs for the IBar function - but it seems to be a bit more involved to use. I appreciate any example you could provide, please.

Thank you.


 
 Post subject: Re: Price Structure - inputs example please? Post rating: 0   New post Posted: Fri 15 Oct, 2010, 09:12 
User avatar

User rating:
Joined: Fri 31 Aug, 2007, 09:17
Posts: 6139
Hi,
It's better to display prices in your strategy, but if you need to do this in the custom indicator, price can be accessed through input parameters. Firstly you need to specify InputParameterInfo.Type to PRICE and then cast input object to double array of arrays.
    InputParameterInfo[] inputParameterInfos = new InputParameterInfo[] {new InputParameterInfo("Input data", InputParameterInfo.Type.PRICE)};
    public void setInputParameter(int index, Object array) {
        double[][] inputs = (double[][]) array;
    }


Prices for PRICE type will be in the following order: Open[0.0], Close[1,0], High[2,0], Low[3,0], Volume[4,0] (but it depends how you will use array indexes).
Please take a look at the following JForex wiki page for more details: https://www.dukascopy.com/wiki/index.php ... ameterInfo
To view custom indicator example please assume this page: https://www.dukascopy.com/wiki/index.php ... _Indicator


 
 Post subject: Re: Price Structure - inputs example please? Post rating: 0   New post Posted: Fri 15 Oct, 2010, 20:34 

User rating: 0
Joined: Thu 14 Oct, 2010, 22:52
Posts: 12
Thank you for your example, but I think I need some more help.

I am trying to make a custom indicator based on different price inputs - Open, High, Low, Close.

My understanding is you create the indicator which is then called by a strategy to manage the actual trades based off of what your 'business logic' is.

I'm still confused about how the 'inputs' section is interpreted for the indicator, relating to incoming prices from the underlying instrument it is applied to.

If I have a strategy that invokes indicator calculation upon the close of the most recent bar, the incoming data for a given bar flowing to the indicator should be:

[Strategy]---->[indicators.calculateIndicator(insert parameters here, "Indicator Name", IIndicators.AppliedPrice[]{in this case, using IIndicators.AppliedPrice.CLOSE}

Assuming most recent price bar is, for example:
Open: 80.395
High: 80.498
Low: 80.37
Close: 80.472

And I want to pass this bar data to the indicator, I should first make sure my input array is declared and allocated like so:

First, in the custom indicator "public class MyTestIndicator implements IIndicator{" section

private double[][] inputs = new double[1][];

Then, in the indicator info section:

public void onStart(IIndicatorContext context){
indicator info = new IndicatorInfo("MyTestIndicator","Description Here","My indicators", false, false, false, 1, 1, 1);

Then the input parameters section:

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

Finally in the "public void setInputParameter(int index, Object array) {" section:

double[][] inputs = (double[][]) array;

Will this allow the price data to pass correctly into the "public IndicatorResult calculate(int startIndex, int endIndex){" section?

I'm sorry if I am missing something here, been looking at the Java guide and the API and I'm still not 'getting' how this works....

Any help appreciated, thank you.


 
 Post subject: Re: Price Structure - inputs example please? Post rating: 0   New post Posted: Mon 18 Oct, 2010, 13:34 
User avatar

User rating:
Joined: Fri 31 Aug, 2007, 09:17
Posts: 6139
TraderTim wrote:
double[][] inputs = (double[][]) array;

Will this allow the price data to pass correctly into the "public IndicatorResult calculate(int startIndex, int endIndex){" section?

As you have initialized inputs array before, you need to use this code to cast parameter in setInputParameter method
    public void setInputParameter(int index, Object array) {
        inputs[index] = (double[][]) array;
    }
This will allow the price data to pass correctly to the calculate method.

If you need more example how to implement custom indicator, please consider the following page viewtopic.php?f=6&t=8379


 
 Post subject: Re: Price Structure - inputs example please? Post rating: 0   New post Posted: Mon 18 Oct, 2010, 14:14 

User rating: 0
Joined: Tue 27 Jul, 2010, 20:57
Posts: 49
TraderTim wrote:
private double[][] inputs = new double[1][];

AFAIK it has to be "private double[][][] inputs = new double[1][][];"


 
 Post subject: Re: Price Structure - inputs example please? Post rating: 0   New post Posted: Mon 18 Oct, 2010, 17:01 

User rating: 0
Joined: Thu 14 Oct, 2010, 22:52
Posts: 12
Guess I'll just post the code that does work for me, while I try to figure out how the IIndicator class is defined.

The problem with looking at sparsely-commented indicator code, is that it doesn't help someone new to java. I know you are doing this support for free - and I understand your time is valuable. Hopefully this simple code will help someone new that is struggling to use close prices. If anyone knows how to access High and Low, let me know.

Indicator code, plots a simple line that is the close of the bar. Active bar will update this value until next bar is drawn. It also prints the current price in the message console for debugging.

public class SimpleClose implements IIndicator {
   
    private IndicatorInfo indicatorInfo;
    private InputParameterInfo[] inputParameterInfos;
    private OptInputParameterInfo[] optInputParameterInfos;
    private OutputParameterInfo[] outputParameterInfos;
    // Declare and allocate array - Getters and Setters - implemented by default, 2-dimensional arrays
    private double[][] inputs = new double[1][]; // creates 2-d array, rows, columns - number has to match what is in inputParameterInfos
    private double[][] outputs = new double[1][]; // creates 2-d array, rows, columns - add another row for drawing two lines
    private IConsole console; // Think you use this for console output
    // Variable definitions go here...

    private int timePeriod = 1; // This was 15, but lets change it to '1' so I can tell what is going on
   
 // I don't know how to get it to display two things at once yet, so I'm going to implement them separately.   
    public void onStart(IIndicatorContext context) {
        indicatorInfo = new IndicatorInfo("SimpleClose", "Plot simple close line", "My indicators",
              false, false, false, 1, 1, 1); // string Indicator name, string Title, string Groupname,
                                                             // bool overChart, bool overVolumes, bool unstablePeriod,
                                                             // int numberOfInputs(price), int numberOfOptionalInputs(parameter),
                                                             //int numberOfOutputs
        console = context.getConsole(); // Used for console
// Input parameters for indicator defined here
        inputParameterInfos = new InputParameterInfo[] {new InputParameterInfo("Input Data", InputParameterInfo.Type.DOUBLE)};
        // Optional Input parameters here...
        // I've set the default to 1 and the minimum to 1 so I can verify that the above is working - put it back when actually
        // calculating the real indicator.
        optInputParameterInfos = new OptInputParameterInfo[] {new OptInputParameterInfo("Time period", OptInputParameterInfo.Type.OTHER,
                new IntegerRangeDescription(1, 1, 100, 1))}; // IntegerRangeDescription(default, min, max, suggested increment)
        // Output Parameters, Drawing line styles defined here
        outputParameterInfos = new OutputParameterInfo[] {new OutputParameterInfo("SimpleClose", OutputParameterInfo.Type.DOUBLE,
                OutputParameterInfo.DrawingStyle.LINE)};
        // Initialize variables here, if any
       
    }
// Start of Indicator main code block

    public IndicatorResult calculate(int startIndex, int endIndex){
       if (startIndex - getLookback() < 0) { // Need some candles before we try to calculate anything
           startIndex -= startIndex - getLookback();
       }
   
       if (startIndex > endIndex) { // I think this stops it from calculating unless there is enough bars available.
            return new IndicatorResult(0, 0);
       }
       
       // Loops for iterating arrays go here
       int i, j;
       for (i = startIndex, j = 0; i <= endIndex; i++, j++){
   
       console.getOut().println("Price at index: "+i+" is: "+ inputs[0][1]); // debug - prints current input value to console
       
        outputs[0][j] = inputs[0][1];
        }
    return new IndicatorResult(startIndex, j); // Returns final result   
    }
// End of Indicator main code block

    public IndicatorInfo getIndicatorInfo() {
        return indicatorInfo;
    }

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

    public int getLookback() { // Saves time period in class variable
        return timePeriod;
    }

    public int getLookforward() {
        return 0;
    }

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

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

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

    public void setOptInputParameter(int index, Object value) { // This is the 'lookback' parameter that is set via the optional
        timePeriod = (Integer) value;                           // inputs section 'optInputParameterInfos' above
    }

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



Hope that helps someone.


 
 Post subject: Re: Price Structure - inputs example please? Post rating: 0   New post Posted: Mon 18 Oct, 2010, 20:51 

User rating: 0
Joined: Thu 14 Oct, 2010, 22:52
Posts: 12
Well, after a few days of banging my head against class definitions - here's the quick and easy way to access the incoming price stream. I am at a loss as to why this isn't detailed elsewhere, but here it goes:

You need to define your inputs like so:

private double[][][] inputs = new double[1][][];


For indicator input, it is sufficient to allow for one since you are only using PRICE. (This was a large part of the puzzle.)

indicatorInfo = new IndicatorInfo("YourIndicatorName", "Description Here", "My indicators",false, false, false, 1, 1, 1);


Under the input parameters section, it is merely defined as PRICE.

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


Inside the "public IndicatorResult calculate(int startIndex, int endIndex)" code block, you'll define your variables to assign
the specific prices to them. Then you may manipulate them at will. Here's the crucial part - using the 3-Dimensional array properly to assign the prices. (My variables have already been declared as doubles).

       Open = inputs[0][0][1]; // Assign Open price    
       High = inputs[0][2][1]; // Assign High price
       Low = inputs[0][3][1]; // Assign Low price
       Close = inputs[0][1][1]; // Assign Close price


It is important to note that the last value in the array determines what bar you are pulling the price from. In this case, [1] is the current bar in progress. [0] would be the last formed bar. Still working out how to access bars beyond just these two instances.

----------
UPDATE - Finally figured this out as well. When you are defining the lookback for your indicator - that determines the range you can pull your prices from. So, if you have a lookback of 15, the OLDEST bar is index 0, the last FORMED bar is 14, and the CURRENT updating bar is 15.
----------

If you just wanted to test this and pipe the output to the indicator as simple price, the outputs assignment is:
(This is based on the simple indicator code you auto-generate when creating a new indicator - but I stripped out the nested loop that iterates backwards using 'k'.)
outputs[0][j] = Close;


Lastly, don't forget to change the "public void setInputParameter(int index, Object array) {" section like so:

inputs[index] = (double[][]) array;


Compile, and then stop tearing your hair out trying to reverse-engineer price inputs.

You're welcome.


 
 Post subject: Re: Price Structure - inputs example please? Post rating: 0   New post Posted: Sun 24 Oct, 2010, 23:59 

User rating: 0
Joined: Thu 14 Oct, 2010, 22:52
Posts: 12
Gotten further - posting so it is informative for newbies not willing to do atomic-level granular searches on the forum.

As to my previous post, the time interval is simple - make sure that you are declaring a variable such as:

private int timePeriod = 15;


A suitable place for this is after the inputs and outputs are defined as referenced in my last post. Make sure as well your optional input parameters - which usually define a possible range of time periods over which to calculate your indicator are set appropriately like so:

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


--------
UPDATE - Please see my prior post above on how the optional parameters for lookback affect your ability to
pull prices without resorting to IHistory calls.
--------

The integers in the last part are the default value, minimum value, maximum value and increment value if the user changes it when applying the indicator to a chart.

Now on the meat of things. STRATEGIES.

I only have a very basic framework up, but believe me - this took time to condense from the examples. The problem I find is that there isn't much out there documenting what you do if you are not using built-in indicators. Some of us make our own! Here's a code reference that will call your custom indicator and then print the output on the message console.

There aren't any order entries or any logic like that - but sometimes having a very basic example helps, wouldn't you agree?

package jforex;

import java.util.*; // Used for toString() calls

import com.dukascopy.api.*;
import com.dukascopy.api.IBar;
import com.dukascopy.api.IIndicators.*; // Used for applied price in calculate indicator call

public class YourStrategyNameHere implements IStrategy {
    // Configurable parameters go here -- if you are using these at all - just for example, not really implemented yet
    @Configurable("Instrument") public Instrument instrument = Instrument.AUDJPY; // Default Instrument
    @Configurable("Instrument Period") public Period period = Period.ONE_MIN; // Default Time Period
    @Configurable("Amount") public double amount = 0.001; // Minimum tick increment, relates to order size
    @Configurable("Stop loss") public int stopLossPips = 10; // Stop in pips
   
   private IEngine engine;
   private IConsole console;
   private IHistory history;
   private IContext context;
   private IIndicators indicators;
   private IUserInterface userInterface;
   
   
   public void onStart(IContext context) throws JFException { // Print start message when started
      this.engine = context.getEngine();
      this.console = context.getConsole();
      this.history = context.getHistory();
      this.context = context;
      this.indicators = context.getIndicators();
      this.userInterface = context.getUserInterface();
        console.getOut().println("Strategy Started"); // Print start message
   }

   public void onAccount(IAccount account) throws JFException {
   }

   public void onMessage(IMessage message) throws JFException {
   }

   public void onStop() throws JFException { // Print stop message if stopped
        console.getOut().println("Strategy Stopped"); // Print stop message
   }

   public void onTick(Instrument instrument, ITick tick) throws JFException { // NOT using tick inputs, so nothing here.
   }
   
// Bar based indicators go in this block ==========================================================================================
    public void onBar(Instrument instrument, Period period, IBar askBar, IBar bidBar) throws JFException {
    // REMEMBER: Shorts are opened by BID price and closed by ASK price. Longs are opened by ASK and closed by BID price.
    // Order won't be closed unless the proper side hits your price.
   
    //engine.submitOrder(label, instrument, orderCmd, amount, price, slippage, stop, takeProfit); // example of taking profit order
       
    //engine.submitOrder(label, instrument, IEngine.OrderCommand.BUY, amount, 0, -1);
    // attempt to enter order without slippage to put in stop - support says that only setting large slippage will work....
    // IOrder in API documentation has all the parameters for market orders
    // Wiki - https://www.dukascopy.com/wiki/index.php/Set_Conditional_Order
   
    if(!instrument.equals(Instrument.AUDJPY) || (period != Period.ONE_MIN)) return; // This is what filters the interval on
                                                                                    // indicator calculations. Other params
                                                                                    // could be TEN_MINS, THIRTY_MINS, etc..
       
       Object[] YourCustomIndicator = indicators.calculateIndicator(instrument, period, new OfferSide[]{OfferSide.BID},
                                                    "YourCustomIndicator", // indicator name - matches name you set your indicator to
                                                    new AppliedPrice[]{IIndicators.AppliedPrice.CLOSE}, // input type
                                                    new Object[]{15}, 1); // Opt params, shift -- or long from, long to
                                                                          // shift 1 = last formed candle, 0 = current in progress candle
       
        // Easier method for extracting output would be using double[] for the above and get rid of the toString() call below...                                                                                                                                                                             
        console.getOut().println("Your custom indicator value is: "+ YourCustomIndicator[0].toString() + " at "+ new Date(bidBar.getTime())); // Prints message to console
         
    }
}


Hope that helps. When I get a chance, I'll try to flesh this out with an example of basic order entry and such.


 
 Post subject: Re: Price Structure - inputs example please? Post rating: 0   New post Posted: Mon 25 Oct, 2010, 15:58 

User rating: 0
Joined: Thu 14 Oct, 2010, 22:52
Posts: 12
Just a short post while I'm working on my strategy.

To access the values from your indicator to utilize it as part of buying or selling order-entry logic, here's a simple example:

Object[] YourCustomIndicator = indicators.calculateIndicator(instrument, period, new OfferSide[]{OfferSide.BID},
                                                    "YourCustomIndicator", // indicator name - matches name you set your indicator to
                                                    new AppliedPrice[]{IIndicators.AppliedPrice.CLOSE}, // input type
                                                    new Object[]{15}, 1); // Opt params, shift -- or long from, long to
                                                                          // shift 1 = last formed candle, 0 = current in progress candle

// Here we do some manipulation to convert the data from the above object to a string, and then finally to a double

String LastFormedCandleString = YourCustomIndicator[0].toString(); // convert object to string
double  IndicatorShiftOne = Double.valueOf(LastFormedCandleString); // convert string to double

console.getOut().println("Last formed candle - My Custom Indicator value is: "+ IndicatorShiftOne +" at "+ new Date(bidBar.getTime())); // Prints message to console with value, and timestamp



Enjoy!

More later...


 

Jump to:  

  © 1998-2024 Dukascopy® Bank SA
On-line Currency forex trading with Swiss Forex Broker - ECN Forex Brokerage,
Managed Forex Accounts, introducing forex brokers, Currency Forex Data Feed and News
Currency Forex Trading Platform provided on-line by Dukascopy.com