package jforex.strategies;
import com.dukascopy.api.*;
import com.dukascopy.api.IEngine.OrderCommand;
public class ManageSL implements IStrategy {
@Configurable("通貨ペア")
public Instrument instrument = Instrument.EURUSD;
@Configurable("時間軸")
public Period period = Period.TEN_SECS;
@Configurable("オーダーコマンド")
public OrderCommand cmd = OrderCommand.BUY;
@Configurable("ストップロス(pips)")
public int StopLossInPips = 5;
private IConsole console;
private IHistory history;
private IEngine engine;
private IOrder order;
@Override
public void onStart(IContext context) throws JFException {
console = context.getConsole();
history = context.getHistory();
engine = context.getEngine();
context.setSubscribedInstruments(java.util.Collections.singleton(instrument), true);
double lastBidPrice = history.getLastTick(instrument).getBid();
double amount = 0.001;
int slippage = 5;
double stopLossPrice = getSLPrice(lastBidPrice);
double takeProfitPrice = 0;
order = engine.submitOrder("order1", instrument, cmd, amount, lastBidPrice, slippage, stopLossPrice, takeProfitPrice);
}
private double getSLPrice (double price){
return cmd.isLong()
? price - instrument.getPipValue() * StopLossInPips
: price + instrument.getPipValue() * StopLossInPips;
}
private void print(Object o){
console.getOut().println(o);
}
@Override
public void onTick(Instrument instrument, ITick tick) throws JFException {}
@Override
public void onBar(Instrument instrument, Period period, IBar askBar, IBar bidBar) throws JFException {
if(instrument != this.instrument || period != this.period){
return;
}
if(order.getState() == IOrder.State.FILLED || order.getState() == IOrder.State.OPENED){
if (doubleEquals(order.getStopLossPrice(),0)){
order.setStopLossPrice(getSLPrice(order.getOpenPrice()));
return;
}
if (Math.abs(order.getOpenPrice() - order.getStopLossPrice()) > StopLossInPips * instrument.getPipValue() * 2){
order.setStopLossPrice(0);
return;
}
if (order.isLong()){
order.setStopLossPrice(order.getStopLossPrice() - instrument.getPipValue());
} else {
order.setStopLossPrice(order.getStopLossPrice() + instrument.getPipValue());
}
}
}
private boolean doubleEquals(double d1, double d2){
return Math.abs(d1-d2) < instrument.getPipValue() / 10;
}
@Override
public void onMessage(IMessage message) throws JFException {
if(message.getOrder() != null && message.getOrder() == order)
print(message);
}
@Override
public void onAccount(IAccount account) throws JFException {}
@Override
public void onStop() throws JFException {
for(IOrder o : engine.getOrders()){
o.close();
}
}
}