/*

	StopManager.java
	version 1.0
	Copyright 2010 Quantisan.com

	Move stops to breakeven when equidistance to original stop loss

*/

package jforex;

import com.dukascopy.api.*;

public class StopManager implements IStrategy {
	private IEngine engine;
	private IConsole console;
	private IContext context;
	
	@Configurable("Lock-in Pips for Breakeven")
	public int lockPip = 3;
	
	@Configurable("Move stop to breakeven?")
	public boolean moveBE = true;
	
	public void onStart(IContext context) throws JFException {
		this.engine = context.getEngine();
		this.console = context.getConsole();
		this.context = context;
	}

	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 {
		for (IOrder order : engine.getOrders(instrument)) {
			if (order.getState() == IOrder.State.FILLED) {
				boolean isLong;
				double open, stop, diff, newStop;
				String label = order.getLabel();
				IChart chart;
				
				isLong = order.isLong();
				open = order.getOpenPrice();
				stop = order.getStopLossPrice(); 
				diff = open - stop;		// stop loss distance
				
				if (isLong) {			// long side order		
					if (moveBE && diff > 0 && tick.getBid() > (open + diff)) {
						// make it breakeven trade + lock in a few pips
						newStop = open + instrument.getPipValue() * lockPip;
						order.setStopLossPrice(newStop);						
                        console.getOut().println(label + ": Moved stop to breakeven");
						
						chart = this.context.getChart(instrument);
						chart.draw(label + "_BE", IChart.Type.SIGNAL_UP, tick.getTime(), newStop);
					}	
				}
				else {					// short side order			
					// Move to breakeven
					if (moveBE && diff < 0 && tick.getAsk() < (open + diff)) {	// diff is negative                        
						// make it breakeven trade + lock in a few pips
                        newStop = open - (instrument.getPipValue() * lockPip);
						order.setStopLossPrice(newStop);
                        console.getOut().println(label + ": Moved stop to breakeven");
						
						chart = this.context.getChart(instrument);
						chart.draw(label + "_BE", IChart.Type.SIGNAL_DOWN, tick.getTime(), newStop);
					}				
				}
            }
        }    
	}
	
    public void onBar(Instrument instrument, Period period, IBar askBar, IBar bidBar) throws JFException {
    }
}