package jforex.stopmanager;

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

import com.dukascopy.api.*;
import com.dukascopy.api.IEngine.OrderCommand;
import com.dukascopy.api.IIndicators.AppliedPrice;
import com.dukascopy.api.IIndicators.MaType;
import com.dukascopy.api.indicators.IIndicator;

public class ATemplateSignals implements IStrategy {

    private IEngine engine;
    private IConsole console;
    private IHistory history;
    private IIndicators indicators;
    private IContext context;
    private int counter = 0;
    private IOrder order;
    @Configurable("Instrument")
    public Instrument instrument = Instrument.EURUSD;
    @Configurable("Period")
    public Period selectedPeriod = Period.FIVE_MINS;
    @Configurable("Offer side")
    public OfferSide offerSide = OfferSide.BID;
    @Configurable("Slippage")
    public double slippage = 0;
    @Configurable("Amount")
    public double amount = 0.02;
    @Configurable("Take profit pips")
    public int takeProfitPips = 0;
    @Configurable("Stop loss in pips")
    public int stopLossPips = 0;
    @Configurable("Applied price")
    public AppliedPrice appliedPrice = AppliedPrice.CLOSE;
    
    
    @Configurable("MACD Fast period")
    public int fastMACDPeriod = 12;
    @Configurable("MACD Slow period")
    public int slowMACDPeriod = 26;
    @Configurable("MACD Signal period")
    public int signalMACDPeriod = 9;
    
    
    @Configurable("STOCH Fast K period")
    public int fastKPeriod = 5;
    @Configurable("STOCH Slow K period")
    public int slowKPeriod = 3;
    @Configurable("STOCH K MA Type")
    public MaType slowKMaType =  MaType.SMA;
    @Configurable("STOCH Slow D period")
    public int slowDPeriod = 3;
    @Configurable("STOCH D MA Type")
    public MaType slowDMaType = MaType.SMA;
    
    @Configurable("Lock-in Pips for Breakeven (SLBE)")
    public int lockPip = 3;
    @Configurable("Stoploss Break Even Trigger (SLBET)")
    public int triggerPips = 40;
    @Configurable("Move stop to breakeven?")
    public boolean moveBE = true;
    
    
    @SuppressWarnings("serial")
    private final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") {

        {
            setTimeZone(TimeZone.getTimeZone("GMT"));
        }
    };

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

        IChart chart = context.getChart(instrument);
        if (chart != null) {
            chart.addIndicator(indicators.getIndicator("MACD"), new Object[]{fastMACDPeriod, slowMACDPeriod, signalMACDPeriod});
            chart.addIndicator(indicators.getIndicator("STOCH"));
        }
    }
    public static final int HIST = 2;

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

    public void onTick(Instrument instrument, ITick tick) throws JFException {
        if (instrument != this.instrument) {
            return;
        }
        
        stopManager(tick);
        
        if(!isActive(order)){
            order = null;
        }        
        
        // MACD SIGNAL
        OrderCommand macdSign = null;
        OrderCommand stochSign = null;
        
        double[] macd0 = indicators.macd(instrument, selectedPeriod, offerSide, appliedPrice, fastMACDPeriod, slowMACDPeriod, signalMACDPeriod, 0);
        double[] macd1 = indicators.macd(instrument, selectedPeriod, offerSide, appliedPrice, fastMACDPeriod, slowMACDPeriod, signalMACDPeriod, 1);

        if (macd0[HIST] > 0) {
            macdSign = OrderCommand.BUY;
        }
        if (macd0[HIST] < 0) {
            macdSign = OrderCommand.SELL;
        }
        
        // STOCH SIGNAL  
        int K = 0;
        int D = 1;        
        double[] stoch0 = indicators.stoch(instrument, selectedPeriod, offerSide, fastKPeriod, slowKPeriod, slowKMaType, slowDPeriod, slowDMaType, 0 );
        double[] stoch1 = indicators.stoch(instrument, selectedPeriod, offerSide, fastKPeriod, slowKPeriod, slowKMaType, slowDPeriod, slowDMaType, 1 );
        
        if(stoch0[K] > stoch0[D] && stoch1[K] <= stoch1[D]) {
            stochSign = OrderCommand.BUY;
            
        } else if(stoch0[K] < stoch0[D] && stoch1[K] >= stoch1[D]) {
            stochSign = OrderCommand.SELL;
        }
        
        // PLACE ORDER        
        if(stochSign == OrderCommand.BUY && macdSign == OrderCommand.BUY) {
            if(order != null) {
                if(!order.isLong()) {
                    order.close();
                    order = submitOrder(OrderCommand.BUY);
                }
            } else {
                order = submitOrder(OrderCommand.BUY);
            }
            
        } else if(stochSign == OrderCommand.SELL && macdSign == OrderCommand.SELL) {
            if(order != null) {
                if(order.isLong()) {
                    order.close();
                    order = submitOrder(OrderCommand.SELL);
                }
            } else {
                order = submitOrder(OrderCommand.SELL);
            }
        }
    }
    
    private void stopManager(ITick tick) throws JFException{
    	for (IOrder order : engine.getOrders(instrument)) {
            if (order.getState() == IOrder.State.FILLED) {
                boolean isLong;
                double open, newStop;
                String label = order.getLabel();
                IChart chart;

                isLong = order.isLong();
                open = order.getOpenPrice();

                if (isLong) { // long side order
                    if (moveBE && tick.getBid() > (open + toPrice(instrument, triggerPips))) {
                        // make it breakeven trade + lock in a few pips
                        newStop = open + toPrice(instrument, lockPip);
                        order.setStopLossPrice(newStop);
                        console.getOut().println(label + ": Moved stop to breakeven");

                        chart = this.context.getChart(instrument);
                        chart.draw(label + "_BE", IChart.Type.SIGNAL_UP, tick.getTime(), newStop);
                    }
                } else { // short side order
                    // Move to breakeven
                    if (moveBE && tick.getAsk() < (open - toPrice(instrument, triggerPips))) { // diff is negative
                        // make it breakeven trade + lock in a few pips
                        newStop = open - toPrice(instrument, lockPip);
                        order.setStopLossPrice(newStop);
                        console.getOut().println(label + ": Moved stop to breakeven");

                        chart = this.context.getChart(instrument);
                        chart.draw(label + "_BE", IChart.Type.SIGNAL_DOWN, tick.getTime(), newStop);
                    }
                }
            }
        }
    }
    
    private double toPrice(Instrument instr, int pips) {
        return instr.getPipValue() * pips;
    }


    public void onMessage(IMessage message) throws JFException {
    }

    public void onAccount(IAccount account) throws JFException {
    }

    public void onStop() throws JFException {
    }

    private IOrder submitOrder(OrderCommand orderCmd) throws JFException {

        double stopLossPrice = 0.0, takeProfitPrice = 0.0;

        // Calculating order price, stop loss and take profit prices
        if (orderCmd == OrderCommand.BUY) {
            if(stopLossPips > 0) {
                stopLossPrice = history.getLastTick(instrument).getBid() - getPipPrice(stopLossPips);
            }
            if(takeProfitPips > 0) {
                takeProfitPrice = history.getLastTick(instrument).getBid() + getPipPrice(takeProfitPips);
            }
        } else {
            if(stopLossPips > 0) {
                stopLossPrice = history.getLastTick(instrument).getBid() + getPipPrice(stopLossPips);
            }
            if(takeProfitPips > 0) {
                takeProfitPrice = history.getLastTick(instrument).getBid() - getPipPrice(takeProfitPips);
            }
        }

        return engine.submitOrder(getLabel(instrument), instrument, orderCmd, amount, 0, slippage, stopLossPrice, takeProfitPrice);
    }

    private void closeOrder(IOrder order) throws JFException {
        if (order == null) {
            return;
        }
        if (order.getState() != IOrder.State.CLOSED && order.getState() != IOrder.State.CREATED && order.getState() != IOrder.State.CANCELED) {
            order.close();
            order = null;
        }
    }
    
        
    private boolean isActive(IOrder order) throws JFException {
        if (order != null && order.getState() != IOrder.State.CLOSED && order.getState() != IOrder.State.CREATED && order.getState() != IOrder.State.CANCELED) {
            return true;
        }
        return false;
    }

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

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

    private void print(Object... o) {
        for (Object ob : o) {
            //console.getOut().print(ob + "  ");
            if (ob instanceof double[]) {
                print((double[]) ob);
            } else if (ob instanceof double[]) {
                print((double[][]) ob);
            } else if (ob instanceof Long) {
                print(dateToStr((Long) ob));
            } else {
                print(ob);
            }
            print(" ");
        }
        console.getOut().println();
    }

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

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

    private void print(double[] arr) {
        println(arrayToString(arr));
    }

    private void print(double[][] arr) {
        println(arrayToString(arr));
    }

    private void printIndicatorInfos(IIndicator ind) {
        for (int i = 0; i < ind.getIndicatorInfo().getNumberOfInputs(); i++) {
            println(ind.getIndicatorInfo().getName() + " Input " + ind.getInputParameterInfo(i).getName() + " " + ind.getInputParameterInfo(i).getType());
        }
        for (int i = 0; i < ind.getIndicatorInfo().getNumberOfOptionalInputs(); i++) {
            println(ind.getIndicatorInfo().getName() + " Opt Input " + ind.getOptInputParameterInfo(i).getName() + " " + ind.getOptInputParameterInfo(i).getType());
        }
        for (int i = 0; i < ind.getIndicatorInfo().getNumberOfOutputs(); i++) {
            println(ind.getIndicatorInfo().getName() + " Output " + ind.getOutputParameterInfo(i).getName() + " " + ind.getOutputParameterInfo(i).getType());
        }
        console.getOut().println();
    }

    public static String arrayToString(double[] arr) {
        String str = "";
        for (int r = 0; r < arr.length; r++) {
            str += "[" + r + "] " + (new DecimalFormat("#.#######")).format(arr[r]) + "; ";
        }
        return str;
    }

    public static String arrayToString(double[][] arr) {
        String str = "";
        if (arr == null) {
            return "null";
        }
        for (int r = 0; r < arr.length; r++) {
            for (int c = 0; c < arr[r].length; c++) {
                str += "[" + r + "][" + c + "] " + (new DecimalFormat("#.#######")).format(arr[r][c]);
            }
            str += "; ";
        }
        return str;
    }

    public String toDecimalToStr(double d) {
        return (new DecimalFormat("#.#######")).format(d);
    }

    public String dateToStr(Long time) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") {

            {
                setTimeZone(TimeZone.getTimeZone("GMT"));
            }
        };
        return sdf.format(time);
    }
}

