Skip to Content
While25SDK docs
ExamplesStrategies

Moving-average trend on a Bars line

Holds MSFT while its fast average is above its slow one and is flat otherwise, deciding on each closed hourly bar. The `Bars` line arrives warmed up, so the first decision already has its history; exits are sized from what this strategy holds, never from the account.

Holds MSFT while its fast average is above its slow one and is flat otherwise, deciding on each closed hourly bar. The Bars line arrives warmed up, so the first decision already has its history; exits are sized from what this strategy holds, never from the account.

Shows: Strategy, typed inputs (Int), Bars, @on.bar(line), line.closes, portfolio.my_position(), buy/sell, tag=.

View on GitHub

strategies/sma_trend.py
"""Moving-average trend on a Bars line

Holds MSFT while its fast average is above its slow one and is flat
otherwise, deciding on each closed hourly bar. The `Bars` line arrives warmed
up, so the first decision already has its history; exits are sized from what
this strategy holds, never from the account.

Shows: Strategy, typed inputs (Int), Bars, @on.bar(line), line.closes, portfolio.my_position(), buy/sell, tag=.
"""
from decimal import Decimal

import while25
from while25 import Bars, Strategy, on
from while25.inputs import Int

KEY = "EQ:US:MSFT"
KEEP = 300          # the most bars the slow average may span


def sma(values, n):
    """The mean of the last n values, or None while there are fewer."""
    if n < 1 or len(values) < n:
        return None
    return sum(values[-n:]) / n


def target_shares(closes, fast, slow, shares):
    """`shares` while the fast average is above the slow one, else 0.
    None while either average is still warming up: no decision yet."""
    f, s = sma(closes, fast), sma(closes, slow)
    if f is None or s is None:
        return None
    return shares if f > s else 0


def order_delta(held, target):
    """What to buy (+) or sell (-) to go from `held` to `target` shares."""
    return Decimal(target) - Decimal(held)


class SmaTrend(Strategy):
    id = "sma_trend"
    label = "MSFT moving-average trend"
    version = "1.0.0"
    inputs = [Int("fast", default=20, minimum=2, maximum=100),
              Int("slow", default=100, minimum=3, maximum=KEEP),
              Int("shares", default=10, minimum=1, maximum=10_000)]

    msft = Bars(KEY, "1h", keep=KEEP)

    @on.bar(msft)
    def on_bar(self, ctx, bar):
        p = while25.params
        target = target_shares(self.msft.closes, p["fast"], p["slow"], p["shares"])
        if target is None:
            return
        mine = while25.portfolio.my_position(KEY)          # this strategy's own part
        held = mine["quantity"] if mine else Decimal(0)
        delta = order_delta(held, target)
        if delta > 0:
            while25.buy(KEY, delta, tag="sma_trend")
            while25.log(f"fast above slow at {bar['close']}: buy {delta}")
        elif delta < 0:
            while25.sell(KEY, -delta, tag="sma_trend")
            while25.log(f"fast below slow at {bar['close']}: sell {-delta}")