import com.dukascopy.api.Configurable;
import com.dukascopy.api.IAccount;
import com.dukascopy.api.IBar;
import com.dukascopy.api.IConsole;
import com.dukascopy.api.IContext;
import com.dukascopy.api.IEngine;
import com.dukascopy.api.IEngine.OrderCommand;
import com.dukascopy.api.IHistory;
import com.dukascopy.api.IMessage;
import com.dukascopy.api.IOrder;
import com.dukascopy.api.IStrategy;
import com.dukascopy.api.ITick;
import com.dukascopy.api.Instrument;
import com.dukascopy.api.JFException;
import com.dukascopy.api.Period;
import java.text.DecimalFormat;

public class Grids_On_Counter_Zero_V1 implements IStrategy {

    public int tradesTotalBUY(Instrument INS) throws JFException {
        int counter1 = 0;
        for (IOrder ORD : engine.getOrders(INS)) {
            if (ORD.getState() == IOrder.State.FILLED && ORD.isLong()) {
                counter1++;
            }
        }
        return counter1;
    }

    public int tradesTotalSELL(Instrument INS) throws JFException {
        int counter2 = 0;
        for (IOrder ORD : engine.getOrders(INS)) {
            if (ORD.getState() == IOrder.State.FILLED && !ORD.isLong()) {
                counter2++;
            }
        }
        return counter2;
    }

    private IEngine engine;
    private IConsole console;
    private int counter = 0;
    private IHistory history;
    private ITick previousTick = null;
    private String string = "";

    @Configurable("Step pips")
    public double step = 20;
    @Configurable("Instrument")
    public Instrument instrument = Instrument.EURUSD;
    @Configurable("Slippage")
    public double slippage = 2;
    @Configurable("Amount")
    public double amount = 0.1;

    @Configurable("Stop Loss Pips")
    public int slPips = 20;
    
    @Configurable("Take Profit Pips")
    public int takeProfitPips = 20;

    @Configurable("Total take profit Money")
    public double tpProfit = 0;
    
    @Configurable("Total take loss Money")
    public double ngProfit = 0;
    private double balance;
    @Override
    public void onStart(IContext context) throws JFException {
        this.console = context.getConsole();
        this.engine = context.getEngine();
        this.setHistory(context.getHistory());

        balance = context.getAccount().getEquity();
        console.getOut().println("initial balance " + (new DecimalFormat("#.#######")).format(balance));

    }

    @Override
    public void onBar(Instrument instrument, Period period, IBar askBar, IBar bidBar) throws JFException {
        if (instrument != this.instrument) {
            return;
        }
    }

    public void onTick(Instrument instrument, ITick tick) throws JFException {
        
        if (instrument != this.instrument) {
            return;
        }
        if (previousTick == null) {
            previousTick = tick;
            return;
        }

        if (tick.getBid() >= previousTick.getBid() + getPipPrice(step)) {
            if (tradesTotalSELL(instrument) == 0) {
                string = "SELL@Step";
                submitOrder(OrderCommand.SELL, instrument);
                previousTick = tick;
            }
            previousTick = tick;

        } else if (tick.getAsk() <= previousTick.getAsk() - getPipPrice(step)) {
            if (tradesTotalBUY(instrument) == 0) {
                string = "BUY@Step";
                submitOrder(OrderCommand.BUY, instrument);
                previousTick = tick;
            }
        }
    }

    private double getPipPrice(double pips) {
        return pips * this.instrument.getPipValue();
    }

    private String getLabel(Instrument instrument) {
        String label = instrument.name();
        label = label + (counter++);
        label = label.toUpperCase();
        return label;
    }

    public void onMessage(IMessage message) throws JFException {
        print(message);
    }

    public void onStop() throws JFException {
    }

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

    public IHistory getHistory() {
        return history;
    }

    public void setHistory(IHistory history) {
        this.history = history;
    }

    private IOrder submitOrder(OrderCommand orderCmd, Instrument instrument) throws JFException {
        double stopLossPrice = 0.0, takeProfitPrice = 0.0;
        if (orderCmd == OrderCommand.BUY) {
            if (slPips > 0) {
                stopLossPrice = history.getLastTick(instrument).getBid() - getPipPrice(slPips);
            }
            if (takeProfitPips > 0) {
                takeProfitPrice = history.getLastTick(instrument).getBid() + getPipPrice(takeProfitPips);
            }
        } else if (orderCmd == OrderCommand.SELL) {
            if (slPips > 0) {
                stopLossPrice = history.getLastTick(instrument).getBid() + getPipPrice(slPips);
            }
            if (takeProfitPips > 0) {
                takeProfitPrice = history.getLastTick(instrument).getBid() - getPipPrice(takeProfitPips);
            }
        }

        return engine.submitOrder(getLabel(instrument), instrument, orderCmd, amount, 0, slippage, stopLossPrice,takeProfitPrice,0,string);
    }
    public void onAccount(IAccount account) throws JFException {

        double pozitivebalance = balance + tpProfit;
        double negativebalance = balance - ngProfit;

        if (tpProfit > 0) {
        if (pozitivebalance < history.getEquity()) {
            for (IOrder order : engine.getOrders()) {
                if (order.getState() != IOrder.State.CLOSED && order.getState() != IOrder.State.CANCELED) {
                    order.close();
            }}
            balance = account.getEquity();
            console.getOut().println("UP balance " + (new DecimalFormat("#.#######")).format(balance));
            }}
       if (ngProfit > 0) {        
        if (negativebalance > history.getEquity()) {
            for (IOrder order : engine.getOrders()) {
                if (order.getState() != IOrder.State.CLOSED && order.getState() != IOrder.State.CANCELED) {
                    order.close();
            }}

            balance = account.getEquity();
            console.getOut().println("DOWN balance " + (new DecimalFormat("#.#######")).format(balance));
            }
        }
    }
}
