//Require Bar Updates in @StudyHeader.
@StudyHeader(
namespace="com.mycompany",
id="test1",
rb="com.motivewave.platform.study.nls.strings",
name="test1",
label="test1",
desc="test1",
menu="MyStrategies",
overlay = true,
signals = true,
strategy = true,
autoEntry = true,
manualEntry = false,
supportsUnrealizedPL = true,
supportsRealizedPL = true,
supportsTotalPL = true,
supportsRiskRatio = true,
showTradeOptions = true,
supportsBarUpdates = true,
supportsPositionType = true,
supportsTargetPL = true,
underlayByDefault = true,
barUpdatesByDefault = true,
requiresBarUpdates = true)
//Declare global variables
private Order LongEntryOrder = null;
float SLprice = 0f;
//Then, perform all calculations inside calculate.
@Override
protected void calculate(int index, DataContext ctx) {
//For example, assume the price crosses above a moving average. This condition must be evaluated only after the bar is complete,
//even when Bar Updates is enabled in the Strategy Settings.
boolean crossover = crossedAbove(series, index, Values.CLOSE, Value.EMA) && series.isBarComplete(index);
//Calculate your stop-loss level dynamically
double low = series.lowest(index, 3, Enums.BarInput.LOW);
float SLprice = instr.round((float) (low - (tickSize*3))); // Dynamic stop loss: 3 ticks below the lowest low of the last 3 candles.
//Then, trigger the signal
if (crossover){
series.setBoolean(index, Signals.BuySignal, true);
//This will trigger even we don't enable "Signal" in the "Signals" tab
ctx.signal(index, Signals.BuySignal, buyMessage, "Current price: " + round(Close, 2));"
}
}
//Enter a long position
@Override
public void onSignal(OrderContext ctx, Object signal) {
if (signal == Signals.BuySignal){
// submit a market buy or limit buy entry
LongEntryOrder = ctx.createLimitOrder(...);
ctx.submitOrders(LongEntryOrder);
}
}
//After the long entry order is filled, close the position if the dynamic stop-loss level is hit
@Override
public void onOrderFilled(OrderContext ctx, Order order) {
if (order == LongEntryOrder){
if (close < SLprice){
ctx.closeAtMarket() //close the position
}
}
}