package jforex;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

import com.dukascopy.api.*;
import com.dukascopy.api.IEngine.OrderCommand;
import com.dukascopy.api.IIndicators.AppliedPrice;
import com.dukascopy.api.IOrder.State;
import com.dukascopy.api.indicators.IIndicator;

public class Strategy implements IStrategy {
	private IEngine engine;
	private IHistory history;
	private IIndicators indicators;
	private int counter = 0;
	private IConsole console;

	@Configurable("Instrument")
	public Instrument instrument = Instrument.EURUSD;
	@Configurable("Amount")
	public double amount = 0.02;
	@Configurable("Delta pips")
	public int deltaPips = 0;
	
	private IOrder order;
	
	public void onStart(IContext context) throws JFException {
		this.engine = context.getEngine();
		this.history = context.getHistory();
		this.indicators = context.getIndicators();
		this.console = context.getConsole();
		
		// place the order at ask price + delta
		double price = history.getLastTick(instrument).getAsk() + deltaPips * instrument.getPipValue();		
		order = engine.submitOrder( "order", this.instrument, OrderCommand.BUYSTOP, amount, price, 0);
	}

	public void onAccount(IAccount account) throws JFException {
	}

	public void onMessage(IMessage message) throws JFException {
	}

	public void onStop() throws JFException {
		// close all orders
		for (IOrder order : engine.getOrders()) {
			engine.getOrder(order.getLabel()).close();
		}
	}

	public void onTick(Instrument instrument, ITick tick) throws JFException {
		if (!instrument.equals(this.instrument))
			return;
		
		// lower the order price when ask price drops
		double newPrice = tick.getAsk() + deltaPips * instrument.getPipValue();	
		if(order.getState().equals(State.OPENED) && order.getOpenPrice() > newPrice){
			order.setOpenPrice(newPrice);
		}
	}

	public void onBar(Instrument instrument, Period period, IBar askBar,
			IBar bidBar) throws JFException {
	}
}