3. Higher order functions in automating buy or sell orders
def mean(list: List[Double]): Double = {
list.isEmpty match {
case true => 0
case false => list.sum / list.size
}
}
def ascending[A](list: List[A])(implicit ord: Ordering[A]): Boolean = {
(list.size < 2) match {
case true => true
case false => list.sliding(2).forall { case List(a, b) => ord.lteq(a, b) }
}
}
val mean_reversion = (prices: List[Double], threshold:Double) => {
(prices.last - mean(prices)) > threshold
}
val momentum = (prices: List[Double], threshold: Double) => {
ascending(prices) && ((prices.last - prices.head) > threshold)
}
def runStrategy(strategy: (List[Double], Double) => Boolean,
prices:List[Double], threshold:Double) : Boolean = {
strategy(prices, threshold)
}
def main(args: Array[String]) : Unit = {
val prices = List(..)
val threshold = ...
Boolean isTradingOpportunity = runStrategy(mean_reversion, prices, threshold)
// we can plug and play a different strateegy as below
// Boolean isTradingOpportunity = runStrategy(momentum, prices, threshold)
}
Last updated