Skip to Content
While25SDK docs
ExamplesStrategies

Risk-sized stop-limit entry from the account's buying power

Each day MSFT closes above its 50-day average, rests a stop-limit buy just above that day's high, with a protective stop under its low. The share count risks a fixed fraction of the money the broker says is available for a new trade, and is checked against the venue's size and tick rules before anything is sent. When the broker states no such figure, it does not trade.

Each day MSFT closes above its 50-day average, rests a stop-limit buy just above that day's high, with a protective stop under its low. The share count risks a fixed fraction of the money the broker says is available for a new trade, and is checked against the venue's size and tick rules before anything is sent. When the broker states no such figure, it does not trade.

Shows: portfolio.funds() figures and the "available" role, funds_unavailable_reason(), Money, order_type="STP LMT", trigger_price=, stop_loss= (a bracket), Instrument.offset()/snap()/check()/notice().

View on GitHub

strategies/risk_sized_entry.py
"""Risk-sized stop-limit entry from the account's buying power

Each day MSFT closes above its 50-day average, rests a stop-limit buy just
above that day's high, with a protective stop under its low. The share count
risks a fixed fraction of the money the broker says is available for a new
trade, and is checked against the venue's size and tick rules before anything
is sent. When the broker states no such figure, it does not trade.

Shows: portfolio.funds() figures and the "available" role, funds_unavailable_reason(), Money, order_type="STP LMT", trigger_price=, stop_loss= (a bracket), Instrument.offset()/snap()/check()/notice().
"""
from decimal import ROUND_FLOOR, Decimal

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

KEY = "EQ:US:MSFT"
TAG = "msft_risk"


def available_money(funds):
    """The figure the broker marks "available" (IBKR's Current Available
    Funds, Alpaca's Buying power) as (Decimal, currency), or None when the
    broker states none. Never a 0 for "not stated"."""
    if funds is None:
        return None
    fig = next((g for g in funds["figures"] if "available" in g["roles"]), None)
    if fig is None or fig["value"] is None:
        return None
    return fig["value"], fig["currency"]


def risk_shares(capital, risk_pct, entry, stop, step):
    """Shares whose loss from `entry` to `stop` is `risk_pct` percent of
    `capital`, rounded down to the venue's step; 0 when nothing fits."""
    per_share = Decimal(entry) - Decimal(stop)
    if per_share <= 0:
        return Decimal(0)
    budget = Decimal(capital) * Decimal(str(risk_pct)) / 100
    step = step or Decimal(1)
    return (budget / per_share / step).to_integral_value(rounding=ROUND_FLOOR) * step


def entry_levels(inst, high, low, ticks_above, slip_ticks):
    """(trigger, limit, stop) on the tick grid: trigger `ticks_above` ticks
    over the high, the limit `slip_ticks` over the trigger, the stop a tick
    under the low."""
    trigger = inst.offset(high, ticks_above)
    limit = inst.offset(trigger, slip_ticks) if trigger is not None else None
    stop = inst.offset(inst.snap(low, mode="down"), -1)
    return trigger, limit, stop


class RiskSizedEntry(Strategy):
    id = "msft_risk_sized"
    label = "MSFT risk-sized stop-limit entry"
    inputs = [Float("risk_pct", default=0.5, minimum=0.05, maximum=5.0, step=0.05,
                    label="Risk per trade (% of available)"),
              Int("ticks_above", default=1, minimum=1, maximum=50),
              Int("slip_ticks", default=5, minimum=0, maximum=100,
                  label="Limit this many ticks past the trigger"),
              Int("trend_length", default=50, minimum=5, maximum=200)]

    daily = Bars(KEY, "1D", keep=250)

    def on_start(self, ctx):
        self.inst = while25.data.instrument(KEY)

    @on.bar(daily)
    def on_day(self, ctx, bar):
        p = while25.params
        closes = self.daily.closes
        n = p["trend_length"]
        if len(closes) < n or bar["close"] <= sum(closes[-n:]) / n:
            return
        mine = while25.portfolio.my_position(KEY)
        if (mine and (mine["quantity"] != 0 or mine["brackets"])) or while25.orders.mine(KEY):
            return                              # already in, or an entry is waiting

        cash = available_money(while25.portfolio.funds())
        if cash is None:
            why = while25.portfolio.funds_unavailable_reason() or "no available figure"
            while25.log(f"not sizing a trade: the broker states no buying power ({why})", "warn")
            return
        capital, currency = cash
        trigger, limit, stop = entry_levels(self.inst, bar["high"], bar["low"],
                                            p["ticks_above"], p["slip_ticks"])
        if None in (trigger, limit, stop):
            while25.log("the venue states no tick for MSFT: no entry", "warn")
            return
        qty = risk_shares(capital, p["risk_pct"], limit, stop, self.inst.step)
        problem = self.inst.check(quantity=qty, price=limit, side="BUY") if qty else "size is 0"
        if problem:
            while25.log(f"no entry: {problem}")
            return
        gap = self.inst.notice(quantity=qty, price=limit)
        if gap:
            while25.log(gap)                    # sent anyway; the venue judges it
        while25.buy(KEY, qty, order_type="STP LMT", trigger_price=trigger, price=limit,
                    stop_loss=stop, validity="day", tag=TAG)
        while25.log(f"{qty} above {trigger} (limit {limit}), stop {stop}: "
                    f"{p['risk_pct']}% of {capital} {currency}")