package jforex.requests;

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 TemplateSignalsSTOCHONLY_log 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.THIRTY_MINS;
    @Configurable("Offer side")
    public OfferSide offerSide = OfferSide.BID;
    @Configurable("Slippage")
    public double slippage = 2;
    @Configurable("Amount")
    public double amount = 0.1;
    @Configurable("Take profit pips")
    public int takeProfitPips = 100;
    @Configurable("Stop loss in pips")
    public int stopLossPips = 100;
    @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;
    
    
    @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();
        
        println("start");

        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;
        }
        
        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 /*&& macd1[HIST] <= 0*/) {
        //    macdSign = OrderCommand.BUY;
       // }
       // if (macd0[HIST] < 0 /*&& macd1[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) {
            if(order != null) {
                if(!order.isLong()) {
                    order.close();
                    order = submitOrder(OrderCommand.BUY);
                    println(String.format("order=%s, stoch0: K=%.5f D=%.5f, stoch1: K=%.5f D=%.5f", order, stoch0[K], stoch0[D], stoch1[K], stoch1[D]));
                }
            } else {
                order = submitOrder(OrderCommand.BUY);
                println(String.format("order=%s, stoch0: K=%.5f D=%.5f, stoch1: K=%.5f D=%.5f", order, stoch0[K], stoch0[D], stoch1[K], stoch1[D]));
            }
            
            
        } else if(stochSign == OrderCommand.SELL) {
            if(order != null) {
                if(order.isLong()) {
                    order.close();
                    order = submitOrder(OrderCommand.SELL);
                    println(String.format("order=%s, stoch0: K=%.5f D=%.5f, stoch1: K=%.5f D=%.5f", order, stoch0[K], stoch0[D], stoch1[K], stoch1[D]));
                }
            } else {
                order = submitOrder(OrderCommand.SELL);
                println(String.format("order=%s, stoch0: K=%.5f D=%.5f, stoch1: K=%.5f D=%.5f", order, stoch0[K], stoch0[D], stoch1[K], stoch1[D]));
            }
        }
    }

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

    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);
            }
        }
        println(String.format("stopLossPrice=%.5f, stopLossPrice=%.5f", stopLossPrice, takeProfitPrice));
        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);
    }
}

