package com.dukascopy.visualforex.visualjforex;

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 2.40
 * Date: 28.09.2017 13:10
 */
public class DocDowIchimoku_Help 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("defaultTakeProfit:")
	public int defaultTakeProfit = 50;
	@Configurable("defaultTradeAmount:")
	public double defaultTradeAmount = 0.001;
	@Configurable("defaultInstrument:")
	public Instrument defaultInstrument = Instrument.EURUSD;
	@Configurable("defaultSlippage:")
	public int defaultSlippage = 5;
	@Configurable("defaultStopLoss:")
	public int defaultStopLoss = 25;
	@Configurable("defaultPeriod:")
	public Period defaultPeriod = Period.THIRTY_MINS;

	private Candle candle37 =  null ;
	private Candle candle36 =  null ;
	private Candle candle39 =  null ;
	private Tick LastTick =  null ;
	private Candle candle38 =  null ;
	private int _tempVar422 = 2;
	private String AccountCurrency = "";
	private double _tempVar152 = 10.0;
	private Period _tempVar151 = Period.THIRTY_MINS;
	private Period _tempVar150 = Period.THIRTY_MINS;
	private Candle candle33 =  null ;
	private double _tempVar355 = -100.0;
	private Candle candle35 =  null ;
	private Candle candle34 =  null ;
	private double Leverage;
	private double _chinkouSpan56;
	private Period _tempVar92 = Period.FIVE_MINS;
	private double _senkouB56;
	private double _tempVar356 = -50.0;
	private int _tempVar433 = 1;
	private int _tempVar439 = 0;
	private int _tempVar362 = 25;
	private int _tempVar364 = 50;
	private int _tempVar165 = 4;
	private Candle LastAskCandle =  null ;
	private double _kijunSen56;
	private int _pos;
	private double _VARatr;
	private int _Shift = 0;
	private Candle LastBidCandle =  null ;
	private double _c150 = 150.0;
	private IOrder _longpos =  null ;
	private String AccountId = "";
	private int _tempVar408 = 48;
	private double _ipos;
	private double Equity;
	private double _tempVar402 = 50.0;
	private double _VARabove150;
	private IOrder _shortpos =  null ;
	private int _tempVar407 = 48;
	private int OverWeekendEndLeverage;
	private int _tempVar294 = 0;
	private Candle _candle4 =  null ;
	private Candle _candle3 =  null ;
	private double _tenkanSen56;
	private Candle _candle2 =  null ;
	private double _Lot = 10.0;
	private Candle _candle1 =  null ;
	private double _cminus150 = -150.0;
	private List<IOrder> PendingPositions =  null ;
	private double _variableabove150;
	private double _senkouA56;
	private List<IOrder> OpenPositions =  null ;
	private double UseofLeverage;
	private IMessage LastTradeEvent =  null ;
	private Candle candle40 =  null ;
	private boolean GlobalAccount;
	private int MarginCutLevel;
	private List<IOrder> AllPositions =  null ;
	private double _VARbelow150;


	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, defaultPeriod, OfferSide.BID, 1);
		IBar askBar = context.getHistory().getBar(defaultInstrument, defaultPeriod, OfferSide.ASK, 1);
		LastAskCandle = new Candle(askBar, defaultPeriod, defaultInstrument, OfferSide.ASK);
		LastBidCandle = new Candle(bidBar, defaultPeriod, defaultInstrument, OfferSide.BID);

		if (indicators.getIndicator("ICHIMOKUVF") == null) {
			indicators.registerDownloadableIndicator("7842","ICHIMOKUVF");
		}
		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();
			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);

			If_block_72(0);

	}

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

	}

    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 ICHIMOKUVF_block_56(Integer flow) {
		Instrument argument_1 = defaultInstrument;
		Period argument_2 = Period.FIFTEEN_MINS;
		int argument_3 = 0;
		int argument_4 = 9;
		int argument_5 = _tempVar422;
		int argument_6 = 52;
		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[3];
		params[0] = 9;
		params[1] = _tempVar422;
		params[2] = 52;
		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,
					"ICHIMOKUVF", appliedPrice, params, Filter.WEEKENDS, 1, time, 0);
			if ((new Double(((double [])indicatorResult[0])[0])) == null) {
				this._tenkanSen56 = Double.NaN;
			} else { 
				this._tenkanSen56 = (((double [])indicatorResult[0])[0]);
			} 
			if ((new Double(((double [])indicatorResult[1])[0])) == null) {
				this._kijunSen56 = Double.NaN;
			} else { 
				this._kijunSen56 = (((double [])indicatorResult[1])[0]);
			} 
			if ((new Double(((double [])indicatorResult[2])[0])) == null) {
				this._chinkouSpan56 = Double.NaN;
			} else { 
				this._chinkouSpan56 = (((double [])indicatorResult[2])[0]);
			} 
			if ((new Double(((double [])indicatorResult[3])[0])) == null) {
				this._senkouA56 = Double.NaN;
			} else { 
				this._senkouA56 = (((double [])indicatorResult[3])[0]);
			} 
			if ((new Double(((double [])indicatorResult[4])[0])) == null) {
				this._senkouB56 = Double.NaN;
			} else { 
				this._senkouB56 = (((double [])indicatorResult[4])[0]);
			} 
		If_block_73(flow);
		} catch (JFException e) {
			e.printStackTrace();
			console.getErr().println(e);
			this._tenkanSen56 = Double.NaN;
			this._kijunSen56 = Double.NaN;
			this._chinkouSpan56 = Double.NaN;
			this._senkouA56 = Double.NaN;
			this._senkouB56 = Double.NaN;
		}
	}

	private  void If_block_64(Integer flow) {
		int argument_1 = OpenPositions.size();
		int argument_2 = 1;
		if (argument_1< argument_2) {
		}
		else if (argument_1> argument_2) {
		}
		else if (argument_1== argument_2) {
			If_block_81(flow);
		}
	}

	private  void If_block_72(Integer flow) {
		Instrument argument_1 = LastTick.getInstrument();
		Instrument argument_2 = defaultInstrument;
		if (argument_1 == null && argument_2 !=null || (argument_1!= null && !argument_1.equals(argument_2))) {
		}
		else if (argument_1!= null && argument_1.equals(argument_2)) {
			ICHIMOKUVF_block_56(flow);
		}
	}

	private  void If_block_73(Integer flow) {
		int argument_1 = AllPositions.size();
		double argument_2 = 1.0;
		if (argument_1< argument_2) {
			MultipleAction_block_74(flow);
		}
		else if (argument_1> argument_2) {
		}
		else if (argument_1== argument_2) {
			If_block_64(flow);
		}
	}

	private  void MultipleAction_block_74(Integer flow) {
		If_block_75(flow);
	}

	private  void If_block_75(Integer flow) {
		double argument_1 = _kijunSen56;
		double argument_2 = _tenkanSen56;
		if (argument_1< argument_2) {
			If_block_76(flow);
		}
		else if (argument_1> argument_2) {
		}
		else if (argument_1== argument_2) {
		}
	}

	private  void If_block_76(Integer flow) {
		double argument_1 = _senkouA56;
		double argument_2 = _senkouB56;
		if (argument_1< argument_2) {
			OpenatMarket_block_77(flow);
		}
		else if (argument_1> argument_2) {
		}
		else if (argument_1== argument_2) {
		}
	}

	private  void OpenatMarket_block_77(Integer flow) {
		Instrument argument_1 = defaultInstrument;
		double argument_2 = 3.0;
		int argument_3 = defaultSlippage;
		int argument_4 = 0;
		int argument_5 = 0;
		String argument_6 = "";
		ITick tick = getLastTick(argument_1);

		IEngine.OrderCommand command = IEngine.OrderCommand.SELL;

		double stopLoss = round(argument_4, argument_1);
		double takeProfit = round(argument_5, argument_1);
		
           try {
               String label = getLabel();           
               _shortpos = context.getEngine().submitOrder(label, argument_1, command, argument_2, 0, argument_3,  stopLoss, takeProfit, 0, argument_6);
				Assign_block_78(flow);
        } catch (JFException e) {
            e.printStackTrace();
        }
	}

	private  void Assign_block_78(Integer flow) {
		int argument_1 = -1;
		_pos =  argument_1;
		}

	private  void If_block_79(Integer flow) {
		double argument_1 = _kijunSen56;
		double argument_2 = _tenkanSen56;
		if (argument_1< argument_2) {
		}
		else if (argument_1> argument_2) {
			CloseandCancelPosition_block_80(flow);
		}
		else if (argument_1== argument_2) {
		}
	}

	private  void CloseandCancelPosition_block_80(Integer flow) {
		try {
			if (_shortpos != null && (_shortpos.getState() == IOrder.State.OPENED||_shortpos.getState() == IOrder.State.FILLED)){
				_shortpos.close();
			}
		} catch (JFException e)  {
			e.printStackTrace();
		}
	}

	private  void If_block_81(Integer flow) {
		int argument_1 = _pos;
		int argument_2 = 0;
		if (argument_1< argument_2) {
			If_block_79(flow);
		}
		else if (argument_1> argument_2) {
		}
		else if (argument_1== argument_2) {
		}
	}

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;
    }
}

    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;
        }
    }
}