package com.dukascopy.visualforex.Ken73;

import java.util.*;
import com.dukascopy.api.*;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.concurrent.CopyOnWriteArrayList;
import java.lang.reflect.*;
import java.math.BigDecimal;


/*
 * Created by VisualJForex Generator, version 1.30
 * Date: 27.10.2013 17:18
 */

  @RequiresFullAccess 
public class Stoch4hStoch1h implements IStrategy {

    private CopyOnWriteArrayList<TradeEventAction> tradeEventActions = new CopyOnWriteArrayList<TradeEventAction>();
    private static final String DATE_FORMAT_NOW = "yyyyMMdd_HHmmss";
    private IEngine engine;
    private IConsole console;
    private IHistory history;
    private IContext context;
    private IIndicators indicators;
    private IUserInterface userInterface;

    @Configurable("defaultSlippage:")
    public int defaultSlippage = 5;
    @Configurable("defaultTakeProfit:")
    public int defaultTakeProfit = 50;
    @Configurable("defaultPeriod:")
    public Period defaultPeriod = Period.TEN_MINS;
    @Configurable("defaultTradeAmount:")
    public double defaultTradeAmount = 0.0010;
    @Configurable("defaultStopLoss:")
    public int defaultStopLoss = 30;
    @Configurable("defaultInstrument:")
    public Instrument defaultInstrument = Instrument.EURUSD;
    List<ISignal> listSignals25 = new ArrayList<ISignal>();
    IDownloadableStrategy strategy25 = null;
    enum Sound {COIN, OHYEAH, BEAR, BULL, CASH, RING};
    List<ISignal> listSignals39 = new ArrayList<ISignal>();
    IDownloadableStrategy strategy39 = null;

    private double SlowkVerde1h;
    private String AccountCurrency = "";
    private Candle candle31 =  null ;
    private double Leverage;
    private double SlowdRossa1h;
    private Candle Last1hcandle =  null ;
    private Tick LastTick =  null ;
    private String AccountId = "";
    private double Equity;
    private double UseofLeverage;
    private double SlowkVerde4h;
    private List<IOrder> PendingPositions =  null ;
    private List<IOrder> AllPositions =  null ;
    private double SlowdRossa4h;
    private int OverWeekendEndLeverage;
    private int MarginCutLevel;
    private Candle LastAskCandle =  null ;
    private double SlowkVerdeDaily;
    private boolean GlobalAccount;
    private double SlowdRossaDaily;
    private List<IOrder> OpenPositions =  null ;
    private double Ema9Verde4h;
    private IMessage LastTradeEvent =  null ;
    private Candle LastBidCandle =  null ;


    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();

        subscriptionInstrumentCheck(defaultInstrument);

        ITick lastITick = context.getHistory().getLastTick(defaultInstrument);
        LastTick = new Tick(lastITick, defaultInstrument);

        IBar bidBar = context.getHistory().getBar(defaultInstrument, Period.ONE_MIN, OfferSide.BID, 1);
        IBar askBar = context.getHistory().getBar(defaultInstrument, Period.ONE_MIN, OfferSide.ASK, 1);
        LastAskCandle = new Candle(askBar, Period.ONE_MIN, defaultInstrument, OfferSide.ASK);
        LastBidCandle = new Candle(bidBar, Period.ONE_MIN, defaultInstrument, OfferSide.BID);

        if (indicators.getIndicator("STOCH") == null) {
            indicators.registerDownloadableIndicator("1279","STOCH");
        }
        HashMap<String, Object> map25 = new HashMap<String, Object>();
        map25.put("Sound Signal", Sound.COIN);
        map25.put("Beep on Testing", true);
        strategy25 = context.getDownloadableStrategies().init("1252","Sound Alert", context, IDownloadableStrategy.ComponentType.BLOCK_STRATEGY, IEngine.StrategyMode.SIGNALS, map25);
        if (indicators.getIndicator("STOCH") == null) {
            indicators.registerDownloadableIndicator("1279","STOCH");
        }
        HashMap<String, Object> map39 = new HashMap<String, Object>();
        map39.put("Sound Signal", Sound.COIN);
        map39.put("Beep on Testing", true);
        strategy39 = context.getDownloadableStrategies().init("1252","Sound Alert", context, IDownloadableStrategy.ComponentType.BLOCK_STRATEGY, IEngine.StrategyMode.SIGNALS, map39);
        subscriptionInstrumentCheck(Instrument.fromString("EUR/USD"));

    }

    public void onAccount(IAccount account) throws JFException {
        AccountCurrency = account.getCurrency().toString();
        Leverage = account.getLeverage();
        AccountId= account.getAccountId();
        Equity = account.getEquity();
        UseofLeverage = account.getUseOfLeverage();
        OverWeekendEndLeverage = account.getOverWeekEndLeverage();
        MarginCutLevel = account.getMarginCutLevel();
        GlobalAccount = account.isGlobal();
    }

    private void updateVariables(Instrument instrument) {
        try {
            AllPositions = engine.getOrders(instrument);
            List<IOrder> listMarket = new ArrayList<IOrder>();
            for (IOrder order: AllPositions) {
                if (order.getState().equals(IOrder.State.FILLED)){
                    listMarket.add(order);
                }
            }
            List<IOrder> listPending = new ArrayList<IOrder>();
            for (IOrder order: AllPositions) {
                if (order.getState().equals(IOrder.State.OPENED)){
                    listPending.add(order);
                }
            }
            OpenPositions = listMarket;
            PendingPositions = listPending;
        } catch(JFException e) {
            e.printStackTrace();
        }
    }

    public void onMessage(IMessage message) throws JFException {
        if (message.getOrder() != null) {
            updateVariables(message.getOrder().getInstrument());
            LastTradeEvent = message;
            for (TradeEventAction event :  tradeEventActions) {
                IOrder order = message.getOrder();
                if (order != null && event != null && message.getType().equals(event.getMessageType())&& order.getLabel().equals(event.getPositionLabel())) {
                    Method method;
                    try {
                        method = this.getClass().getDeclaredMethod(event.getNextBlockId(), Integer.class);
                        method.invoke(this, new Integer[] {event.getFlowId()});
                    } catch (SecurityException e) {
                            e.printStackTrace();
                    } catch (NoSuchMethodException e) {
                          e.printStackTrace();
                    } catch (IllegalArgumentException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    } 
                    tradeEventActions.remove(event); 
                }
            }   
        }
    }

    public void onStop() throws JFException {
    }

    public void onTick(Instrument instrument, ITick tick) throws JFException {
            LastTick = new Tick(tick, instrument);
        updateVariables(instrument);


    }

    public void onBar(Instrument instrument, Period period, IBar askBar, IBar bidBar) throws JFException {
        LastAskCandle = new Candle(askBar, period, instrument, OfferSide.ASK);
        LastBidCandle = new Candle(bidBar, period, instrument, OfferSide.BID);
        updateVariables(instrument);
            If_block_16(1);

    }

    public void subscriptionInstrumentCheck(Instrument instrument) {
        try {
              if (!context.getSubscribedInstruments().contains(instrument)) {
                  Set<Instrument> instruments = new HashSet<Instrument>();
                  instruments.add(instrument);
                  context.setSubscribedInstruments(instruments, true);
                  Thread.sleep(100);
              }
          } catch (InterruptedException e) {
              e.printStackTrace();
          }
        }

    public double round(double price, Instrument instrument) {
        BigDecimal big = new BigDecimal("" + price); 
        big = big.setScale(instrument.getPipScale() + 1, BigDecimal.ROUND_HALF_UP); 
        return big.doubleValue(); 
    }

    public ITick getLastTick(Instrument instrument) {
        try { 
            return (context.getHistory().getTick(instrument, 0)); 
        } catch (JFException e) { 
             e.printStackTrace();  
         } 
         return null; 
    }

    private void STOCH_block_10(Integer flow) {
        Instrument argument_1 = defaultInstrument;
        Period argument_2 = Period.FOUR_HOURS;
        int argument_3 = 0;
        int argument_4 = 10;
        int argument_5 = 6;
        IIndicators.MaType argument_6 = IIndicators.MaType.EMA;
        int argument_7 = 3;
        IIndicators.MaType argument_8 = IIndicators.MaType.EMA;
        OfferSide[] offerside = new OfferSide[1];
        IIndicators.AppliedPrice[] appliedPrice = new IIndicators.AppliedPrice[1];
        offerside[0] = OfferSide.BID;
        appliedPrice[0] = IIndicators.AppliedPrice.CLOSE;
        Object[] params = new Object[5];
        params[0] = 10;
        params[1] = 6;
        params[2] = 1;
        params[3] = 3;
        params[4] = 1;
        try {
            subscriptionInstrumentCheck(argument_1);
            long time = context.getHistory().getBar(argument_1, argument_2, OfferSide.BID, argument_3).getTime();
            Object[] indicatorResult = context.getIndicators().calculateIndicator(argument_1, argument_2, offerside,
                    "STOCH", appliedPrice, params, Filter.WEEKENDS, argument_3 + 1, time, 0);
            if ((new Double(((double [])indicatorResult[0])[0])) == null) {
                this.SlowkVerde4h = Double.NaN;
            } else { 
                this.SlowkVerde4h = (((double [])indicatorResult[0])[0]);
            } 
            if ((new Double(((double [])indicatorResult[1])[0])) == null) {
                this.SlowdRossa4h = Double.NaN;
            } else { 
                this.SlowdRossa4h = (((double [])indicatorResult[1])[0]);
            } 
        } catch (JFException e) {
            e.printStackTrace();
        }
        STOCH_block_35(flow);
    }

    private  void If_block_16(Integer flow) {
        Period argument_1 = LastBidCandle.getPeriod();
        Period argument_2 = Period.ONE_HOUR;
        if (!argument_1.equals(argument_2)) {
        }
        else if (argument_1.equals(argument_2)) {
            If_block_29(flow);
        }
    }

    private  void SoundAlert_block_25(Integer flow) {
        try {
            List<ISignal> signals25 = null;
            switch (flow) {
                case 0:
                    signals25 = strategy25.onTick(LastTick.getInstrument(), LastTick.getTick());
                    break;
                case 1:
                    signals25 = strategy25.onBar(LastAskCandle.getInstrument(), LastAskCandle.getPeriod(), LastAskCandle.getBar(), LastBidCandle.getBar());
                    break;
                case 2:
                    signals25 = strategy25.onMessage(LastTradeEvent);
                    break;
                default:
                    signals25 = strategy25.onTick(LastTick.getInstrument(), LastTick.getTick());
                    break;
            }
        } catch (JFException e) {
            e.printStackTrace();
        }
    }

    private  void If_block_29(Integer flow) {
        Instrument argument_1 = defaultInstrument;
        Instrument argument_2 = LastBidCandle.getInstrument();
        if (!argument_1.equals(argument_2)) {
        }
        else if (argument_1.equals(argument_2)) {
            STOCH_block_10(flow);
        }
    }

    private  void If_block_34(Integer flow) {
        double argument_1 = SlowkVerde4h;
        int argument_2 = 70;
        if (argument_1< argument_2) {
            If_block_37(flow);
        }
        else if (argument_1> argument_2) {
            If_block_36(flow);
        }
        else if (argument_1== argument_2) {
        }
    }

    private void STOCH_block_35(Integer flow) {
        Instrument argument_1 = defaultInstrument;
        Period argument_2 = Period.ONE_HOUR;
        int argument_3 = 0;
        int argument_4 = 10;
        int argument_5 = 6;
        IIndicators.MaType argument_6 = IIndicators.MaType.EMA;
        int argument_7 = 3;
        IIndicators.MaType argument_8 = IIndicators.MaType.EMA;
        OfferSide[] offerside = new OfferSide[1];
        IIndicators.AppliedPrice[] appliedPrice = new IIndicators.AppliedPrice[1];
        offerside[0] = OfferSide.BID;
        appliedPrice[0] = IIndicators.AppliedPrice.CLOSE;
        Object[] params = new Object[5];
        params[0] = 10;
        params[1] = 6;
        params[2] = 1;
        params[3] = 3;
        params[4] = 1;
        try {
            subscriptionInstrumentCheck(argument_1);
            long time = context.getHistory().getBar(argument_1, argument_2, OfferSide.BID, argument_3).getTime();
            Object[] indicatorResult = context.getIndicators().calculateIndicator(argument_1, argument_2, offerside,
                    "STOCH", appliedPrice, params, Filter.WEEKENDS, argument_3 + 1, time, 0);
            if ((new Double(((double [])indicatorResult[0])[0])) == null) {
                this.SlowkVerde1h = Double.NaN;
            } else { 
                this.SlowkVerde1h = (((double [])indicatorResult[0])[0]);
            } 
            if ((new Double(((double [])indicatorResult[1])[0])) == null) {
                this.SlowdRossa1h = Double.NaN;
            } else { 
                this.SlowdRossa1h = (((double [])indicatorResult[1])[0]);
            } 
        } catch (JFException e) {
            e.printStackTrace();
        }
        If_block_34(flow);
    }

    private  void If_block_36(Integer flow) {
        double argument_1 = SlowkVerde1h;
        int argument_2 = 70;
        if (argument_1< argument_2) {
        }
        else if (argument_1> argument_2) {
            SoundAlert_block_25(flow);
        }
        else if (argument_1== argument_2) {
        }
    }

    private  void If_block_37(Integer flow) {
        double argument_1 = SlowkVerde4h;
        int argument_2 = 30;
        if (argument_1< argument_2) {
            If_block_38(flow);
        }
        else if (argument_1> argument_2) {
        }
        else if (argument_1== argument_2) {
        }
    }

    private  void If_block_38(Integer flow) {
        double argument_1 = SlowkVerde1h;
        int argument_2 = 30;
        if (argument_1< argument_2) {
            SoundAlert_block_39(flow);
        }
        else if (argument_1> argument_2) {
        }
        else if (argument_1== argument_2) {
        }
    }

    private  void SoundAlert_block_39(Integer flow) {
        try {
            List<ISignal> signals39 = null;
            switch (flow) {
                case 0:
                    signals39 = strategy39.onTick(LastTick.getInstrument(), LastTick.getTick());
                    break;
                case 1:
                    signals39 = strategy39.onBar(LastAskCandle.getInstrument(), LastAskCandle.getPeriod(), LastAskCandle.getBar(), LastBidCandle.getBar());
                    break;
                case 2:
                    signals39 = strategy39.onMessage(LastTradeEvent);
                    break;
                default:
                    signals39 = strategy39.onTick(LastTick.getInstrument(), LastTick.getTick());
                    break;
            }
        } catch (JFException e) {
            e.printStackTrace();
        }
    }

class Candle  {

    IBar bar;
    Period period;
    Instrument instrument;
    OfferSide offerSide;

    public Candle(IBar bar, Period period, Instrument instrument, OfferSide offerSide) {
        this.bar = bar;
        this.period = period;
        this.instrument = instrument;
        this.offerSide = offerSide;
    }

    public Period getPeriod() {
        return period;
    }

    public void setPeriod(Period period) {
        this.period = period;
    }

    public Instrument getInstrument() {
        return instrument;
    }

    public void setInstrument(Instrument instrument) {
        this.instrument = instrument;
    }

    public OfferSide getOfferSide() {
        return offerSide;
    }

    public void setOfferSide(OfferSide offerSide) {
        this.offerSide = offerSide;
    }

    public IBar getBar() {
        return bar;
    }

    public void setBar(IBar bar) {
        this.bar = bar;
    }

    public long getTime() {
        return bar.getTime();
    }

    public double getOpen() {
        return bar.getOpen();
    }

    public double getClose() {
        return bar.getClose();
    }

    public double getLow() {
        return bar.getLow();
    }

    public double getHigh() {
        return bar.getHigh();
    }

    public double getVolume() {
        return bar.getVolume();
    }
}
class Tick {

    private ITick tick;
    private Instrument instrument;

    public Tick(ITick tick, Instrument instrument){
        this.instrument = instrument;
        this.tick = tick;
    }

    public Instrument getInstrument(){
       return  instrument;
    }

    public double getAsk(){
       return  tick.getAsk();
    }

    public double getBid(){
       return  tick.getBid();
    }

    public double getAskVolume(){
       return  tick.getAskVolume();
    }

    public double getBidVolume(){
        return tick.getBidVolume();
    }

   public long getTime(){
       return  tick.getTime();
    }

   public ITick getTick(){
       return  tick;
    }
}

public class AssertException extends RuntimeException {

    public AssertException(Object primary, Object compared) {
        super("Primary object : " + primary.toString() + " is different from " + compared.toString());
    }
}
    protected String getLabel() {
        String label;
        label = "IVF" + getCurrentTime(LastTick.getTime()) + generateRandom(10000) + generateRandom(10000);
        return label;
    }

    private String getCurrentTime(long time) {
        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
        return sdf.format(time);
    }

    private static String generateRandom(int n) {
        int randomNumber = (int) (Math.random() * n);
        String answer = "" + randomNumber;
        if (answer.length() > 3) {
            answer = answer.substring(0, 4);
        }
        return answer;
    }

    class TradeEventAction {
        private IMessage.Type messageType;
        private String nextBlockId = "";
        private String positionLabel = "";
        private int flowId = 0;

        public IMessage.Type getMessageType() {
            return messageType;
        }

        public void setMessageType(IMessage.Type messageType) {
            this.messageType = messageType;
        }

        public String getNextBlockId() {
            return nextBlockId;
        }

        public void setNextBlockId(String nextBlockId) {
            this.nextBlockId = nextBlockId;
        }
        public String getPositionLabel() {
            return positionLabel;
       }

        public void setPositionLabel(String positionLabel) {
            this.positionLabel = positionLabel;
        }
        public int getFlowId() {
            return flowId;
        }
        public void setFlowId(int flowId) {
            this.flowId = flowId;
        }
    }
}