package singlejartest;

import java.text.SimpleDateFormat;
import java.util.TimeZone;

import com.dukascopy.api.*;

public class FindMaxFractal implements IStrategy {

    IIndicators indicators;
    IConsole console;
    IHistory history;
    
    @Configurable("")
    public Instrument instrument = Instrument.EURUSD;
    @Configurable("")
    public Period period = Period.TEN_MINS;
    @Configurable("")
    public OfferSide side = OfferSide.BID;
    @Configurable("")
    public int barsOnSides = 10;
    @Configurable("")
    public int maxLookback = 1000;
    
    private static int MAX = 0;
    private static int MIN = 1;
    
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyy HH:mm:ss"); 
    
    @Override
    public void onStart(IContext context) throws JFException {
        indicators = context.getIndicators();
        console = context.getConsole();
        history = context.getHistory();
        sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
        
        //change shift to 0 to check fractal values starting from the current bar
        IBar currBar = history.getBar(instrument, period, side, 100);
        
        double[][] frac = indicators.fractal(instrument, period, side, barsOnSides, Filter.NO_FILTER, maxLookback, currBar.getTime(), 0);
        
        double maxValue = Double.MIN_VALUE, minValue = Double.MAX_VALUE;
        int maxShift = 0, minShift = 0;
        
        for(int shift = frac[0].length - 1; shift >=0; shift--){
            if(frac[MAX][shift] > maxValue){
                maxValue = frac[MAX][shift];
                maxShift = shift;
            }
            if(frac[MIN][shift] < minValue){
                minValue = frac[MIN][shift];
                minShift = shift;
            }
        }
        long minTime = history.getBar(instrument, period, side, minShift).getTime();
        long maxTime = history.getBar(instrument, period, side, maxShift).getTime();
        
        console.getOut().println(String.format("Max value=%.5f of shift=%s at %s; Min value=%.5f of shift=%s at %s", 
                maxValue, maxShift, sdf.format(maxTime), minValue, minShift, sdf.format(minTime)));
    }

    @Override
    public void onTick(Instrument instrument, ITick tick) throws JFException {}

    @Override
    public void onBar(Instrument instrument, Period period, IBar askBar,
            IBar bidBar) throws JFException {}

    @Override
    public void onMessage(IMessage message) throws JFException {}

    @Override
    public void onAccount(IAccount account) throws JFException {}

    @Override
    public void onStop() throws JFException {}

}
