/*
 * Copyright (c) 2006-2009 OrangeSignal.com All rights reserved.
 */

package jp.sourceforge.orangesignal.trading.strategy.stop;

import static jp.sourceforge.orangesignal.trading.PositionType.LONG;
import static jp.sourceforge.orangesignal.trading.PositionType.SHORT;
import static jp.sourceforge.orangesignal.trading.order.OrderTiming.NEXT_STOP;

import java.util.List;

import jp.sourceforge.orangesignal.ta.PercentageScale;
import jp.sourceforge.orangesignal.trading.Position;
import jp.sourceforge.orangesignal.trading.strategy.StrategyStatus;
import jp.sourceforge.orangesignal.trading.strategy.StrategySupport;

/**
 * 一定以上の損失が出たところで、逆指値注文を出すストラテジーを提供します。
 *
 * @author 杉澤 浩二
 */
public class StopLoss extends StrategySupport {

	private double loss;

	public double getLoss() { return loss; }

	public void setLoss(final double loss) { this.loss = loss; }

	private PercentageScale scale;

	public PercentageScale getScale() { return scale; }

	public void setScale(final PercentageScale scale) { this.scale = scale; }

	@Override
	public StrategyStatus process() {
		final List<Position> positions = getCurrentPositions();
		for (final Position p : positions) {
			final double loss = (this.scale == null) ? this.loss : Math.ceil(p.getEntryPrice() * (this.loss / this.scale.scale()));
			if (p.getType() == LONG)
				sell(getStrategyName(), NEXT_STOP, p.getEntryPrice() - loss, p.getEntryLabel());
			else if (p.getType() == SHORT)
				buyToCover(getStrategyName(), NEXT_STOP, p.getEntryPrice() + loss, p.getEntryLabel());
		}
		return StrategyStatus.NEXT;
	}

}
