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.IIndicators.MaType;
import com.dukascopy.api.indicators.IIndicator;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Calendar;
import java.util.GregorianCalendar;

public class MAStrat3 implements IStrategy {

    private IEngine engine;
    private IConsole console;
    private IHistory history;
    private IIndicators indicators;
    private int counter = 0;
    private IOrder order;
    @Configurable("Instrument")
    public Instrument instrument = Instrument.EURUSD;
    @Configurable("Period")
    public Period selectedPeriod = Period.DAILY;
    @Configurable("MA period")
    public int maPeriod = 10;
    @Configurable("MA lookback")
    public int maLookback = 10;
    @Configurable("MA type")
    public MaType maType = MaType.SMA;
    @Configurable("Use ATR")
    public boolean useATR = true;
    @Configurable("ATR period")
    public int atrPeriod = 14;
    @Configurable("ATR multipler")
    public double atrMult = 1.4;
    @Configurable("Applied price")
    public AppliedPrice appliedPrice = AppliedPrice.CLOSE;
    @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("Stop loss pips")
    public int stopLossPips = 0;

    @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("MA"), new Object[]{maPeriod, maType.ordinal()});
        }
    }

    @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;
        } else if (order.equals(IOrder.State.CREATED)) {
            return;
        }

        boolean sellSign = false;
        boolean buySign = false;

        IBar bar = offerSide.equals(OfferSide.ASK) ? askBar : bidBar;
        IBar todayBar = history.getBars(instrument, period, offerSide, filter, 0, bar.getTime(), 1).get(0);
        IBar oldBar = history.getBars(instrument, period, offerSide, filter, 40, bar.getTime(), 0).get(0);

        double[] ma10 = indicators.ma(instrument, selectedPeriod, offerSide, appliedPrice, maPeriod, maType, filter, 10, bar.getTime(), 0);
        double[] ma0 = indicators.ma(instrument, selectedPeriod, offerSide, appliedPrice, maPeriod, maType, filter, 1, bar.getTime(), 0);

        double[] atr = indicators.atr(instrument, selectedPeriod, offerSide, atrPeriod, filter, 1, bar.getTime(), 0);
        double atrVal = atrMult * atr[0];

        double c1 = bar.getClose() - ma10[0];
        double c2 = oldBar.getClose() - ma0[0];

        if (c1 > 0 && c2 > 0) {
            buySign = true;
        }
        if (c1 < 0 && c2 < 0) {
            sellSign = true;
        }


        boolean updateSL = true;

        // PLACE ORDER
        if (buySign) {
            if (order == null || !order.isLong()) {
                closeOrder(order);
                double stopLoss = 0.0;
                if(useATR) {
                    stopLoss = todayBar.getClose() - atrVal;
                    stopLoss = round(stopLoss, instrument);                    
                }
                order = submitOrder(OrderCommand.BUY, instrument, stopLoss);
                updateSL = false;
            }

        } else if (sellSign) {
            if (order == null || order.isLong()) {
                closeOrder(order);
                double stopLoss = 0.0;
                if(useATR) {
                    stopLoss = todayBar.getClose() + atrVal;
                    stopLoss = round(stopLoss, instrument);                    
                }
                order = submitOrder(OrderCommand.SELL, instrument, stopLoss);
                updateSL = false;
            }
        }
        
        // UPDATE STOP LOSS
        if(updateSL && useATR && order != null) {
            double stopLoss;
            if(order.isLong()) {
                stopLoss = order.getOpenPrice() - atrVal;
            } else {
                stopLoss = order.getOpenPrice() + atrVal;
            }
            
            stopLoss = round(stopLoss, instrument);
            if(stopLoss != order.getStopLossPrice()) {
                order.setStopLossPrice(stopLoss);
            }
        }
    }

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

    
    private IOrder submitOrder(OrderCommand orderCmd, Instrument instr, double stopLossPrice) throws JFException {

        double takeProfitPrice = 0.0;
        
        ITick t = history.getLastTick(instr);

        // Calculating order price, stop loss and take profit prices
        if (orderCmd.isLong()) {
            if(stopLossPrice == 0.0 && stopLossPips > 0) {
                stopLossPrice = t.getBid() - pip(stopLossPips, instr);
            }
            if(takeProfitPips > 0) {
                takeProfitPrice = t.getBid() + pip(takeProfitPips, instr);
            }
        } else {
            if(stopLossPrice == 0.0 && stopLossPips > 0) {
                stopLossPrice = t.getAsk() + pip(stopLossPips, instr);
            }
            if(takeProfitPips > 0) {
                takeProfitPrice = t.getAsk() - pip(takeProfitPips, instr);
            }
        }

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

    private void closeOrder(IOrder order) throws JFException {
        if (order == null) {
            return;
        }
        if (order.getState() == IOrder.State.CREATED) {
            order.waitForUpdate();
        }
        if (order.getState() != IOrder.State.CLOSED && order.getState() != IOrder.State.CANCELED) {
            order.close();
            order.waitForUpdate();
            if (order.getState() == IOrder.State.FILLED) {
                // order OPENNED -> order.close() -> order FILLED -> recieves message ORDER_ALREADY_FILLED -> resend order.close()
                order.close();
            }
        }
    }

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

    private double pip(double pips, Instrument instr) {
        return pips * instr.getPipValue();
    }

    private String getLabel(Instrument instr) {
        String label = instr.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;
    }

    public void updateTrailingStopLoss(ITick tick, IOrder pOrder, double pTriggerPips, double pStopLossPips) throws JFException {

        if (pStopLossPips > 0 && pOrder != null && pOrder.getState() == IOrder.State.FILLED) {

            Instrument instr = pOrder.getInstrument();

            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 ((currentStopLoss == 0.0 || tick.getBid() > currentStopLoss + pip(pStopLossPips, instr))
                        && tick.getBid() > openPrice + pip(pTriggerPips, instr)) {
                    // trailing stop loss
                    newStop = tick.getBid() - pip(pStopLossPips, instr);
                    newStop = round(newStop, instr);

                    if (currentStopLoss != newStop) {
                        pOrder.setStopLossPrice(newStop);
                        return;
                    }
                }

            } else { // short side order            
                if ((currentStopLoss == 0.0 || tick.getAsk() < currentStopLoss - pip(pStopLossPips, instr))
                        && tick.getAsk() < openPrice - pip(pTriggerPips, instr)) {

                    // trailing stop loss
                    newStop = tick.getAsk() + pip(pStopLossPips, instr);
                    newStop = round(newStop, instr);

                    if (currentStopLoss != newStop) {
                        pOrder.setStopLossPrice(newStop);
                        return;
                    }
                }
            }
        }
    }

    private double round(double price, Instrument instr) {
        BigDecimal bd = new BigDecimal(price);
        bd = bd.setScale(instr.getPipScale() + 1, RoundingMode.HALF_UP);
        return bd.doubleValue();
    }

    private double roundPips(double pips) {
        BigDecimal bd = new BigDecimal(pips);
        bd = bd.setScale(1, RoundingMode.HALF_UP);
        return bd.doubleValue();
    }

    public void onMessage(IMessage message) throws JFException {
        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));
    }
}
