// The condition of opening a long position is triggered and the current short position is held, or the condition of opening a long position is triggered and no position is held
if (up && (state == SHORT || state == IDLE)) {
// If you have a short position, close it first
if (state == SHORT && cover(exchange.Buy, "closesell")) {
// Mark open positions after closing them
state = IDLE
// The price of reset position is 0
holdPrice = 0
// Mark on the chart
$.PlotFlag(r[l - 1].Time, 'coverShort', 'CS')
}
// Open a long position after closing the position
exchange.SetDirection("buy")
if (exchange.Buy(-1, amount)) {
// Mark the current status
state = LONG
// Record the current price
holdPrice = r[l - 1].Close
$.PlotFlag(r[l - 1].Time, 'openLong', 'L')
}
} else if (down && (state == LONG || state == IDLE)) {
// The same as the judgment of up condition
if (state == LONG && cover(exchange.Sell, "closebuy")) {
state = IDLE
holdPrice = 0
$.PlotFlag(r[l - 1].Time, 'coverLong', 'CL')
}
exchange.SetDirection("sell")
if (exchange.Sell(-1, amount)) {
state = SHORT
holdPrice = r[l - 1].Close
$.PlotFlag(r[l - 1].Time, 'openShort', 'S')
}
}
// Stop profits
if (state == LONG && r[l - 1].Close - holdPrice > profitTarget && cover(exchange.Sell, "closebuy")) {
state = IDLE
holdPrice = 0
$.PlotFlag(r[l - 1].Time, 'coverLong', 'CL')
} else if (state == SHORT && holdPrice - r[l - 1].Close > profitTarget && cover(exchange.Buy, "closesell")) {
state = IDLE
holdPrice = 0
$.PlotFlag(r[l - 1].Time, 'coverShort', 'CS')
}
// Display time on the status bar
LogStatus(_D())
Sleep(500)
}
}
Strategy source code: https://www.fmz.com/strategy/333269
The strategy is for program design tutorial only, please do not use it in the real bot.