package jforex.feed.test;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;

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

/**
 * The following strategy demonstrates how one can bind an arbitrary set of indicators
 * with corresponding feed descriptors, such that each indicator with its feed descriptor 
 * can be used both for indicator calculation and indicator plotting on the chart.
 *
 */

public class dragondeuxmilletreize implements IStrategy {

    private IConsole console;
    private IIndicators indicators;
    private IContext context;
    private IEngine engine;
    private IHistory history;
    private IUserInterface userInterface;
    private SimpleDateFormat sdf;



    @Configurable("")
    public Instrument instrument = Instrument.GBPJPY;
    
    public int counter;
    
    @Configurable("Period")
    public Period selectedPeriodq = Period.FIFTEEN_MINS;
    
    @Configurable("Period")
    public Period selectedPeriodh = Period.ONE_HOUR;

    @Configurable("Period")
    public Period selectedPeriodc = Period.FIVE_MINS;
        
    @Configurable("Period")
    public Period selectedPeriodm = Period.ONE_MIN;      
                    
    @Configurable("SMA filter")
    public Filter indicatorFilter = Filter.NO_FILTER;
    @Configurable("Amount")
    public double amount = 0.1;
    @Configurable("Stop loss")
    public int stopLossPips = 20;
    
    
    
    @Configurable("Take profit")
    public int takeProfitPips = 100;
    

    
    
    @Configurable("")
    public OfferSide side = OfferSide.BID;

    public int w=0;

    public double ccio;
    public double macdd;
    public double ccim;
    public double ccih;
    public double rsim;
    public double rsih;
    public double cciq;
    public double ccic;



    class IndDataAndFeed{
        
        private IFeedDescriptor feedDescriptor;
        private String indicatorName;
        private Object[] optionalInputs;
        private int outputIndex;
        private IIndicator indicator;
        private IChart chart;
        
        public IndDataAndFeed(String indicatorName, Object[] optionalInputs, int outputIndex, IFeedDescriptor feedDescriptor) {
            this.feedDescriptor = feedDescriptor;
            this.indicatorName = indicatorName;
            this.optionalInputs = optionalInputs;
            this.outputIndex = outputIndex;
        }
        
        public void openChartAddIndicator(){
            if ( context.getCharts(feedDescriptor.getInstrument()) == null ) 
                       {return;}
            for(IChart openedChart : context.getCharts(feedDescriptor.getInstrument())){
                IFeedDescriptor chartFeed = openedChart.getFeedDescriptor();
                if(chartFeed.getPeriod() == feedDescriptor.getPeriod() && chartFeed.getOfferSide() == feedDescriptor.getOfferSide()){
                    chart = openedChart;
                }
            }
            if(chart == null){
                chart = context.openChart(feedDescriptor);
            }
            indicator = indicators.getIndicator(indicatorName);
            chart.add(indicator, optionalInputs);
        }
        
        public double getCurrentValue() throws JFException{
            Object[] outputs = indicators.calculateIndicator(feedDescriptor, new OfferSide[] { side },indicatorName,
                    new AppliedPrice[] { AppliedPrice.CLOSE }, optionalInputs, 0);
            double value = (Double) outputs[outputIndex];
            return value;
        }
        
        public void removeFromChart(){
            if(chart != null && indicator != null){
                chart.removeIndicator(indicator);
            }
        }
        
        @Override 
        public String toString(){
            return String.format("%s %s on %s feed", indicatorName, Arrays.toString(optionalInputs), feedDescriptor.getPeriod());
        }
        
    }
    
    private List<IndDataAndFeed> calculatableIndicators = new ArrayList<IndDataAndFeed>(Arrays.asList(new IndDataAndFeed[]{
            new IndDataAndFeed("MACD", new Object[] {12,26,9}, 2, new TimePeriodAggregationFeedDescriptor(instrument, Period.FIVE_MINS, side)),
            new IndDataAndFeed("RSI", new Object[] {14}, 0, new TimePeriodAggregationFeedDescriptor(instrument, Period.FIVE_MINS, side)),
            new IndDataAndFeed("RSI", new Object[] {14}, 0, new TimePeriodAggregationFeedDescriptor(instrument, Period.ONE_HOUR, side)),
            new IndDataAndFeed("CCI", new Object[] {14}, 0, new TimePeriodAggregationFeedDescriptor(instrument, Period.FIFTEEN_MINS, side)),
            new IndDataAndFeed("CCI", new Object[] {14}, 0, new TimePeriodAggregationFeedDescriptor(instrument, Period.ONE_HOUR, side)),
            new IndDataAndFeed("CCI", new Object[] {14}, 0, new TimePeriodAggregationFeedDescriptor(instrument, Period.FIVE_MINS, side))
    }));
    

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

        if(!context.getSubscribedInstruments().contains(instrument)){
            context.setSubscribedInstruments(new HashSet<Instrument>(Arrays.asList(new Instrument [] {instrument})), true);
        }
        
        this.context = context;
        console = context.getConsole();
        indicators = context.getIndicators();
        
        for(IndDataAndFeed indDataAndFeed : calculatableIndicators){
            indDataAndFeed.openChartAddIndicator();
        }
    }
    
    @Override
    public void onTick(Instrument instrument, ITick tick) throws JFException {
    }
 
    private void print(Object o) {
        console.getOut().println(o);
    }

    private void print(String format, Object... args) {
        print(String.format(format, args));
    }    
    
        
    private IOrder submitOrder(OrderCommand orderCmd) throws JFException {

        return engine.submitOrder(getLabel(instrument), this.instrument, orderCmd, this.amount, 0, 5);
    }
    

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

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

        
        int i=0;
        
        for (IndDataAndFeed indDataAndFeed : calculatableIndicators) 
            {
            double value = indDataAndFeed.getCurrentValue();
             i=i+1;
     
            if(i==1) {macdd = value;}    
            if(i==2) {rsim = value;}                  
            if(i==3) {rsih = value;}                  
            if(i==4) {cciq = value;  print("cci 15 minutes =%s", cciq);}    
            if(i==5) {ccih = value; print("cci 1 heure =%s", ccih);}        
            if(i==6) {ccic = value;  print("cci 5 minutes =%s", ccic);}    
 
  
                                                             
        if (cciq>100 && ccih>100 && ccic>100 && engine.getOrder("abuy") == null)
            {engine.submitOrder("abuy", instrument, OrderCommand.BUY, 100);
            w=300;}
            
        if (cciq<-100 && ccih<-100 && ccic<-100 && engine.getOrder("asell") == null)
            {engine.submitOrder("asell", instrument, OrderCommand.SELL, 100);
            w=400;}     

         if(engine.getOrder("abuy") != null && ccic<-100)
             {engine.getOrder("abuy").close();
              engine.getOrder("abuy").waitForUpdate(IOrder.State.CLOSED); 
             }
             
         if(engine.getOrder("asell") != null && ccic>100)
             {engine.getOrder("asell").close();
             engine.getOrder("asell").waitForUpdate(IOrder.State.CLOSED); 
             }
                         
             
            }
                
            
     }              

    
    @Override
    public void onStop() throws JFException 
    {
        for(IndDataAndFeed indDataAndFeed : calculatableIndicators)
        {
            indDataAndFeed.removeFromChart();
        }
        //close all orders
        for (IOrder order : engine.getOrders()) 
        {
            engine.getOrder(order.getLabel()).close();
        }
    }

   

    @Override
    public void onMessage(IMessage message) throws JFException {
    }

    @Override
    public void onAccount(IAccount account) throws JFException {
    }



}
