package jforex.orders2;

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

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

/**
 * The strategy on its start opens an order and in 3 increments
 * partially closes the order until it has been closed completely.
 * Strategy gets stopped once the order has been completely closed.
 *
 */
@RequiresFullAccess
public class PartialClose implements IStrategy {
    
    private IOrder order;
    private IEngine engine;
    private IConsole console;
    private IContext context;
    
    @SuppressWarnings("serial")
    public static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS") 
        {{    setTimeZone(TimeZone.getTimeZone("GMT")); }};

    @Override
    public void onStart(IContext context) throws JFException {
        engine = context.getEngine();
        console = context.getConsole();
        this.context = context;
        
        order = engine.submitOrder("order1", Instrument.EURUSD, OrderCommand.BUY, 1);
    }
    
    private void print(Object o){
        console.getOut().println(o);
    }

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

    @Override
    public void onBar(Instrument instrument, Period period, IBar askBar, IBar bidBar) throws JFException {
        if(instrument != Instrument.EURUSD || period != Period.TEN_SECS){
            return;
        }        
        if(order.getState() == IOrder.State.FILLED){
            order.close(0.4);
            order.waitForUpdate(2000);
            print(String.format("%s closePrice=%.5f, amount=%.3f, requestedAmount=%.3f, closeTime=%s, state=%s", 
                    order.getLabel(), order.getClosePrice(), order.getAmount(), order.getRequestedAmount(), 
                    sdf.format(order.getCloseTime()), order.getState()));
        }
    }

    @Override
    public void onMessage(IMessage message) throws JFException {
        print(message);
        if(order.getState() == IOrder.State.CLOSED){
            print("Order has been closed completely. Stop the strategy");
            print(String.format("%s closePrice=%.5f, amount=%.3f, requestedAmount=%.3f, closeTime=%s, state=%s", 
                    order.getLabel(), order.getClosePrice(), order.getAmount(), order.getRequestedAmount(), 
                    sdf.format(order.getCloseTime()), order.getState()));
            context.stop();
            return;
        }
    }

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

    @Override
    public void onStop() throws JFException {}

}
