package jforex.feed;

import com.dukascopy.api.*;
import com.dukascopy.api.feed.IRenkoBar;
import com.dukascopy.api.feed.IRenkoBarFeedListener;

/**
 * The strategy prints the last two renko bars in onTick whenever a new renko bar arrives
 *
 */
public class RenkoLastAndPrev implements IStrategy {

    private IConsole console;
    private IHistory history;

    @Configurable("Brick size (pips)")
    public int brickSize = 1;
    @Configurable("Instrument")
    public Instrument instrument = Instrument.EURUSD;
    @Configurable("Offer side")
    public OfferSide offerSide = OfferSide.BID;

    private IRenkoBar brick;
    private IRenkoBar brickPrevious;
    
    private PriceRange priceRange;
    boolean newBrick;

    @Override
    public void onStart(IContext context) throws JFException {
        this.console = context.getConsole();
        this.history = context.getHistory();
        
        priceRange = PriceRange.valueOf(brickSize);
        //read the first brick from the history - the next ones will come from the feed
        brick = history.getRenkoBar(instrument, offerSide, priceRange, 0);        
        
        context.subscribeToRenkoBarFeed(instrument, offerSide, priceRange, new IRenkoBarFeedListener (){
            @Override
            public void onBar(Instrument instrument, OfferSide offerSide, PriceRange brickSize, IRenkoBar feedBrick) {
                brick = feedBrick;
                newBrick = true;
            }});
    }

    @Override
    public void onTick(Instrument instrument, ITick tick) throws JFException {
        if(instrument == this.instrument){
            if(newBrick){
                brickPrevious = history.getRenkoBar(instrument, offerSide, priceRange, 1);
                print(String.format("\ncurr: %s \nprev: %s\n_______",  brick, brickPrevious));
            }
            newBrick = false;
        }
    }

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

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

}
