package jforex.data.async;

import com.dukascopy.api.*;
import com.dukascopy.api.feed.IRenkoBar;
import com.dukascopy.api.feed.IRenkoBarFeedListener;
import java.text.SimpleDateFormat;
import java.util.TimeZone;

/**
 * The strategy asynchonously reads 2 pip renko bars over the last hour
 * and stops the strategy once the reading has been finished
 *
 */
public class ReadRenkos implements IStrategy {

    private IHistory history;
    private IConsole console;
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
    
    @Override
    public void onStart(final IContext context) throws JFException {
        history = context.getHistory();
        console = context.getConsole();
        
        sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
        
        long to = history.getLastTick(Instrument.XAUUSD).getTime();
        //console.getOut().println("LastTick="+sdf.format(to));
        //long from = to - Period.ONE_HOUR.getInterval();
        to = history.getRenkoBar(Instrument.XAUUSD, OfferSide.BID, PriceRange.valueOf(89), 0).getEndTime();
        
        long from = history.getRenkoBar(Instrument.XAUUSD, OfferSide.BID, PriceRange.valueOf(89), 15).getTime();
        
        console.getOut().println("from="+sdf.format(from)+"   to="+sdf.format(to));

        history.readRenkoBars(Instrument.XAUUSD, OfferSide.BID, PriceRange.valueOf(89), from, to, 
            new IRenkoBarFeedListener(){
                @Override
                public void onBar(Instrument instrument, OfferSide offerSide, PriceRange brickSize, IRenkoBar bar) {
                    console.getOut().println(bar);
                    
                }},
            new LoadingProgressListener(){

                @Override
                public void dataLoaded(long start, long end, long currentPosition, String information) {}

                @Override
                public void loadingFinished(boolean allDataLoaded, long start, long end, long currentPosition) {
                    if(allDataLoaded){
                        console.getOut().println("Loading finished! Stopping the strategy.");
                        context.stop();
                    }                    
                }

                @Override
                public boolean stopJob() {
                    return false;
                }
            }
        );
    }    

    @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 {}

}
