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=.
"""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}")Scale-in strategy that survives a restart
Buys SPY in up to three equal tranches, each a set percent below the first entry, and sells everything once the price is back a set percent above the average cost. Its plan (the first entry and how many tranches are in) is saved in a file on every change and on stop; on start it reads the file back and checks it against what the platform says this strategy holds, which wins.
SPY bull call spread as one order
Once a day at a set time, if SPY is above its 20-day average, buys the at-the-money call and sells the call a few strikes higher as ONE combo at a limit built from each leg's mid price. An unfilled combo is cancelled whole after a few minutes; a filled one is squared off whole if SPY closes a 15-minute bar below the long strike.