Skip to Content
While25SDK docs
ExamplesStrategies

Two strategies on one instrument, one account

A slow trend strategy and a fast mean-reversion strategy both trade NVDA. The broker nets their fills into one position, but each strategy keeps its own part: each tags its orders, listens only to its own tag, and sizes every exit from `my_position()`, never from the account's `position()`. Each also reads its part again when the whole position is squared off.

A slow trend strategy and a fast mean-reversion strategy both trade NVDA. The broker nets their fills into one position, but each strategy keeps its own part: each tags its orders, listens only to its own tag, and sizes every exit from my_position(), never from the account's position(). Each also reads its part again when the whole position is squared off.

Shows: two Strategy classes in one file, tag= on orders and @on.order(tag=), my_position() vs portfolio.position(), POSITION_SQUARED_OFF, a shared pure helper.

View on GitHub

strategies/two_strategies_one_account.py
"""Two strategies on one instrument, one account

A slow trend strategy and a fast mean-reversion strategy both trade NVDA. The
broker nets their fills into one position, but each strategy keeps its own
part: each tags its orders, listens only to its own tag, and sizes every exit
from `my_position()`, never from the account's `position()`. Each also reads
its part again when the whole position is squared off.

Shows: two Strategy classes in one file, tag= on orders and @on.order(tag=), my_position() vs portfolio.position(), POSITION_SQUARED_OFF, a shared pure helper.
"""
from decimal import Decimal

import while25
from while25 import Bars, Strategy, on

KEY = "EQ:US:NVDA"


def own_quantity(mine):
    """This strategy's part, outside any bracket: 0 when it has nothing there."""
    return mine["quantity"] if mine else Decimal(0)


def zscore(values, n):
    """How far the last value sits from the mean of the last n, in standard
    deviations; None with fewer than n values or no spread."""
    if len(values) < n:
        return None
    w = values[-n:]
    mean = sum(w) / n
    sd = (sum((v - mean) ** 2 for v in w) / n) ** 0.5
    return None if sd == 0 else (w[-1] - mean) / sd


class NvdaTrend(Strategy):
    """Holds 20 shares while the hourly close is above its 50-hour average."""
    id = "nvda_trend"
    label = "NVDA trend (slow)"
    hourly = Bars(KEY, "1h", keep=60)

    @on.bar(hourly)
    def on_bar(self, ctx, bar):
        closes = self.hourly.closes
        if len(closes) < 50:
            return
        held = own_quantity(while25.portfolio.my_position(KEY))
        target = Decimal(20) if closes[-1] > sum(closes[-50:]) / 50 else Decimal(0)
        if target > held:
            while25.buy(KEY, target - held, tag="nvda_trend")
        elif target < held:
            while25.sell(KEY, held - target, tag="nvda_trend")

    @on.order(tag="nvda_trend")
    def on_order(self, ctx, ev):
        if ev["event"] == "POSITION_SQUARED_OFF":
            account = while25.portfolio.position(KEY)
            while25.log(f"the whole position was squared off ({ev['reason']}); "
                        f"mine is now {own_quantity(while25.portfolio.my_position(KEY))}, "
                        f"the account's {account['quantity'] if account else 0}")


class NvdaReversion(Strategy):
    """Buys 5 shares when a 5-minute close is 2 standard deviations under its
    recent mean, and sells them back at the mean."""
    id = "nvda_reversion"
    label = "NVDA mean reversion (fast)"
    fast = Bars(KEY, "5m", keep=40)

    @on.bar(fast)
    def on_bar(self, ctx, bar):
        z = zscore(self.fast.closes, 30)
        if z is None:
            return
        held = own_quantity(while25.portfolio.my_position(KEY))
        if held == 0 and z <= -2:
            while25.buy(KEY, 5, tag="nvda_revert")
        elif held > 0 and z >= 0:
            while25.sell(KEY, held, tag="nvda_revert")      # its own 5, not the trend's 20

    @on.fill(tag="nvda_revert")
    def on_fill(self, ctx, ev):
        while25.log(f"{ev['side']} {ev['last_fill_quantity']} @ {ev['last_fill_price']}")