With BacktestJS you can

Quickly see all trades, income graphs, buy / sell graphs and much more

leafleafleafDocy banner shape 01Docy banner shape 02Man illustrationFlower illustration
Trading Strategy Examples

SMA With Shorting & Stop Loss

Estimated reading: 2 minutes 157 views

Summary: Code a more advanced sma trading strategy including shorting / stop losses.

About

In this example we will continue from the last example and add shorting logic and stop loss logic as well as add another param for the stop loss.  Lets start by creating the strategy

Create Trading Strategy SMA With Stop Loss

In the below example we continue from the last example but add shorting and a stop loss based off of a percentage.  

Performing a short can be achieved by simply putting a position type within the buy (line 40).  Also in both the long and short buys we set a stop loss.  The stop loss uses the stopLoss param coming from the input when running the trading strategy.  In the end the stop loss is set to the buying price – x percent for long or buying price + x percent when shorting.

One important note is the addition of checking if you are bought in or not (lines 28 and 39), while this is not mandatory as you are buying with all your assets its a good habit to get into.

				
					// Must Define Params: lowSMA, highSMA, stopLoss

// Define imports
import { BTH } from "../infra/interfaces"
import { indicatorSMA } from "../indicators/moving-averages"

// SMA Strategy With Shorthing and Stop Loss
export async function sma(bth: BTH) {
    // Get low and high SMA and stop loss from input
    const lowSMAInput = bth.params.lowSMA
    const highSMAInput = bth.params.highSMA
    const stopLoss = bth.params.stopLoss

    // Get last candles based on low and high SMA
    const lowSMACandles = await bth.getCandles('close', 0, lowSMAInput)
    const highSMACandles = await bth.getCandles('close', 0, highSMAInput)

    // Get low and high SMA
    const lowSMA = await indicatorSMA(lowSMACandles, lowSMAInput, 1)
    const highSMA = await indicatorSMA(highSMACandles, highSMAInput, 1)

    // Buy long if lowSMA crosses over highSMA and set stop loss
    if (lowSMA > highSMA) {
        // Sell if bought into a short
        if (bth.orderBook.boughtShort) await bth.sell()

        // Only buy if not already bought into a long
        if (!bth.orderBook.boughtLong) {
            await bth.buy({ stopLoss: bth.currentCandle.close * (1 - (stopLoss / 100)) })
        }
    }

    // Buy short if lowSMA crosses under highSMA
    else {
        // Sell if bought into a long
        if (bth.orderBook.boughtLong) await bth.sell()

        // Only buy if not already bought into a short
        if (!bth.orderBook.boughtLong) {
            await bth.buy({ position: 'short', stopLoss: bth.currentCandle.close * (1 + (stopLoss / 100)) })
        }
    }
}
				
			

Below is an example of what running the trading strategy would look like with multiple stop losses as well as low and high sma’s!!  Remember this will test every combination possible with all the params provided.

Run Trading Strategy SMA With Stop Loss

Leave a Comment