Quote:
I wonder why such important thing is not implemented into JForex platform?
When trading manually default stop loss can be enabled in settings: Tools > Preferences > General > "Apply defoult stop loss to all market orders".
Here is modified strategy.
It updates stop loss only once and automatically sets stop loss to orders that do not have stop loss.
package jforex.strategies;
import com.dukascopy.api.*;
public class StopManager implements IStrategy {
private IEngine engine;
private IConsole console;
private IContext context;
@Configurable("Lock-in Pips for Breakeven (SLBE)")
public int lockPip = 1;
@Configurable("Stoploss Break Even Trigger (SLBET)")
public int triggerPips = 3;
@Configurable("Auto stop loss pips")
public int autoStopLossPips = 10;
@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, newStop, stopLoss;
String label = order.getLabel();
IChart chart;
isLong = order.isLong();
open = order.getOpenPrice();
stopLoss = order.getStopLossPrice();
// auto set stop loss
if( stopLoss == 0.0 ){
if(isLong) {
order.setStopLossPrice(open - toPrice(instrument, autoStopLossPips) );
} else {
order.setStopLossPrice(open + toPrice(instrument, autoStopLossPips) );
}
}
if (isLong) { // long side order
if(open < stopLoss){
return;
}
if (moveBE && tick.getBid() > (open + toPrice(instrument, triggerPips))) {
// make it breakeven trade + lock in a few pips
newStop = open + toPrice(instrument, 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
if(open > stopLoss){
return;
}
// Move to breakeven
if (moveBE && tick.getAsk() < (open - toPrice(instrument, triggerPips))) { // diff is negative
// make it breakeven trade + lock in a few pips
newStop = open - toPrice(instrument, 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);
}
}
}
}
}
private double toPrice(Instrument instr, int pips) {
return instr.getPipValue() * pips;
}
public void onBar(Instrument instrument, Period period, IBar askBar, IBar bidBar) throws JFException {
}
}