package jforex;

import java.util.*;

import com.dukascopy.api.*;

public class testCloseOrderWithTimer 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();
		
		double ask = history.getLastTick(Instrument.EURUSD).getAsk();
		long openTime = history.getLastTick(Instrument.EURUSD).getTime();
		double pip = Instrument.EURUSD.getPipValue();
		
		IOrder order = engine.submitOrder("THIS_LABEL_HAS_TO_BUT_SHOULD_NOT_HAVE_TO_BE_UNIQUE",Instrument.EURUSD, IEngine.OrderCommand.BUY, 0.1, ask-300*pip,ask+300*pip);
		
		long WaitingTimeBeforeClosing = 30*60000;
		long nowPlusWaitingTimeBeforeClosing = openTime + WaitingTimeBeforeClosing;
		
		ScheduleClosingOrder ScheduleClosingOrder = new ScheduleClosingOrder(order, nowPlusWaitingTimeBeforeClosing);
	}

	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 {
	}
    
	class ScheduleClosingOrder {
		Timer m_timer;
		IOrder m_order;
		
		public ScheduleClosingOrder(IOrder order, long closeTime) {
			m_order = order;
			m_timer = new Timer();
			m_timer.schedule(new TimerAction(order), closeTime);
		}
		
		class TimerAction extends TimerTask {
			IOrder m_order;
			
			public TimerAction(IOrder order) {
				m_order = order;
			}

			public void run() {
				if (m_order.getState() == IOrder.State.FILLED) {
					m_order.close();
					m_timer.cancel();
				}
			}
		}//TimerAction
        
	}//ScheduleClosingOrder
}//testCloseOrderWithTimer