package jforex.test.markethours;

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

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

/**
 * The strategy creates a single order at the given time point
 */
public class TradeMarketHoursSdf implements IStrategy {
    
    private IConsole console;
    private IEngine engine;
    
    private Period period = Period.ONE_HOUR;
    private Instrument instrument = Instrument.AUDUSD;
    
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private String timeStr = "2008-08-25 04:00:00";
    
    @Override
    public void onStart(IContext context) throws JFException {
        console = context.getConsole();
        engine = context.getEngine();
        sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
    }
    
    private boolean timesEqual(String timeString, long barEndtime) throws JFException {  
        boolean result = false;
        try {
            long time = sdf.parse(timeString).getTime();            
            result = time == barEndtime;            
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return result;
    }
    
    @Override
    public void onBar(Instrument instrument, Period period, IBar askBar, IBar bidBar) throws JFException {
        if (period != this.period || instrument != this.instrument)
            return;

        if(this.timesEqual(timeStr, askBar.getTime() + period.getInterval())){
            engine.submitOrder("orderSellLimit", instrument, OrderCommand.SELLLIMIT, 0.3, 0.8633, 20);
        }
    }

    private void print(Object o) {
        console.getOut().println(o);
    }

    @Override
    public void onTick(Instrument instrument, ITick tick) throws JFException {    }
    @Override
    public void onMessage(IMessage message) throws JFException {
        print(sdf.format(message.getCreationTime())+ ": " +message);
    }
    @Override
    public void onAccount(IAccount account) throws JFException {    }
    @Override
    public void onStop() throws JFException {    }

}
