Untitled

mail@pastecode.io avatar
unknown
typescript
2 years ago
2.5 kB
5
Indexable
Never
/**
 * Apply strategy and calculate the score
 * @param candels Candel[]
 * @returns number
 */
function score(ichiDirection: IchimokuDirection, candels: Candel[]) {
  const lastCandel = candels[candels.length - 1]
  const lastClose = +lastCandel.close

  let score = 0

  // 1- Create indicators
  const adx = new ADX(14)
  const bollingerBands = new BollingerBands(20)
  const stochasticOscillator = new StochasticOscillator(14, 3)
  const macd = new MACD({
    longInterval: 26,
    shortInterval: 12,
    signalInterval: 9,
    indicator: DEMA,
  })

  // 2- Feed indicators
  candels.forEach((c) => {
    adx.update(c)
    bollingerBands.update(c.close)
    stochasticOscillator.update(c)
    macd.update(c.close)
  })

  // 3- Get all indicator results
  const adxRes = adx.getResult().adx.toNumber()
  const bollingerRes = bollingerBands.getResult()
  const stockRes = stochasticOscillator.getResult()

  // 4- ADX doesn't care about direction, so apply score here
  if (adxRes > 25 && adxRes <= 50) {
    score += 1
  } else if (adxRes > 50 && adxRes <= 75) {
    score += 2
  } else if (adxRes > 75) {
    score += 3
  }

  // BollingerBands
  const bbUp = bollingerRes.upper.toNumber()
  const bbMid = bollingerRes.middle.toNumber()
  const bbLow = bollingerRes.lower.toNumber()

  // Stochastic Oscillator
  const stochK = stockRes.k.toNumber()
  const stochD = stockRes.d.toNumber()

  // MACD
  const macdRes = macd.getResult().macd.toNumber()

  // 5- Add score depends on direction
  switch (ichiDirection) {
    case 'LONG':
      {
        // BollingerBands
        if (lastClose >= bbMid && lastClose < bbUp) {
          score += 2
        } else if (lastClose >= bbUp) {
          score += 1
        }

        // Stochastic Oscillator
        if (stochK <= 20 && stochD <= 20) {
          score += 2
        } else if (stochK <= 80 && stochD <= 80) {
          score += 1
        }

        // MACD
        if (macdRes >= 0) {
          score += 1
        }
      }
      break

    case 'SHORT':
      {
        // BollingerBands
        if (lastClose <= bbMid && lastClose > bbLow) {
          score += 2
        } else if (lastClose <= bbLow) {
          score += 1
        }

        // Stochastic Oscillator
        if (stochK >= 80 && stochD >= 80) {
          score += 2
        } else if (stochK >= 20 && stochD >= 20) {
          score += 1
        }

        // MACD
        if (macdRes <= 0) {
          score += 1
        }
      }
      break
  }

  return score
}