package jforex.requests;

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

public class OneTradePerBar implements IStrategy {
    
    @Configurable("")
    public Period period = Period.TEN_SECS;
    @Configurable("")
    public Instrument instrument = Instrument.EURUSD;
    
    private IEngine engine;
    private IConsole console;
    private IHistory history;
    

    @Override
    public void onStart(IContext context) throws JFException {
        engine = context.getEngine();
        console = context.getConsole();
        history = context.getHistory();
        
        
    }

    @Override
    public void onTick(Instrument instrument, ITick tick) throws JFException {
        if(instrument != this.instrument){
            return;
        }
        
        makeOrder(instrument, period);
    }
    
    private int orderCounter;
    private void makeOrder(Instrument instrument, Period period) throws JFException {
        IBar bar = history.getBar(instrument, period, OfferSide.BID, 0);
        for(IOrder order : engine.getOrders(instrument)){
            if(order.getCreationTime() > bar.getTime()){
                console.getOut().println("There is an order already opened within the current bar for "+instrument);
                return;
            }
        }
        console.getOut().println("active orders: " + engine.getOrders(instrument));
        engine.submitOrder("order"+ ++orderCounter, instrument, OrderCommand.BUY, 0.001);
    }

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

}
