package jforex;

import java.util.*;
import java.text.SimpleDateFormat;
import com.dukascopy.api.IIndicators.AppliedPrice;
import com.dukascopy.api.*;

public class TrixTestStrategy implements IStrategy {
    private IEngine engine;
    private IConsole console;
    private IHistory history;
    private IContext context;
    private IIndicators indicators;
    private IUserInterface userInterface;
    
    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();
        Set<Instrument> instruments = new HashSet<Instrument>();
        instruments.add(Instrument.EURUSD);
        context.setSubscribedInstruments(instruments, true);

    }

    public void onAccount(IAccount account) throws JFException {
    }

    public void onMessage(IMessage message) throws JFException {
    }

    public void onStop() throws JFException {
    }

    public void onTick(Instrument instrument, ITick tick) throws JFException {
    }
    
    public void onBar(Instrument instrument, Period period, IBar askBar, IBar bidBar) throws JFException {
        if (instrument != Instrument.EURUSD) return;
        if (period != Period.FIFTEEN_MINS) return;
        try{
            // index: 0 last bar
            //        1 currentBar
            double trix[] = indicators.trix(instrument, period, OfferSide.BID,AppliedPrice.CLOSE, 12, Filter.ALL_FLATS, 2, bidBar.getTime(), 0);
            if (trix.length < 1){
                console.getErr().println("Could not calculate TRIX for "+instrument.toString()+", candle period = "+period.toString()+
                        ",  period = "+12+
                        ",  time = "+getGMTString(bidBar.getTime()));
                
            }
            console.getOut().println("trix = "+trix[trix.length-1]+" at "+getGMTString(bidBar.getTime()));
        }
        catch (Exception e){
           
            e.printStackTrace(console.getErr());
            console.getErr().println("period = "+period.toString());
        }
    }
    
      public static String getGMTString(long milis){
          Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
          cal.setTimeInMillis(milis);
          return getGMTString(cal.getTime());
      }
     
      public static String getGMTString(Calendar cal){
          if (cal == null) return "null";
          return getGMTString(cal.getTime());
      }
      public static String getGMTString(Date date){      
          //     Festlegung des Formats:
          SimpleDateFormat df = new SimpleDateFormat( "dd-MM-yyyy HH:mm:ss.SSS z" );
          df.setTimeZone(TimeZone.getTimeZone("GMT"));            
          return df.format(date);      
      }
      
}