package jforex.strategies.indicators;

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.indicators.IIndicator;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Calendar;
import java.util.GregorianCalendar;

public class ADXStrat implements IStrategy {
    
    private IEngine engine;
    private IConsole console;
    private IHistory history;
    private IIndicators indicators;
    private IAccount account;
    private int counter = 0;
    private IOrder order;
        
    
    @Configurable("Applied price")
    public AppliedPrice appliedPrice = AppliedPrice.CLOSE;
    @Configurable("ADX period")
    public int adxPeriod = 14;
    @Configurable("DX+ period")
    public int plusDiPeriod = 14;
    @Configurable("DX- period")
    public int minusDiPeriod = 14;
    @Configurable("+/- points")
    public int points = 5;
    
    
    @Configurable("Instrument")
    public Instrument instrument = Instrument.EURUSD;
    @Configurable("Period")
    public Period selectedPeriod = Period.TEN_MINS;
    @Configurable("Offer side")
    public OfferSide offerSide = OfferSide.BID;
    @Configurable("Slippage")
    public double slippage = 0;
    @Configurable("Amount")
    public double amount = 0.02;
    @Configurable("Filter")
    public Filter filter = Filter.ALL_FLATS;
    
    @Configurable("Take profit pips")
    public int takeProfitPips = 0;
    @Configurable("Trailing Stop loss in pips")
    public int stopLossPips = 15;

    @Override
    public void onStart(IContext context) throws JFException {
        this.console = context.getConsole();
        this.indicators = context.getIndicators();
        this.history = context.getHistory();
        this.engine = context.getEngine();
        
        IChart chart = context.getChart(instrument);
        if (chart != null) {
            chart.addIndicator(indicators.getIndicator("ADX"), new Object[]{adxPeriod});
            chart.addIndicator(indicators.getIndicator("PLUS_DI"), new Object[]{plusDiPeriod});
            chart.addIndicator(indicators.getIndicator("MINUS_DI"), new Object[]{minusDiPeriod});
        }
    }
    
    @Override
    public void onBar(Instrument instrument, Period period, IBar askBar, IBar bidBar) throws JFException {
        if (period != this.selectedPeriod || instrument != this.instrument) {
            return;
        }
        
        if (!isActive(order)) {
            order = null;
        }

        // ADX SIGNAL
        boolean sellSign1 = false;
        boolean buySign1 = false;
        
        double[] adx = indicators.adx(instrument, selectedPeriod, offerSide, adxPeriod, filter, 3, askBar.getTime(), 0);
        double[] plusDi = indicators.plusDi(instrument, selectedPeriod, offerSide, plusDiPeriod, filter, 3, askBar.getTime(), 0);
        double[] minusDi = indicators.minusDi(instrument, selectedPeriod, offerSide, minusDiPeriod, filter, 3, askBar.getTime(), 0);
        
        if (adx[0] < adx[1] && adx[1] < adx[2] &&
                plusDi[2] > adx[2] + points && plusDi[2] > minusDi[2]) {  
            print(adx[2], toStr(askBar.getTime()));
            buySign1 = true;
        } else if (adx[0] > adx[1] && adx[1] > adx[2] &&
                minusDi[2] > adx[2] + points && minusDi[2] > plusDi[2]) {                    
            sellSign1 = true;
            print(adx[2], toStr(askBar.getTime()));
        }
        
        // PLACE ORDER        
        if (buySign1) {
            if (order == null || !order.isLong()) {
                closeOrder(order);
                order = submitOrder(OrderCommand.BUY, instrument);
            }

        } else if (sellSign1) {
            if (order == null || order.isLong()) {
                closeOrder(order);
                order = submitOrder(OrderCommand.SELL, instrument);
            }
        }

    }

    public void onTick(Instrument instrument, ITick tick) throws JFException {
        if (instrument != this.instrument) {
            return;
        }
    }

    private IOrder submitOrder(OrderCommand orderCmd, Instrument instr) throws JFException {

        double stopLossPrice = 0.0, takeProfitPrice = 0.0;
        OfferSide orderSide;

        // Calculating order price, stop loss and take profit prices
        if (orderCmd == OrderCommand.BUY) {
            if(stopLossPips > 0) {
                stopLossPrice = history.getLastTick(instr).getBid() - getPipPrice(stopLossPips);
            }
            if(takeProfitPips > 0) {
                takeProfitPrice = history.getLastTick(instr).getBid() + getPipPrice(takeProfitPips);
            }
            orderSide = OfferSide.BID;
        } else {
            if(stopLossPips > 0) {
                stopLossPrice = history.getLastTick(instr).getBid() + getPipPrice(stopLossPips);
            }
            if(takeProfitPips > 0) {
                takeProfitPrice = history.getLastTick(instr).getBid() - getPipPrice(takeProfitPips);
            }
            orderSide = OfferSide.ASK;
        }
        
        IOrder order = engine.submitOrder(getLabel(instr), instr, orderCmd, amount, 0, slippage, 0, takeProfitPrice);
        order.waitForUpdate(2000);
        order.setStopLossPrice(stopLossPrice, orderSide, 10);
        return order;
    }

    private void closeOrder(IOrder order) throws JFException {
        if (order != null && isActive(order)) {
            order.close();
        }
    }

    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(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 boolean timeIsEqual(long time, int hour, int min){
        Calendar cal = new GregorianCalendar();
        cal.setTimeZone(TimeZone.getTimeZone("GMT"));
        cal.setTimeInMillis(time);
        cal.set(Calendar.HOUR_OF_DAY, hour);
        cal.set(Calendar.MINUTE, min);

        Calendar cal2 = new GregorianCalendar();
        cal2.setTimeZone(TimeZone.getTimeZone("GMT"));
        cal2.setTimeInMillis(cal.getTimeInMillis());
        cal2.add(Calendar.MINUTE, 5);

        if(cal.getTimeInMillis() <= time
                && time <= cal2.getTimeInMillis() ) {
            return true;
        }
        return false;
    }
    
        
    public boolean isRightTime(long time, int fromHour, int fromMin, int toHour, int toMin){
        Calendar cal = new GregorianCalendar();
        cal.setTimeZone(TimeZone.getTimeZone("GMT"));
        cal.setTimeInMillis(time);
        cal.set(Calendar.HOUR_OF_DAY, fromHour);
        cal.set(Calendar.MINUTE, fromMin);

        Calendar cal2 = new GregorianCalendar();
        cal2.setTimeZone(TimeZone.getTimeZone("GMT"));
        cal2.setTimeInMillis(time);
        cal2.set(Calendar.HOUR_OF_DAY, toHour);
        cal2.set(Calendar.MINUTE, toMin);

        if(cal.getTimeInMillis() <= time
                && time <= cal2.getTimeInMillis() ) {
            return true;
        }
        return false;
    }
    
    
        // sets stop loss to "tick.getAsk - pStopLossPips" if price is higher than "pOrder.getOpenPrice() + pTriggerPips"
    public boolean updateTrailingStopLoss(ITick tick, IOrder pOrder, double pTriggerPips, double pStopLossPips) throws JFException {
        boolean triggered = false;
        if (    pTriggerPips > 0 && pStopLossPips > 0 &&
                pOrder != null && pOrder.getState() == IOrder.State.FILLED) {
            double newStop;
            double openPrice = pOrder.getOpenPrice();
            double currentStopLoss = pOrder.getStopLossPrice();

            // (START) trailing stop loss is activated when price is higher than oper price + trailingTrigger pips
            // (TRAILING STOP) if price moves further up (for BUY order), stop loss is updated to stopLossPips

            if (pOrder.isLong()) { // long side order                
                if (       tick.getBid() > currentStopLoss + getPipPrice(pStopLossPips)
                        && tick.getBid() > openPrice + getPipPrice(pTriggerPips)) {
                    // trailing stop loss
                    newStop = tick.getBid() - getPipPrice(pStopLossPips);
                    newStop = (new BigDecimal(newStop)).setScale(instrument.getPipScale(), BigDecimal.ROUND_HALF_UP).doubleValue();

                    if (currentStopLoss != newStop) {
                        pOrder.setStopLossPrice(newStop);
                        triggered = true;
                    }
                }

            } else { // short side order                
                if (        tick.getAsk() < currentStopLoss - getPipPrice(pStopLossPips)
                        && tick.getAsk() < openPrice - getPipPrice(pTriggerPips)) {
                    // trailing stop loss
                    newStop = tick.getAsk() + getPipPrice(pStopLossPips);
                    newStop = (new BigDecimal(newStop)).setScale(instrument.getPipScale(), BigDecimal.ROUND_HALF_UP).doubleValue();

                    if (currentStopLoss != newStop) {
                        pOrder.setStopLossPrice(newStop);
                        triggered = true;
                    }
                }
            }
        }
        return triggered;
    }
    
    
    
    private double getRoundedPrice(double price) {
        BigDecimal bd = new BigDecimal(price);
        bd = bd.setScale(instrument.getPipScale() + 1, RoundingMode.HALF_UP);
        return bd.doubleValue();
    }

    private double getRoundedPips(double pips) {
        BigDecimal bd = new BigDecimal(pips);
        bd = bd.setScale(1, RoundingMode.HALF_UP);
        return bd.doubleValue();
    }

    public void onMessage(IMessage message) throws JFException {
        if(message.getType() == IMessage.Type.ORDER_CHANGED_OK ||
                message.getType() == IMessage.Type.ORDER_CLOSE_OK ||
                message.getType() == IMessage.Type.ORDER_FILL_OK ||
                message.getType() == IMessage.Type.ORDER_SUBMIT_OK) {
            return;
        }
        print(message);
    }

    public void onAccount(IAccount account) throws JFException {
    }

    public void onStop() throws JFException {
    }

    /**************** debug print functions ***********************/
    private void print(Object... o) {
        for (Object ob : o) {
            //console.getOut().print(ob + "  ");
            if (ob instanceof Double) {
                print2(toStr((Double) ob));
            } else if (ob instanceof double[]) {
                print((double[]) ob);
            } else if (ob instanceof double[]) {
                print((double[][]) ob);
            } else if (ob instanceof Long) {
                print2(toStr((Long) ob));
            } else if (ob instanceof IBar) {
                print2(toStr((IBar) ob));
            } else {
                print2(ob);
            }
            print2(" ");
        }
        console.getOut().println();
    }

    private void print(Object o) {
        console.getOut().println(o);
    }

    private void print2(Object o) {
        console.getOut().print(o);
    }
    
    private void print(double d) {
        print(toStr(d));
    }

    private void print(double[] arr) {
        print(toStr(arr));
    }

    private void print(double[][] arr) {
        print(toStr(arr));
    }
    private void print(IBar bar) {
        print(toStr(bar));
    }

    private void printIndicatorInfos(IIndicator ind) {
        for (int i = 0; i < ind.getIndicatorInfo().getNumberOfInputs(); i++) {
            print(ind.getIndicatorInfo().getName() + " Input " + ind.getInputParameterInfo(i).getName() + " " + ind.getInputParameterInfo(i).getType());
        }
        for (int i = 0; i < ind.getIndicatorInfo().getNumberOfOptionalInputs(); i++) {
            print(ind.getIndicatorInfo().getName() + " Opt Input " + ind.getOptInputParameterInfo(i).getName() + " " + ind.getOptInputParameterInfo(i).getType());
        }
        for (int i = 0; i < ind.getIndicatorInfo().getNumberOfOutputs(); i++) {
            print(ind.getIndicatorInfo().getName() + " Output " + ind.getOutputParameterInfo(i).getName() + " " + ind.getOutputParameterInfo(i).getType());
        }
        console.getOut().println();
    }

    public static String toStr(double[] arr) {
        String str = "";
        for (int r = 0; r < arr.length; r++) {
            str += "[" + r + "] " + (new DecimalFormat("#.#######")).format(arr[r]) + "; ";
        }
        return str;
    }

    public static String toStr(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 toStr(double d) {
        return (new DecimalFormat("#.#######")).format(d);
    }

    public String toStr(long time) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") {

            {
                setTimeZone(TimeZone.getTimeZone("GMT"));
            }
        };
        return sdf.format(time);
    }
    
    private String toStr(IBar bar) {
        return toStr(bar.getTime()) + "  O:" + bar.getOpen() + " C:" + bar.getClose() + " H:" + bar.getHigh() + " L:" + bar.getLow();
    }

    private void printTime(Long time) {
        console.getOut().println(toStr(time));
    }

}
