import java.text.SimpleDateFormat;
import java.util.*;

import com.dukascopy.api.*;

public class TestStrategy implements IStrategy {
    private IEngine engine;
    private IConsole console;
    private IHistory history;
    private IContext context;
    private IIndicators indicators;
    private IUserInterface userInterface;

    @Configurable("Period")
    public Period strategyPeriod = Period.ONE_HOUR;

    @Configurable("Instrument")
    public Instrument strategyInstrument = Instrument.EURUSD;

    @SuppressWarnings("serial")
    private final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") {
        {
            setTimeZone(TimeZone.getTimeZone("GMT"));
        }
    };

    double previousValue = 0;

    public void onStart(IContext context) throws JFException {
        this.engine = context.getEngine();
        this.console = context.getConsole();
        this.history = context.getHistory();
        this.context = context;
        this.indicators = context.getIndicators();
        this.userInterface = context.getUserInterface();
    }

    public void onAccount(IAccount account) throws JFException {
    }

    public void onMessage(IMessage message) throws JFException {
    }

    public void onStop() throws JFException {
        print("Stopped!");
    }

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

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

        if (instrument.equals(strategyInstrument) && period.equals(strategyPeriod)) {

            double[] ac1 = indicators.ac(strategyInstrument, strategyPeriod, OfferSide.BID, IIndicators.AppliedPrice.CLOSE, 5, 34, 1);

            double x0 = ac1[0];
            double x1 = ac1[1];
            double x = x0 == 0 ? x1 : x0;

            String color = "_____";
            if (previousValue > x) {
                color = "__red";
            } else if (previousValue < 0) {
                color = "green";
            }

            console.getOut().format("%s %5s % .7f % .7f \n", sdf.format(bidBar.getTime()), color, x0, x1);
            console.getOut().flush();
            
            previousValue = x;
        }
    }

    public void print(Object o) {
        this.console.getOut().println(o.toString());
    }

    private void print(long time, Object o) {
        print(sdf.format(time) + " " + o);
    }
}
