package jforex.strategies;

import com.dukascopy.api.*;
import com.dukascopy.api.IIndicators.AppliedPrice;
import com.dukascopy.api.IIndicators.MaType;
import java.text.DecimalFormat;

public class MAStrategySample implements IStrategy {

    private IConsole console;
    private IIndicators indicators;
    
    @Configurable("Instrument")
    public Instrument selectedInstrument = Instrument.EURUSD;
    @Configurable("Applied price")
    public AppliedPrice appliedPrice = AppliedPrice.CLOSE;    
    @Configurable("MA type")
    public MaType maType = MaType.SMA;
    @Configurable("MA time period")
    public int maPeriod = 5;
    
    private OfferSide selectedOfferSide = OfferSide.BID;
    private Period selectedPeriod = Period.TEN_SECS;

    public void onStart(IContext context) throws JFException {
        this.indicators = context.getIndicators();
        this.console = context.getConsole();
        
        // add MA indicator to chart from strategy
        IChart chart = context.getChart(selectedInstrument);        
        if (chart != null) {
            selectedOfferSide = chart.getSelectedOfferSide();            
            selectedPeriod = chart.getSelectedPeriod();
            chart.addIndicator(indicators.getIndicator("MA"), new Object[]{maPeriod, maType.ordinal()});
        }
    }

    public void onAccount(IAccount account) throws JFException {
    }

    public void onMessage(IMessage message) throws JFException {
    }

    public void onStop() throws JFException {
    }

    public void onTick(Instrument instrument, ITick tick) throws JFException {
        if (!instrument.equals(this.selectedInstrument)) {
            return;
        }
    }

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

        if (!instrument.equals(this.selectedInstrument)
                || !period.equals(this.selectedPeriod)) {
            return;
        }
        
        // open order signals with MA
        int barCount = 2;
        double[] ma = indicators.ma(instrument, this.selectedPeriod, selectedOfferSide, appliedPrice, maPeriod, maType, Filter.ALL_FLATS, barCount, askBar.getTime(), 0);
        // print derivative of last two bars
        printDouble(ma[1] - ma[0]);
    }

    private void printDouble(double d) {
        console.getOut().println((new DecimalFormat("#.#######")).format(d));
    }
}
