Skip to content
Back to skills

Strategy Building Core

ASecurity

Use as the main direct-edit strategy-building skill for new BotSpot strategies and substantial strategy rewrites. Choose the decision owner first, preserving explicit architecture choices and the Python-first default for mechanical builds. It owns the build, plan, validation and final handoff. A fast Python/hybrid recommendation explains avoided AI round-trip latency and credit use. Load supported LumiBot API references only as needed.

  • 2 stars
  • 0 votes
  • 0 copies
  • 0 views
  • Added December 1, 2026
ai-agentspythonexpresstestingapi

Works with

  • terminal
  • api
  • mcp

Security analysis

A100/100

Pro scans all 20 files and shows the line behind each finding

Scanned December 1, 2026

npx -y skills add Lumiwealth/lumibot-trading-skills --skill strategy-building-core --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Strategy Building Core?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Strategy Building Core
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/lumiwealth-strategy-building-core/badge)](https://www.skillsdirectory.com/skills/lumiwealth-strategy-building-core)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: strategy-building-core
public-name: lumibot-strategy-building
visibility: public
title: "Building LumiBot Strategies on BotSpot"
description: "Use as the main direct-edit strategy-building skill for new BotSpot strategies and substantial strategy rewrites. Choose the decision owner first, preserving explicit architecture choices and the Python-first default for mechanical builds. It owns the build, plan, validation and final handoff. A fast Python/hybrid recommendation explains avoided AI round-trip latency and credit use. Load supported LumiBot API references only as needed."
---
> PUBLIC SKILL: served to anyone through the BotSpot MCP. Never add secrets, customer data or internal details.
# Strategy Building Core

Choose the decision owner before writing the first file. New builds whose
rules can be written down and that Python can do easily default to plain
Python, for any asset class, even when the user never says Python. AI-owned
decisions are for strategies that need judgment or outside information, or
when the user asks for AI. Company numbers (revenue growth, P/E, debt, margins)
are built in, so a screen on them is Python. For AI-owned builds load `lumibot-ai-agents`: exactly one agent may
trade, research/planning agents cannot trade, and every configured agent runs
each trading iteration. Preserve an explicit Python/hybrid choice and use the
cadence/latency decision rules below for faster signals. A request mixing a
calculable step with a judgment step (rank 500 stocks, AI reads news on the top
5) is hybrid: load `lumibot-ai-agents` and copy its shortlist example.

Select trading sessions separately from `self.sleeptime`. For continuous crypto,
call `self.set_market("24/7")` in `initialize`, unless the customer restricts
hours. Preserve venue calendars and requested sessions for other instruments.

## Complete the current customer workflow

An edit in an established backtesting conversation is a test-change-test task.
A completed earlier run or plan does not end that workflow. Save the requested
code and coherent Rules, read both from the final revision, then call
`start_backtest` on that revision using the established window, capital and data
settings. Do this before the final answer; the customer need not ask to test again.
Explicit save-only/do-not-backtest instructions and disabled automatic-backtest
preferences take precedence. A standalone edit without a backtesting workflow
finishes after save, readback and the available `review_strategy_change` review;
resolve supported in-scope findings and review any further saved edit. A backtest
is required when requested or for a first build or rescue; "fix it" for broken
or non-trading behavior is a rescue. A no-trade result never authorizes changing
the customer's signal merely to manufacture fills, but code contradicting the
strategy's stated rule is the bug: on "fix", fix it, rerun, say what changed.
A prior run validates only its own revision.

## Record the accepted requirements

RULES LEDGER CONTRACT: User-authored strategy behavior is durable by default,
even when the user never says `rule` or `remember`. Entry and exit conditions, symbols and universes, indicators and
timeframes, sizing and risk, order placement, cadence and frequency, options
construction and delta/DTE/premium constraints, holding behavior, and explicit
allowed or forbidden actions belong in `rules.json`. Load `strategy-rules` for
ledger shape, create/edit/disable history, readback, exact backtest review, and
mixed-turn precedence. Follow that contract on every strategy build or edit,
including requirements embedded in advice, result discussion, backtest
requests, rescue, and AI-only work. Keep executable behavior and the Rules
ledger aligned in the same conversational edit. A manual Rules-tab save is a
ledger-only operation and does not authorize a Python edit.

For a behavior edit with existing Rules, make the task's completion criterion
cover both the executable change and the matching active Rule interpretation.
"Only change this setting" still updates its operative Rule. After the code save, read Rules from that returned revision, reconcile
the requested intent while retaining original quotes and history, then read
both saved files from the final revision before validation.

## Read the request literally

- Trade exactly the instrument named: "nq" is NQ, not MNQ. Offer a smaller stand-in in the reply; never swap.
- "Gets above", "crosses", "breaks", "drops below" are events: enter once when it turns true, again only after it turned false or the position closed and it fires anew. "Add once" is one add per position.
- "N more" adds to the current value: a 3-candle wait plus "two more" is 5.
- Hours or days rules ("first hour", "no fridays") limit entries only; exits and stops act any time.
- "Faster without changing what it does": same trades, less work. Check once per signal bar (sleeptime = that bar size; checking more often is not part of the rules) and ask once per check for only the bars used; removing a duplicate call alone is not faster.
- A number the customer gave (count, length, percent, level) is a `parameters` entry read with `self.get_parameters()`, never typed into the logic.
- Session levels (opening range, session high) use every bar of that session: compute once, keep in `self.vars` for the day.
- A dollar loss limit sets size and stop together: quantity x stop distance = the limit, stop resting from entry; with leverage, size to about 90% of the maximum.
- "Hold N" or "rotate between" splits the money across N holdings (equal parts by default, said in the reply), checking cash before each buy; never all cash into the first pick.
- A scalp or day-trading default has a resting stop, a target, a daily trade cap and stated hours.
- Keep the order type the request implies ("buy when it breaks" is a market or stop entry). Fix a size or cap overshoot by resizing, never with a limit order that may not fill.

## Select the execution owner before writing order logic

For Python execution, read the applicable complete pattern BEFORE implementing
that state owner, rather than as an optional lookup after a failed run. Keep an
existing equivalent owner when it already satisfies the requirements. A narrow
parameter edit does not authorize replacing unrelated working mechanisms.

An expressly requested optimization ("make it faster") is a saved change that
keeps entry, exit, sizing and stops.
The coherent implementation may change producers and their consumers together;
coordinating several methods is no reason to stop after describing the work. Report a concrete unavailable
dependency when one actually prevents the requested change.

Simple signal bots (one asset, signal in and out, market orders): copy
`references/simple-signal-bot-example.py`. Check the position, submit one order
and let LumiBot track it; request native bar sizes instead of resampling minute
bars. A requested stop or target is one bracket/OTO order sent with the entry
and resting at the broker, never a price check in the loop (live bots sleep
between runs). A daily loss limit also closes the open position. Add no order
reconciliation machinery to these bots.
Scanners scan a real universe: copy `references/stock-scanner-example.py`
and save `strategy-building-core:references/sp500_universe.py` beside it with
`create_file(sourceResourceKey=...)`; never a
hand-picked list.
A basket or the strongest few of a list: copy
`references/basket-rotation-example.py`.
Biggest companies or a screen on company numbers: copy
`references/top-market-cap-example.py` or
`references/fundamentals-screen-example.py`; never type counts or caps. The universe is a list of tickers, never an index name.
Long and short, leverage, or a dollar loss limit: copy
`references/long-short-loss-limit-example.py`. Futures Supertrend:
`references/futures-supertrend-daily-loss-example.py`. Supply/demand zone
retest: `references/templates/zone-retest.py`. Save with
`replace_file(sourceResourceKey=..., parameters=...)`.
Load `references/protective-position-example.py` and the order-quantity and
order-operation references only when the request needs them: limit or stop
entries that can sit unfilled, partial fills, scaling in or out, multi-leg
options, rebalancing many positions, orders the bot did not place, or an
explicit ask. Then wire their fill, cancel and retained-exit handling in full.
Send a trailing stop as a resting broker order:
`create_order(asset, qty, "sell", trail_percent=0.03)` (a fraction; 3 is 300%)
or `trail_price=`. Only a volatility-sized distance or a broker without
trailing orders needs `references/trailing-stop-policy.py`.
Reconcile partial fills, canceled/rejected orders and existing positions. Run
risk and accepted exits before entry-only returns; a pending entry cannot bypass
an exit. Cancel conflicting entries when policy requires cash, and confirm
protective-order cancellation before submitting a competing full exit. Retain
unfinished market exits rather than canceling/recreating them each iteration.
A later market sell based on yesterday's low is not a stop fill at the threshold.
Preserve broker/gap constraints and disclose actual data/fill-model limits.

- Only when rebalance orders can sit unfilled or fill in parts, load `references/rebalance-state.md` and `references/rebalance-example.py` and adapt its policy without changing the customer's allocation.
- A target allocation is not spendable cash. For a rebalance, retain the target and outstanding order identities until fills and actual positions reconcile. A weekly/monthly signal schedules new targets; it must not prevent finishing an already accepted rebalance between signal dates. Submit reductions first, then calculate remaining buys from confirmed available cash, existing holdings and still-active orders without counting the same reservation twice. Include fees and execution-price movement. Preserve the customer's weights, universe and cadence; do not hide an execution shortfall by changing their allocation or enabling margin.


For a daily **filled-entry** limit, changing a resettable submission counter is
not the complete repair: yesterday's pending order can first fill today. Before
editing this mechanism, load `references/entry-fill-allowance.py`. Reserve new
entry intent before publication, retain every unresolved attempt across session
reset, and count its first execution once, including partial fills and retries.
Keep submission/attempt limits distinct when that is what the customer requested.
The helper counts entries only; preserve position sizing and order-quantity
reconciliation. Connect the selected pattern to actual submission, partial/full
fill and terminal-order paths before launching verification. Merely loading it,
changing a constant, or disclosing missing lifecycle handling does not implement
the requested limit. Do not classify its pending reservation as a filled trade.
Prefer its complete `EntryOrderLifecycle.for_strategy(self)` factory and wiring:
keep the returned owner on the strategy object, with only its plain state in
`self.vars`. LumiBot Vars supports attributes and `get/set`, not dict subscripting
or `setdefault`. Refresh before entry eligibility,
submit the prepared order through `submit_new`, and observe actual order callbacks.
It preserves reservations on unknown submission errors. Use the lower-level
`observe_order` adapter only when preserving an existing equivalent state owner,
including polling after a missed callback. Keep existing persisted state during
initialization. An unknown historical fill date may use the first observation
as a conservative upper bound; disclose that bound instead of inventing a date
or permanently consuming every future session's allowance.


## Preserve the customer intent across files

For an existing strategy, add the requested behavior to its existing working
state owner before considering a replacement. If a new exit condition can set
accepted exit intent, add the trigger to that existing intent path. Preserve its
pending-order and callback handling. In particular, protective orders and discretionary closing orders have different roles:
cancelling every sell before a new exit can cancel the market close you are
already waiting to fill. An added trigger does not by itself require changing
which existing orders are cancelled or replacing their reconciliation.

Defensive changes outside the requested operation are still behavior changes.
Keep a reconciliation repair within its affected operation; do not transplant
it into sibling entry blockers, deadlines, sizing or scheduling. Compare each
changed method against the request-start file. If a sibling method needs no
change to fulfill the request, retain its original behavior, including its
existing handling of missing data. Report an unrelated concern separately
instead of silently repairing it in a narrow edit.

Use the same requested intent change in both saved representations:

| User's change | Executable behavior | Existing active Rules |
| --- | --- | --- |
| Replace a setting | Change that setting and required consumers | Update its interpretation and history; retain the original quote |
| Add a condition or exit | Add only that behavior | Append a separate active requirement when an existing broad mandate does not conflict |
| Remove a condition | Remove its enforcement | Disable/delete the removed Rule; do not add an active inverse |

A ledger may contain one broad original-mandate Rule rather than separate
conditions. Keeping that Rule unchanged does not record an added behavior:
append the new active requirement with the current request as provenance; preserve the entire existing interpretation, including setup and validation requirements,
unless the existing interpretation must be amended to resolve a real conflict.
"Don't touch anything else" preserves unrelated behavior; it does not omit the
requested behavior from Rules. "Just save" permits both necessary file saves,
without a backtest, deployment or trade. Before the final response, verify two
facts in the final revision: the requested executable change is present AND
the active ledger describes it. Reading Rules without recording the addition
is an incomplete edit.

## Verify the change against its starting point

Use the successful code mutation in this request as evidence of what you changed.
A common sequence is: read code A -> save code B -> save Rules C. The C-versus-B
analysis can truthfully say code did not change in that last save, because
B already contains the change made during this request. It does not mean the
code was unchanged from A. For the customer, lead with the saved behavior and
what validation actually ran. Do not claim that code was already present or
left unchanged when your own successful mutation added it.

When explaining an edit, compare the final saved behavior with the starting revision read before this request's first mutation. A later readback of your own edit does not mean the behavior already existed. Keep the explanation short and distinguish saved changes from tests actually run. For a narrow edit, report the requested saved behavior, validation and material limitations. Do not restate unrelated Rules just to expand the handoff. When a constraint is relevant, minimums remain minimums and preferences remain preferences; do not weaken a required bound into a preference or promote a preference into a guarantee.

For a behavior edit that saved more than one file, retain the original code revision id from the first read. Finish with a consecutive comparison readback: read the code from the original request-start revision, then the final shared revision, and read final Rules. Perform no mutation between these comparison reads. This places the actual starting and saved behavior together for the handoff; a later Rules-only revision analysis compares only its immediate parent. It cannot establish that code was unchanged across the request. Report the verified saved behavior and preserved constraints; do not copy a single-save analysis's retrospective claim into the customer reply.

## Select bounded indicator history

For ordinary built-in moving averages, use the matching built-in and its positive offset for the previous observation. Do not wrap ordinary built-in SMAs in a custom indicator merely to return current and prior values. In LumiBot 4.6.32, `self.indicators.sma(asset, length=N)` requests its finite window; `self.indicators.sma(asset, length=N, offset=1)` includes the prior observation. Recursive/custom calculations retain their broader initialization contract; a period alone does not justify truncating them. Preserve completed-bar timing, corporate-action adjustment and genuinely required missing-data checks. A repeated missing-session occurrence count is not the number of distinct missing sessions: inspect the actual dates, requested length and worker version before diagnosing it.

For a new build, hasStrategy=false means no workspace exists. After the required
research/plan, call create_strategy before get_file or list_files.

Before starting validation, finish the saved-file readback and mark the actual
implementation plan item completed. Then start the backtest; only its returned
wait can complete the start item and put validation in waiting. Do not complete
a later plan row while an earlier implementation row is still in progress.

For an authorized implementation or edit request, finish the smallest coherent
saved change before ending. Describing a needed refactor or inspecting source
alone does not complete that request. Missing live timing or deployment proof
limits the verification claim; it does not by itself prevent editing the owned
source with supported APIs and reading back the result. Preserve behavior,
complete the requested edit, and state the actual remaining validation gap.

## Final build handoff

Use this order in the final handoff, even when validation is queued:

1. State the selected decision owner AND why. For a fast Python/hybrid build:
   "The signal/order path uses Python to avoid an AI model round trip and
   per-call credit use." A statement that Python is deterministic or polling is
   fast does not explain that choice.
2. State the saved rules in plain words: entry, exit or stop, symbols, size.
   Use the revision card, not copied UUIDs. For an edit: one line per change asked for, and that everything else is unchanged.
3. State the actual validation status and relevant feed/broker limitations.
   Waiting, or a test that could not run, is one closing sentence, not the reply.

Broker and scheduling latency are separate from AI model round-trip latency.
The first handoff line must explain the decision owner, rather than substituting
a general broker/feed timing disclaimer for the reason AI calls were avoided.

A new trading date resets only session counters for settled work. It does not
prove that yesterday's order, package, position or hedge obligation is terminal.
Retain and reconcile unresolved operations before clearing their identities or
starting another session's entry; an overnight position cannot disappear from
state because the calendar rolled over.
Retention also needs a completion path: consume confirmed exit fills/flatness,
retire the matching resolved package once, and allow the next eligible entry.
Run pending entry/exit reconciliation before a daily-entry/reset eligibility
return; a blocked reset must not make the code that resolves its blocker
unreachable. Preserve both unresolved obligations and ordinary daily repetition.

When the user explicitly requests historical/backtest-only behavior and forbids
live orders, enforce that choice in the saved executable entrypoint and order
path. Do not retain a live `Trader` fallback or claim live execution is disabled
when the code still permits it. This scoped request does not remove live support
from an ordinary strategy whose user authorized that capability.




After start_backtest, copy the COMPLETE returned externalWaitId unchanged into
record_external_wait_in_plan. It is distinct from backtestId; never reconstruct
it by combining UUID segments. Bind that exact returned wait to existing plan
item identities. If the plan snapshot is stale, refresh it before mutating.


Before saving files, distinguish an empty file from an absent file. BotSpot's
neutral starter already contains `main.py` and an empty `requirements.txt`.
Read and replace that existing requirements file with its fresh edit handle;
never use `create_file` for it. Discover any other missing path before creating
it.


## Preserve the execution contract in saved code

An explicitly initial-capital budget is a stable baseline: persist the first
verified portfolio value in `self.vars`, then reuse it across iterations and
restarts. Capture that anchor at the first point account value is known, BEFORE
any independent price/history/quote check can return early. A missing price must
not postpone the baseline until a later, changed account value. Use an explicit
missing test, not a truthiness fallback that overwrites an existing baseline.
Do not substitute the changing current portfolio value. Current-value sizing
remains appropriate when that is what the user's Rules specify.

On an explicit repair request, an observed exception from a public initial-
budget property can be handled with this same persistent starting-value anchor,
using the original configured budget or first verified public account value.
Preserve the allocation rule and never invent a balance. A current framework
reference defining the property does not prove its backing value was available
in the failing deployed lifecycle. Keep that root cause uncertain while
preparing the narrow compatibility repair. A broker reconnect requirement is
separate: save/read back the safe revision and prepare the same deployment's
owner approval using its authoritative credential state, without guessing a
credential or claiming the prepared repair is already running.

Give entry/submission latches the lifetime required by the Rules and the owned
order lifecycle. A latch used to prevent duplicates must not silently disable
later eligible sessions or entries. Re-arm only after the relevant terminal
orders, positions and hedge obligations reconcile; preserve an explicit one-time
strategy rule when the user actually requested one. Trace the reset caller in
the saved code: setting `entry_submitted=True` with no reachable re-arm path is
a permanent shutdown, even if the smoke window only contains one trade. For a
recurrent Rule, reconcile its owned terminal order and flat/closed position,
then let the next eligible session or signal evaluate again. A per-session
allowance uses the strategy's actual trading-session key, not a lifetime flag.

A trading AI's own saved instructions must verify current account state,
positions, open orders, exact contract identities, executable package prices and
liquidity immediately before acting. Adviser output and a separate Rules file
do not perform that verification. When the requested structure is defined-risk
and atomic, preserve that submission contract and verify its returned result
before describing execution. Keep these instructions with the trading owner;
research agents advise without submitting orders.

Explain an architecture recommendation against the requested cadence: model
calls add variable latency and credit cost to a signal path. Deterministic
rules can use ordinary Python; discretionary reasoning can use AI with an
appropriate cadence. In the final recommendation, connect that choice to the
user's deadline: Python avoids a model round trip on a fixed-rule signal path;
full AI reasoning adds variable response latency and per-cycle credit use.
Quote/broker delay is a separate limitation, not that architecture explanation.
Preserve an explicit AI-only or fixed-rules choice.

## Plan transitions during creation and repair

Use the exact returned current item IDs and positions, refreshing get_active_plan
when the visible snapshot is stale. update_plan_item(s) changes existing rows;
it cannot append a future position. Never reopen a completed historical attempt.
Before appending an in_progress replacement, resolve every earlier unresolved
row with its true satisfied/partial/unsuccessful outcome. If a required step
cannot yet be done, preserve that gap and link the actual follow-up rather than
marking it successful. Use replace_plan_items with the full visible list for
an atomic transition, or resolve the current row then add_plan_item with a nested
item object. Copy the returned new identity before updating it. Creation,
saving, validation start and terminal validation are different outcomes.

## Load only the workflow needed now

The common requirements above apply to every creation and edit. For a narrow
setting edit, use this core and `strategy-rules`; do not load an entire build
workflow merely to change one setting. Read a focused reference when its
workflow applies or a specific implementation fact is missing:

- New strategy: `references/first-build-workflow.md`.
- Substantial existing-code edit or repair loop: `references/existing-edit-workflow.md`.
- Cash sizing and complete exits: `references/cash-and-exits.md`.
- Marketplace and dependency preparation: `references/build-preparation.md`.
- Independent preparation, data and API setup: `references/preparation-reads.md`.
- Extended US equity hours: `references/extended-hours-workflow.md`.

These are complete workflow resources, not a checklist to load in every turn.

## Supported implementation references

The implementation catalog has one owner: `lumibot-api-reference`. Use its
existing `load_skill_resource` references for the specific API fact needed by
this build or edit. The core workflow does not embed a second copy of those
references. Preserve the customer's architecture and requirements while using
the supported API; a reference example is not permission to change their rules.

- File/class shape: `references/strategy-structure.md`.
- Historical bars, price methods, orders and positions: `references/methods-properties.md`.
- Fills, partial fills, cancellation, restart and reconciliation: `references/lifecycle-methods.md`.
- Asset/contract identity and base/quote pairs: `references/entities.md`.
- A reusable implementation pattern: `references/examples.md`.
- Fast cancel/hedge deadlines: `references/fast-order-management.md`.

These paths belong to `skill_name="lumibot-api-reference"`. Load the smallest
relevant reference, then return to implementation. Do not load this list as a
checklist, and do not load the large examples catalog for a simple edit whose
API contract is already established. If an exact method or broker behavior is
still uncertain, inspect the corresponding supported LumiBot source. Missing
or conflicting evidence requires a source check, not an invented signature.

Files in this skill

  • SKILL.md26.3 KB
  • references/assets/crypto-strategies.md2.6 KB
  • references/assets/futures-strategies.md473 B
  • references/assets/options-strategies.md2 KB
  • references/assets/stock-etf-strategies.md2.6 KB
  • references/backtest-validation.md7.5 KB
  • references/basket-rotation-example.py8.9 KB
  • references/build-preparation.md11.5 KB
  • references/cash-and-exits.md7.8 KB
  • references/crypto-strategies.md3.9 KB
  • references/editing-existing-strategies.md6.9 KB
  • references/entry-fill-allowance.py11.8 KB
  • references/existing-edit-workflow.md53.1 KB
  • references/extended-hours-equities.md7.9 KB
  • references/extended-hours-workflow.md11.1 KB
  • references/first-build-workflow.md46.7 KB
  • references/fundamentals-screen-example.py6.1 KB
  • references/futures-strategies.md4.8 KB
  • references/futures-supertrend-daily-loss-example.py8.9 KB
  • references/long-short-loss-limit-example.py8.9 KB

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in ai-agents →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.