package jforex.experimental;

import com.dukascopy.api.*;

import static com.dukascopy.api.IEngine.OrderCommand.BUYLIMIT;
import static com.dukascopy.api.Instrument.EURUSD;

/**
 * To be executed on EURUSD at 2017-11-30 00:00 -> 24:00 UTC
 */
public class TslTestStrategy implements IStrategy {

    IContext context;
    IOrder o;
    double oldSL;
    double pip = EURUSD.getPipValue();
    ITick lastTick;

    private void info(String msg, Object... params) {
        String txt = String.format(msg, params);
        context.getConsole().getInfo().println(txt);
    }

    @Override
    public void onStart(IContext context) throws JFException {
        this.context = context;

        o = context.getEngine().submitOrder("Test_TSL", EURUSD, BUYLIMIT,
                /* amount */        0.1,
                /* price */       1.181,
                /* slippage */       10,
                /* stop-loss */       0,
                /* take-profit */ 1.191);
    }

    @Override public void onTick(Instrument instrument, ITick tick) throws JFException {
        if( instrument == EURUSD )
            lastTick = tick;
    }

    @Override public void onBar(Instrument instrument, Period period, IBar askBar, IBar bidBar) throws JFException {}

    @Override public void onMessage(IMessage message) throws JFException {
        IOrder o = message.getOrder();

        switch( message.getType() ) {
            case ORDER_FILL_OK:
                info("" + message);
                info(String.format("set tsl(price: %.5f, side: %s, pips: %s)",
                                   o.getOpenPrice() - 15 * pip, OfferSide.BID, 25));
                o.setStopLossPrice(o.getOpenPrice() - 15 * pip, OfferSide.BID, 25);
                oldSL = o.getStopLossPrice();

                break;

            case ORDER_CHANGED_OK:
                double newSL = o.getStopLossPrice();
                double slStep = oldSL == 0 ? 0 : (newSL - oldSL) / pip;
                double priceToSL = (lastTick.getBid() - newSL) / pip;

                info(String.format("%s, SL: %s, SL step: %.1f ---- Cur.price: %s, price-to-sl: %.1f pips",
                                   message, newSL, slStep, lastTick.getBid(), priceToSL));
                oldSL = newSL;
                break;
        }
    }

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

    @Override
    public void onStop() throws JFException {
        info("... stopped.");
    }
}
