package jforex.orders;

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

import com.dukascopy.api.*;
import com.dukascopy.api.IEngine.OrderCommand;

public class OrderPerChartBar implements IStrategy {

    @Configurable("")
    public Period period = Period.TEN_SECS;
    
    private IConsole console;
    private IContext context;
    private IEngine engine;
    
    @SuppressWarnings("serial")
    public static SimpleDateFormat sdfTimeOnly = new SimpleDateFormat("HH_mm_ss") {
        {
            setTimeZone(TimeZone.getTimeZone("GMT"));
        }
    };
    
    @Override
    public void onStart(IContext context) throws JFException {
        this.context = context;
        this.console = context.getConsole();
        this.engine = context.getEngine();

    }

    @Override
    public void onBar(Instrument instrument, Period period, IBar askBar, IBar bidBar) throws JFException {
        if(this.period != period){
            return;
        }
        IChart chart = context.getChart(instrument);
        print("%s %s bar arrived: %s",instrument, period, bidBar);
        if(chart == null){
            console.getWarn().println(instrument +" chart is null");
            return;
        }
        if(chart.getSelectedPeriod() != period){
            console.getWarn().println(instrument +" chart period "+chart.getSelectedPeriod()+" != " + period);
            return;
        }
        
        String label = String.format("%s_%s",instrument.getPrimaryCurrency(), sdfTimeOnly.format( bidBar.getTime()));
        IOrder order = engine.submitOrder(label, instrument, OrderCommand.BUY, 0.001);
        print("chart period is OK, submitted order "+ order);
    }
    
    private void print(String format, Object...args){
        print(String.format(format,args));
    }
    
    private void print(Object o){
        console.getOut().println(o);
    }

    @Override
    public void onMessage(IMessage message) throws JFException {
        if(message.getOrder() != null){ //only print order related messages
            console.getInfo().println(message);
        }
    }

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

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

    @Override
    public void onStop() throws JFException {}

}
