package jforex;
import com.dukascopy.api.*;
import com.dukascopy.api.IEngine.OrderCommand;
import com.dukascopy.api.IMessage.Type;
public class SimpleTpSlStrategy implements IStrategy {
@Configurable("通貨ペア")
public Instrument instrument = Instrument.EURUSD;
@Configurable("ロット")
public double amount = 0.001;
@Configurable("ストップロス")
public int slPips = 10;
@Configurable("リミット(ストップロスクローズ時)")
public int tpPipsOnLoss = 10;
@Configurable("リミット(リミットクローズ時)")
public int tpPipsOnProfit = 5;
private IEngine engine;
private IHistory history;
private IConsole console;
private IContext context;
private IOrder order;
public void onStart(IContext context) throws JFException {
this.engine = context.getEngine();
this.history = context.getHistory();
this.console = context.getConsole();
this.context = context;
context.setSubscribedInstruments(java.util.Collections.singleton(instrument));
IBar prevDailyBar = history.getBar(instrument, Period.DAILY, OfferSide.ASK, 1);
OrderCommand orderCmd = prevDailyBar.getClose() > prevDailyBar.getOpen()
? OrderCommand.BUY
: OrderCommand.SELL;
submitOrder(amount, orderCmd, tpPipsOnLoss);
}
public void onAccount(IAccount account) throws JFException {
}
public void onMessage(IMessage message) throws JFException {
if (message.getType() != Type.ORDER_CLOSE_OK
|| !message.getOrder().equals(order)
) {
return;
}
console.getInfo().format("%s リミット/ストップによるクローズ %.1f pips", order.getLabel(), order.getProfitLossInPips()).println();
if (message.getReasons().contains(IMessage.Reason.ORDER_CLOSED_BY_TP)) {
submitOrder(amount, order.getOrderCommand(), tpPipsOnProfit);
} else if (message.getReasons().contains(IMessage.Reason.ORDER_CLOSED_BY_SL)) {
OrderCommand orderCmd = order.isLong() ? OrderCommand.SELL : OrderCommand.BUY;
submitOrder(amount, orderCmd, tpPipsOnLoss);
} else {
console.getOut().println("ストラテジー以外の方法でクローズされました。ストラテジーを停止します。");
context.stop();
}
}
private void submitOrder(double amount, OrderCommand orderCmd, double tpPips) throws JFException {
double slPrice, tpPrice;
ITick lastTick = history.getLastTick(instrument);
if (orderCmd == OrderCommand.BUY) {
slPrice = lastTick.getAsk() - slPips * instrument.getPipValue();
tpPrice = lastTick.getAsk() + tpPips * instrument.getPipValue();
} else {
slPrice = lastTick.getBid() + slPips * instrument.getPipValue();
tpPrice = lastTick.getBid() - tpPips * instrument.getPipValue();
}
order = engine.submitOrder( orderCmd.toString() + System.currentTimeMillis(), instrument, orderCmd, amount,
0, 20, slPrice, tpPrice);
}
public void onStop() throws JFException {
if(order.getState() == IOrder.State.FILLED || order.getState() == IOrder.State.OPENED){
order.close();
}
}
public void onTick(Instrument instrument, ITick tick) throws JFException {}
public void onBar(Instrument instrument, Period period, IBar askBar, IBar bidBar) throws JFException {}
}