package testStrategy;

import com.dukascopy.api.*;

import java.util.HashSet;
import java.util.Set;

public class testOrderLabel implements IStrategy {
    private IConsole myConsole;
    private IContext myContext;
    private IHistory myHistory;
    private IEngine myEngine;
    private IOrder myOrder;

    public Instrument myInstrument=Instrument.EURUSD;
    public Period myPeriod=Period.DAILY;

    private int myOrderCounter=0;



    @Override
    public void onStart(IContext context) throws JFException {
        myContext=context;
        myConsole=context.getConsole();
        myHistory=context.getHistory();
        myEngine=context.getEngine();


        Set<Instrument> instruments=new HashSet<Instrument>();
        instruments.add(myInstrument);
        myContext.setSubscribedInstruments(instruments,true);

    }

    @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==myInstrument && period==myPeriod){
            myOrder=myEngine.submitOrder("mySimpleOrder"+ ++myOrderCounter,myInstrument,IEngine.OrderCommand.SELL,0.01);
            myOrder.waitForUpdate(1000);
            myConsole.getOut().println(myOrder.getLabel()+" is opened and filled!");
            double myStopLossPrice=myOrder.getOpenPrice()+60*myInstrument.getPipValue();
            myOrder.setStopLossPrice(myStopLossPrice,OfferSide.ASK,20);
            myOrder.waitForUpdate(1000);
            myConsole.getOut().println(myOrder+"stopLoss is setted!");

        }

    }

    @Override
    public void onMessage(IMessage message) throws JFException {
        if(message.getOrder()==myOrder && message.getReasons().contains(IMessage.Reason.ORDER_CHANGED_SL)){
            boolean OrderLabelEqual=message.getOrder().getLabel()=="mySimpleOrder"+myOrderCounter;
            myConsole.getInfo().println(myOrder.getLabel()+"'s stop loss changed to: "
                    +myOrder.getStopLossPrice()+"|| OrderLabelEqual: "+OrderLabelEqual);
        }

        if(message.getOrder()==myOrder && message.getReasons().contains(IMessage.Reason.ORDER_CLOSED_BY_SL)){

            myConsole.getWarn().println(myOrder.getLabel()+" is closed at: "
                    +myOrder.getClosePrice()+"|| PL is: "+myOrder.getProfitLossInPips());

        }

    }

    @Override
    public void onAccount(IAccount account) throws JFException {

    }

    @Override
    public void onStop() throws JFException {

    }
}
