Skip to content

Instantly share code, notes, and snippets.

@NoctalIvan
Created August 10, 2022 21:40
Show Gist options
  • Save NoctalIvan/90958baebdefe9313357a2731d6d90ca to your computer and use it in GitHub Desktop.
Save NoctalIvan/90958baebdefe9313357a2731d6d90ca to your computer and use it in GitHub Desktop.
back testing on a deltaSma strategy
// WARNING : FOR EDUCATIVE USE ONLY - DO NOT RUN IN PRODUCTION
const Binance = require('binance-api-node').default
const binance = Binance()
const main = async () => {
// 1 - PRICE ACQUISITION
const prices = await binance.candles({
symbol: 'BTCUSDT',
interval: '1h',
limit: 1000, // 1000 candles = 1000 hours ~= 41.5 days (max in 1 request),
})
// 2 - Initialize last buy container and result array
const gains = []
let lastBuy = null
// 3 - Run a simulation on all prices
console.log(`start simulation on ${new Date(prices[50].closeTime).toUTCString()}`)
for(
let i = 51; // we start at 50 to skip the ones without a reliable 50h SMA
i < prices.length;
i ++
) {
// Those are all "past" prices
const supPrices = prices.slice(0, i+1)
// 3 - Strategy
const lastPrice = supPrices[supPrices.length - 1]
const sma = supPrices.slice(-50).map(x => +x.close).reduce((a, b) => a + b, 0) / 50
const prevSma = supPrices.slice(-51, -1).map(x => +x.close).reduce((a, b) => a + b, 0) / 50
const deltaSma = sma / prevSma - 1
const shouldBuy = deltaSma > 0
const shouldSell = deltaSma < 0
// 4 - Simulate actions
if(!lastBuy && shouldBuy) {
console.log(`\nBUY @${lastPrice.close} - ${new Date(prices[i].closeTime).toUTCString()}`)
lastBuy = lastPrice
} else if (lastBuy && shouldSell) {
console.log(`SELL @${lastPrice.close} - ${new Date(prices[i].closeTime).toUTCString()}`)
// compute gain
let gain = (lastPrice.close - lastBuy.close) / lastBuy.close
lastBuy = null
// do not forget to account for trading fees - 0.075% per trade on Binance with BNB
gain -= 0.00075*2
console.log('- gain:', gain)
// add to result array
gains.push(gain)
}
}
console.log(`End of simulation on ${new Date(prices[prices.length - 1].closeTime).toUTCString()}`)
// lastly, triggers a sell on last price if we have a last buy
if(lastBuy) {
const lastPrice = prices[prices.length - 1]
console.log(`\nSELL @${lastPrice.close}`)
let gain = (lastPrice.close - lastBuy.close) / lastBuy.close - 0.00075*2
console.log('- gain:', gain)
gains.push(gain)
}
// Display some result
const totalGain = gains.reduce((a, b) => a + b, 0)
const averageGain = gains.reduce((a, b) => a + b, 0) / gains.length
const elapsedTime = (prices.length - 50) / 24 // in days
const averageDailyGain = totalGain / elapsedTime
console.table({
trades: gains.length,
totalGain,
averageGain,
elapsedTime,
averageDailyGain
})
}
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment