With BacktestJS you can

Easily download candle data from binance and export to a csv.

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

Simple SMA

Estimated reading: 1 minute 153 views

Summary: How to code a simple sma trading strategy.

About

In the code below we code a very simple sma strategy, the flow is defined below:

1. Get the last 3 candles and the last 90 candles
2. Use the candles from step 1 to get the sma for 3 and 90 (3 is the low sma and 90 is the high sma)
4. Buy if the low sma is higher then the high sma
5. Sell if the low sma is lower then the high sma

*** The application is smart enough to know that you bought in with everything on the first buy and cant buy again if the low sma is higher than the high sma for multiple candles.  The same logic goes for the sell, you will only sell if you are actually bought in.

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

// Simple SMA Strategy
export async function sma(bth: BTH) {
    // Get last 3 candles
    const lowSMACandles = await bth.getCandles('close', 0, 3)
    // Get last 90 candles
    const highSMACandles = await bth.getCandles('close', 0, 90)

    // Get low SMA (3 SMA)
    const lowSMA = await indicatorSMA(lowSMACandles, 3, 1)
    // Get high SMA (90 SMA)
    const highSMA = await indicatorSMA(highSMACandles, 90, 1)

    // Buy if lowSMA crosses over highSMA
    if (lowSMA > highSMA) {
        await bth.buy()
    }

    // Sell if lowSMA crosses under highSMA
    else {
        await bth.sell()
    }
}
				
			

Leave a Comment