Strategy Development Documentation
Complete reference for building automated trading strategies with ByteTrader.
Your strategies implement IAgentStrategy and interact with broker, data,
agent, and storage services. All types live in the BTStrategy namespace.
Calling ByteTrader's market data over REST instead? See the Data API reference.
IAgentStrategy
The core interface your strategy must implement. ByteTrader injects all service instances at runtime: _broker, _data, _agent, _store, _logger, and _clock (an ITradingClock — read time from this instead of DateTime.UtcNow so the strategy stays deterministic under backtest replay). Override the lifecycle methods and subscribe to data events in OnAgentBoot. All lifecycle methods return Task — exceptions thrown from your code are caught and logged by the agent host rather than tearing down the process.
/// <summary>
/// The core strategy interface. Implement this to build your trading logic.
/// ByteTrader injects all service instances automatically at runtime.
/// </summary>
public interface IAgentStrategy
{
// --- Injected services ---
/// <summary>Agent control: manage symbols, send inter-agent messages.</summary>
public IAgent _agent { get; set; }
/// <summary>Broker access: place orders, query positions, check balances.</summary>
public IBroker _broker { get; set; }
/// <summary>Persistent key-value storage that survives between sessions.</summary>
public IStorage _store { get; set; }
/// <summary>Real-time market data: candles, indicators, quotes, trades, news.</summary>
public IData _data { get; set; }
/// <summary>Standard .NET logger for agent output and diagnostics.</summary>
public ILogger _logger { get; set; }
/// <summary>
/// Time source. READ FROM THIS instead of DateTime.UtcNow for any
/// time-of-day check, daily-reset trigger, or now-stamping logic.
/// Live: a wall-clock wrapper. Backtest: driven by the engine's event
/// loop, advancing bar-by-bar — reading DateTime.UtcNow directly would
/// return real time and silently desync the strategy from the simulated
/// bar stream. Wired by the host before [Initialize] runs. See the
/// Trading Clock section for members (UtcNow, NowEt, TodayEt, ...).
/// </summary>
public ITradingClock _clock { get; set; }
/// <summary>The list of symbols this agent is currently trading.
/// Mutated by the host when AddSymbol/DropSymbol/SetSymbols is called.</summary>
public List<string> ActiveSymbols { get; set; }
// --- Lifecycle hooks ---
// All lifecycle methods return Task. The agent host AWAITS them so any
// thrown exception is caught and logged rather than tearing down the
// process. Using async void or void here would be a footgun.
/// <summary>
/// Called once when the agent starts. Subscribe to data events here.
/// The default implementation wires up every available event handler;
/// override to only subscribe to the events you actually use.
/// </summary>
[Initialize]
public async Task OnAgentBoot()
{
_agent.Message += OnAgentMessage;
_data.IndicatorUpdate += OnIndicatorUpdate;
_data.CandleUpdate += OnCandleUpdate;
_data.SnapshotRefresh += OnSnapshotRefresh;
_data.QuoteUpdate += OnQuoteUpdate;
_data.TradeUpdate += OnTradeUpdate;
_data.NewsUpdate += OnNewsUpdate;
_data.MarketEventUpdate += OnMarketEvent;
}
/// <summary>Called near market open each trading day (after data is warmed up).</summary>
[DailySetup]
public async Task DailySetup() { }
/// <summary>Called near market close each trading day.</summary>
[DailyCleanup]
public async Task DailyCleanup() { }
// --- Event handlers (override these to implement your strategy) ---
private void OnAgentMessage(object? sender, Envelope message)
{
// message.Source is server-stamped: Agent (sent by another agent)
// vs Webhook (POSTed by an external system to your webhook URL).
// message.Message is the raw payload; message.Read<T>() deserializes
// a JSON payload into a typed model. See the Messaging & Webhooks
// section for the full Envelope shape.
}
private void OnIndicatorUpdate(object? sender, (string Symbol, string Indicator) key)
{
// Example: var rows = _data.Indicators[key];
// var lastRsi = ((RsiRow)rows[rows.Count - 1]).RSI;
}
private void OnCandleUpdate(object? sender, (string Symbol, Interval Interval) key)
{
// Example: var candles = _data.Candles[key];
// var lastClose = candles[candles.Count - 1].Close;
}
private void OnQuoteUpdate(object? sender, Quote quote) { }
private void OnTradeUpdate(object? sender, Trade trade) { }
private void OnNewsUpdate(object? sender, NewsArticle article) { }
/// <summary>
/// Structured market events (SEC/FINRA catalysts + derived signals). See the
/// Market Events section. Distinct from OnNewsUpdate — carries typed detail.
/// </summary>
private void OnMarketEvent(object? sender, MarketEvent evt) { }
/// <summary>
/// Snapshot refresh is async — the host awaits this handler so you can
/// safely call broker / data methods here without worrying about
/// unhandled exceptions.
/// </summary>
public async Task OnSnapshotRefresh(object? sender, SnapshotData snapshot)
{
// Example: rebuild trading universe from snapshot.Overview
// and apply via _agent.SetSymbols(...)
}
}
Lifecycle Attributes
Custom attributes that mark strategy lifecycle methods. The agent runtime discovers them via reflection and calls the marked method automatically at the appropriate time — on boot ([Initialize]), at session start ([DailySetup]) and end ([DailyCleanup]) each trading day, and on a hot code-swap of a running agent ([OnRebind]). Each attribute can appear on at most one method per strategy class. [OnRebind] is optional — most strategies never need it; use it only to re-attach lambda subscriptions or rebuild transient caches when a running agent's strategy is republished in place.
/// <summary>
/// Marks a method to run ONCE when the agent boots up.
/// Use this for initialization: subscribe to events, load persisted state,
/// configure the news filter, set AllowedSenders, etc. The method must
/// return Task — the agent host awaits it.
/// </summary>
[AttributeUsage(AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public sealed class Initialize : Attribute { }
/// <summary>
/// Marks a method to run near market open EACH trading day.
/// Use this for daily setup: refreshing watchlists from the snapshot,
/// resetting daily counters, recalculating session-of-day baselines, etc.
/// </summary>
[AttributeUsage(AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public sealed class DailySetup : Attribute { }
/// <summary>
/// Marks a method to run near market close EACH trading day.
/// Use this for end-of-day cleanup: closing positions, logging summaries,
/// persisting daily P&L, etc. The host calls this BEFORE the broker
/// connection is torn down so you can still place exit orders here.
/// </summary>
[AttributeUsage(AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public sealed class DailyCleanup : Attribute { }
/// <summary>
/// Marks a method to run on a HOT CODE-SWAP (rebind) — when a RUNNING agent's
/// strategy is replaced in place with a republished version. NOT called on a
/// normal boot ([Initialize] handles that). It runs after the framework has
/// already (1) re-wired the same broker/data/storage/clock, (2) copied across
/// your matching data fields, and (3) re-attached your NAMED event handlers —
/// but BEFORE the new instance starts receiving market data.
///
/// Use it only to re-establish what the framework can't transfer automatically:
/// re-add lambda or newly-added event subscriptions, rebuild a transient/derived
/// cache, or re-derive state from _store / current broker positions. Do NOT
/// re-run one-time setup here (no universe re-selection, no startup orders) —
/// the agent is mid-session with positions, orders, and indicators preserved.
/// Optional — most strategies never need it.
/// </summary>
[AttributeUsage(AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public sealed class OnRebind : Attribute { }
// Example — re-attach a lambda subscription that the framework can't auto-rewire:
//
// [OnRebind]
// public async Task OnRebind()
// {
// _data.DepthUpdate += (_, book) => _lastBook = book; // lambda — must re-add
// await Task.CompletedTask;
// }
Trading Clock (ITradingClock)
The time source injected as _clock. Read from this instead of DateTime.UtcNow for any time-of-day check, daily-reset trigger, or now-stamping logic. In live execution it's a thin wall-clock wrapper; in a backtest it's driven by the engine's event loop and advances bar-by-bar, so the same strategy code stays deterministic and aligned with the simulated bar stream. The rule: anything that affects a trading decision or order timing reads from _clock; pure infrastructure (HTTP retry backoff, log line timestamps) can still call DateTime.UtcNow. It's wired by the host before [Initialize] runs, so it's safe to read from any lifecycle method or event handler.
/// <summary>
/// Abstraction for "the current trading time", injected into every
/// strategy as _clock. Read from this instead of DateTime.UtcNow — the
/// latter returns wall-clock time even during a backtest replay, which
/// would silently corrupt time-of-day checks, daily-reset triggers, and
/// any other temporal logic.
/// <para>
/// Two implementations exist:
/// — LiveTradingClock: wraps DateTime.UtcNow for live agent execution.
/// — BacktestTradingClock: driven by the backtest engine's event loop;
/// advances bar-by-bar so TIF expirations, OCO trigger timing, audit
/// timestamps, and strategy-readable time are all deterministic and
/// aligned with the simulated bar stream.
/// </para>
/// <para>
/// Convention: strategies that need wall-clock time for infra purposes
/// (HTTP retries, log line timestamps) can still call DateTime.UtcNow.
/// The rule: anything affecting a trading decision or order timing reads
/// from _clock; anything affecting infrastructure can use real time.
/// </para>
/// </summary>
public interface ITradingClock
{
/// <summary>Current UTC instant. Always carries DateTimeKind.Utc.</summary>
DateTime UtcNow { get; }
/// <summary>Same as UtcNow as a DateTimeOffset with zero offset.</summary>
DateTimeOffset UtcNowOffset { get; }
/// <summary>Current wall-clock time in US Eastern, as a DateTime with
/// DateTimeKind.Unspecified (do NOT pass it through another timezone
/// conversion).</summary>
DateTime NowEt { get; }
/// <summary>Current date in US Eastern. Convenience for
/// "is this order from a prior trading day?" comparisons.</summary>
DateOnly TodayEt { get; }
}
// Example — gate logic on the session clock instead of DateTime.UtcNow so
// it behaves identically live and in backtest:
//
// [DailySetup]
// public async Task DailySetup()
// {
// // Only arm the entry window after 09:35 ET (skip the open auction).
// if (_clock.NowEt.TimeOfDay < new TimeSpan(9, 35, 0))
// return;
//
// _sessionDate = _clock.TodayEt; // reset daily counters keyed by date
// }
IBroker
The broker service interface available via _broker. Use it to query account info, manage positions, place orders (including OCO exit pairs), and subscribe to order lifecycle events. It is the same interface for every supported broker (Alpaca, Charles Schwab, Interactive Brokers, E*TRADE, TradeStation, tastytrade, Coinbase, Kraken and the built-in Paper broker); what each broker accepts differs, see /brokers.
public enum BrokerClient
{
None,
Paper, // Built-in simulated broker (24/7 fills)
AlpacaPaper, // Alpaca paper trading
AlpacaLive, // Alpaca live trading
Schwab, // Charles Schwab
Etrade, // E*TRADE
InteractiveBrokers, // IBKR via Client Portal API
TradeStation, // TradeStation v3 REST
Tastytrade, // tastytrade (stocks, options, futures; no extended hours)
Coinbase, // Coinbase spot crypto
Kraken // Kraken spot crypto
}
/// <summary>
/// Broker service for order execution and account management.
/// Access via _broker in your strategy. The interface is identical across
/// every broker — broker-specific quirks (extended-hours field names,
/// OCO support, etc.) are translated by the concrete BrokerBase subclass.
/// </summary>
public interface IBroker
{
/// <summary>Which broker this instance is connected to.</summary>
BrokerClient Client { get; }
// --- Account ---
Task<AccountInfo> GetAccountInfoAsync();
Task<decimal> GetCashBalanceAsync();
Task<decimal> GetBuyingPowerAsync();
// --- Positions ---
Task<IReadOnlyList<Position>> GetPositionsAsync();
Task<Position?> GetPositionAsync(string symbol);
// --- Orders ---
/// <summary>Submit a single order (market, limit, stop, stop-limit, trailing).</summary>
Task<Order> PlaceOrderAsync(OrderRequest request);
/// <summary>
/// Submit a One-Cancels-Other exit pair (target + stop linked) for an
/// open position. Returns null if the broker doesn't support OCO; the
/// caller should then fall back to placing the stop alone (forgoing
/// the auto-target) or use bracket orders on entry. See the OCO
/// section for full rationale.
/// </summary>
Task<OcoExitOrderResult?> PlaceOcoExitOrderAsync(OcoExitOrderRequest request);
Task<Order?> GetOrderAsync(string orderId);
Task<IReadOnlyList<Order>> GetOrdersAsync();
Task<bool> CancelOrderAsync(string orderId);
// --- Activities / Fills ---
Task<IReadOnlyList<object>> GetActivitiesAsync();
// --- Order lifecycle stream ---
/// <summary>
/// Raised whenever the broker observes an order state change — placed,
/// accepted, partially filled, filled, canceled, rejected, expired,
/// replaced. Brokers with a native push stream raise these directly;
/// brokers without one are wrapped by a polling source that synthesizes
/// the same events. Subscribe in OnAgentBoot.
/// </summary>
event EventHandler<OrderUpdate>? OrderUpdated;
/// <summary>True if this broker raises OrderUpdated from a native push
/// stream rather than a polling diff.</summary>
bool SupportsOrderStreaming { get; }
/// <summary>Suggested polling cadence when this broker is wrapped by
/// the polling fallback. Tuned per broker against rate limits.</summary>
TimeSpan OrderPollingInterval { get; }
// --- Trading session bounds (US Eastern) ---
/// <summary>
/// Earliest time of day this broker accepts orders for execution.
/// Defaults vary per broker — Alpaca/IBKR/Paper use 04:00 ET; Schwab
/// uses 07:00 ET; TradeStation uses 06:00 ET; E*TRADE uses 07:00 ET.
/// Strategies should clamp their entry window to this bound rather
/// than submit orders the broker will reject outright.
/// </summary>
TimeSpan EarliestEntryEt { get; }
/// <summary>
/// Latest time of day this broker accepts orders for the current
/// session. Default 20:00 ET (end of standard US after-hours).
/// </summary>
TimeSpan LatestEntryEt { get; }
/// <summary>
/// True if this broker accepts orders flagged for execution outside
/// regular hours (OrderRequest.ExtendedHours=true). Tastytrade returns
/// false for equities; everyone else returns true.
/// </summary>
bool SupportsExtendedHoursOrders { get; }
}
BrokerBase
The abstract base class every concrete IBroker inherits from. You'll rarely need to interact with BrokerBase directly — strategies always go through the IBroker interface — but it's worth knowing about because it owns the PlaceOrderAsync entry point that raises the LocalSubmission OrderUpdated event. Concrete brokers override the protected SubmitOrderToBrokerAsync hook and call RaiseOrderUpdated from their native streams when fills arrive.
/// <summary>
/// Base class that every IBroker implementation inherits from. It owns
/// the public PlaceOrderAsync entry point — strategies still call
/// _broker.PlaceOrderAsync exactly as before — and wraps it so the
/// optimistic LocalSubmission OrderUpdated event always fires after the
/// order is submitted, regardless of which broker handled it. Concrete
/// brokers implement the protected SubmitOrderToBrokerAsync hook and
/// call RaiseOrderUpdated from their native streams when fills arrive.
/// <para>
/// Strategies rarely interact with BrokerBase directly — but knowing
/// about it explains why your OnOrderUpdated subscriber sees a
/// Source=LocalSubmission event immediately after PlaceOrderAsync
/// returns, even before the broker has acknowledged the order.
/// </para>
/// </summary>
public abstract class BrokerBase : IBroker
{
public abstract BrokerClient Client { get; }
public abstract Task<AccountInfo> GetAccountInfoAsync();
public abstract Task<decimal> GetCashBalanceAsync();
public abstract Task<decimal> GetBuyingPowerAsync();
public abstract Task<IReadOnlyList<Position>> GetPositionsAsync();
public abstract Task<Position?> GetPositionAsync(string symbol);
public abstract Task<Order?> GetOrderAsync(string orderId);
public abstract Task<IReadOnlyList<Order>> GetOrdersAsync();
public abstract Task<bool> CancelOrderAsync(string orderId);
public abstract Task<IReadOnlyList<object>> GetActivitiesAsync();
public event EventHandler<OrderUpdate>? OrderUpdated;
/// <summary>Override and return true when the broker has a native push stream wired up.</summary>
public virtual bool SupportsOrderStreaming => false;
// --- Default session bounds (overridden per broker) ---
/// <summary>Default 04:00 ET. Schwab overrides to 07:00, TradeStation to 06:00, E*TRADE to 07:00.</summary>
public virtual TimeSpan EarliestEntryEt => new TimeSpan(4, 0, 0);
/// <summary>Default 20:00 ET — end of standard after-hours window.</summary>
public virtual TimeSpan LatestEntryEt => new TimeSpan(20, 0, 0);
/// <summary>Default true. Tastytrade overrides to false for equities.</summary>
public virtual bool SupportsExtendedHoursOrders => true;
/// <summary>Default 5s. Per-broker overrides tune against rate limits.</summary>
public virtual TimeSpan OrderPollingInterval => TimeSpan.FromSeconds(5);
/// <summary>
/// Public entry point strategies call. Submits the order via the
/// concrete broker's implementation and immediately raises a
/// LocalSubmission OrderUpdated event so the OrderHistoryRecorder
/// (and any strategy subscriber) writes the initial row before any
/// fill arrives.
/// </summary>
public async Task<Order> PlaceOrderAsync(OrderRequest request)
{
var order = await SubmitOrderToBrokerAsync(request);
// Skip the optimistic LocalSubmission event if the order is ALREADY
// terminal — some brokers (PaperBroker) fill market orders synchronously
// inside SubmitOrderToBrokerAsync and have already raised the authoritative
// fill event. Re-announcing here would emit a phantom "Filled, 0 shares"
// update (BuildSubmissionUpdate hardcodes CumulativeFilledQuantity=0) that
// lands AFTER the real fill and clobbers consumers latching on Filled.
if (order.Status is not (OrderStatus.Filled or OrderStatus.Canceled
or OrderStatus.Rejected or OrderStatus.Expired))
{
RaiseOrderUpdated(BuildSubmissionUpdate(request, order));
}
return order;
}
/// <summary>Concrete brokers override this with their native order-submission logic.</summary>
protected abstract Task<Order> SubmitOrderToBrokerAsync(OrderRequest request);
/// <summary>
/// OCO entry point. Default returns null = "broker doesn't support OCO"
/// — strategy code should fall back to a stop-only exit. Brokers that
/// support OCO override SubmitOcoExitOrderToBrokerAsync.
/// </summary>
public virtual Task<OcoExitOrderResult?> PlaceOcoExitOrderAsync(OcoExitOrderRequest request)
=> SubmitOcoExitOrderToBrokerAsync(request);
protected virtual Task<OcoExitOrderResult?> SubmitOcoExitOrderToBrokerAsync(OcoExitOrderRequest request)
=> Task.FromResult<OcoExitOrderResult?>(null);
/// <summary>
/// Publish an order lifecycle event. Called by the base class itself
/// (LocalSubmission), by concrete brokers from their native streaming
/// callbacks (Stream), and by the polling fallback (Poll). Strategies
/// should never call this — subscribe to OrderUpdated instead.
/// </summary>
public void RaiseOrderUpdated(OrderUpdate update)
=> OrderUpdated?.Invoke(this, update);
}
IData
The real-time market data service available via _data. Access candle history and indicator values through dictionaries keyed by (Symbol, Interval) and (Symbol, IndicatorName). Subscribe to event handlers in OnAgentBoot for real-time updates. The SnapshotRefresh event uses AsyncEventHandler so the host can await your handler and catch exceptions; the high-frequency Quote/Trade/Candle events use plain EventHandler to avoid backpressure. IData also exposes the multi-asset and on-demand surface: ResolveInstrument (asset class / multiplier / session / contract detail), GetOptionChainAsync, Level-2 depth (SubscribeDepth / DepthUpdate / GetOrderBook), and on-demand GetHistoricalBarsAsync / GetFundamentalsAsync — each covered in its own section below.
/// <summary>
/// Real-time market data service. Access via _data in your strategy.
/// Candles and Indicators are dictionaries keyed by (Symbol, Interval/Name).
/// Subscribe to event handlers in OnAgentBoot for real-time updates.
/// </summary>
public interface IData
{
/// <summary>
/// Historical and live candle data, keyed by (Symbol, Interval).
/// List is ordered oldest-first; most recent candle is at index Count-1.
/// Example: var c = _data.Candles[("AAPL", Interval.OneMinute)];
/// </summary>
public Dictionary<(string Symbol, Interval Interval), List<Candles>> Candles { get; set; }
/// <summary>
/// Computed indicator values, keyed by (Symbol, IndicatorName).
/// IndicatorName is the name you gave the indicator in its profile —
/// NOT the indicator class name. Example: a profile with two EMAs
/// named "EMA9" and "EMA21" produces two entries here.
/// Cast each row to the specific type:
/// var rows = _data.Indicators[("AAPL", "EMA9")];
/// var lastEma = ((EmaRow)rows[rows.Count - 1]).Ema;
/// </summary>
public Dictionary<(string Symbol, string Indicator), List<IBaseRow>> Indicators { get; set; }
/// <summary>Daily snapshot with fundamentals, splits, dividends, and per-symbol overviews.</summary>
public SnapshotData Snapshot { get; set; }
// --- Real-time event handlers ---
// High-frequency events use plain EventHandler so the host can fire
// them synchronously without backpressure. SnapshotRefresh uses
// AsyncEventHandler so the host awaits your handler and catches any
// thrown exception (snapshots fire rarely — once per day — so the
// perf tradeoff is worth it).
/// <summary>Fires when a new candle closes or an existing one updates.</summary>
public EventHandler<(string Symbol, Interval Interval)>? CandleUpdate { get; set; }
/// <summary>Fires when indicator values are recalculated for a symbol.</summary>
public EventHandler<(string Symbol, string Indicator)>? IndicatorUpdate { get; set; }
/// <summary>Fires on each real-time NBBO quote (bid/ask) update.</summary>
public EventHandler<Quote>? QuoteUpdate { get; set; }
/// <summary>Fires on each real-time trade tick.</summary>
public EventHandler<Trade>? TradeUpdate { get; set; }
/// <summary>
/// Fires when a news article reaches your filter. Default behavior is
/// the FIRESHOSE — every article streamed from the provider. Call
/// SetNewsFilter to narrow.
/// </summary>
public EventHandler<NewsArticle>? NewsUpdate { get; set; }
/// <summary>
/// Fires when a structured MarketEvent is detected (SEC/FINRA catalysts +
/// the platform's derived signals). Typed — NOT flattened into news. Full
/// firehose by default; call SetMarketEventFilter to narrow. See the Market
/// Events section.
/// </summary>
public EventHandler<MarketEvent>? MarketEventUpdate { get; set; }
/// <summary>
/// Fires when the daily snapshot rolls over. Async so the host awaits
/// your handler — safe to call broker / data methods here.
/// </summary>
public AsyncEventHandler<SnapshotData>? SnapshotRefresh { get; set; }
/// <summary>
/// Configures which news articles reach NewsUpdate. See the News
/// Filter section for full semantics.
/// </summary>
public Task SetNewsFilter(List<string> watchlist, NewsScope scope = NewsScope.All);
/// <summary>
/// Narrows MarketEventUpdate to the given symbols (default = firehose).
/// Market-wide events with no Symbol always pass. See the Market Events section.
/// </summary>
public Task SetMarketEventFilter(List<string> symbols);
// --- Multi-asset & on-demand pulls (default-implemented; the live/backtest host wires them) ---
/// <summary>Fires on each Level-2 order-book update for symbols opted in via
/// SubscribeDepth. Crypto venues only (Kraken, Coinbase). See the Market Depth section.</summary>
public EventHandler<OrderBook>? DepthUpdate { get; set; }
/// <summary>Resolves a symbol's instrument metadata — asset class, contract multiplier,
/// trading session, and contract detail (strike/expiry/right, base/quote ccy). Lets one
/// strategy branch per class when trading mixed symbols. See the Instruments section.</summary>
public InstrumentInfo ResolveInstrument(string symbol);
/// <summary>Fetches the option chain for an underlying on demand (first option-capable
/// provider wins; Schwab includes greeks/IV/OI). Null = no provider serves options.
/// See the Option Chains section.</summary>
public Task<OptionChain?> GetOptionChainAsync(string underlyingSymbol,
DateTime? from = null, DateTime? to = null, string? contractType = null,
CancellationToken ct = default);
/// <summary>Opt in to Level-2 order-book streaming for the given symbols (OFF by default).
/// After this, DepthUpdate fires and GetOrderBook returns the live book. See Market Depth.</summary>
public Task SubscribeDepth(List<string> symbols);
/// <summary>The latest Level-2 order book for a symbol, or null if depth isn't subscribed
/// or the provider has no book feed. Pull-style alternative to the DepthUpdate event.</summary>
public OrderBook? GetOrderBook(string symbol);
/// <summary>Fetches historical OHLC candles on demand for any symbol/interval/range —
/// e.g. to warm a long look-back indicator at [Initialize]. See the On-Demand Data section.</summary>
public Task<List<Candles>> GetHistoricalBarsAsync(string symbol, Interval interval,
DateTime from, DateTime to, CancellationToken ct = default);
/// <summary>Fetches the latest computed fundamentals for a symbol on demand (P/E, margins,
/// market cap, dividend, 52-week range, …) beyond the once-daily snapshot. See On-Demand Data.</summary>
public Task<Fundamental?> GetFundamentalsAsync(string symbol, CancellationToken ct = default);
}
/// <summary>
/// Task-returning equivalent of EventHandler{T}. Used for low-frequency
/// events (snapshot refresh, lifecycle) where the agent host awaits the
/// handler so any thrown exception is catchable rather than escaping
/// into the process unhandled-exception path. Hot-path events
/// (Quote/Trade/Candle/...) stay on EventHandler{T} to avoid backpressure.
/// </summary>
public delegate Task AsyncEventHandler<T>(object? sender, T e);
IAgent
The agent control service available via _agent. Manage the symbol watchlist at runtime (Add / Drop / Set), send messages to other agents for coordinated multi-agent strategies, and configure which agents are allowed to send messages to this one via AllowedSenders. Inbound messages — from other agents AND from external webhooks — arrive on the Message event as an Envelope; see the Messaging & Webhooks section for the payload shape.
/// <summary>
/// Agent control service. Access via _agent in your strategy.
/// Manage your symbol watchlist dynamically and communicate between agents.
/// </summary>
public interface IAgent
{
/// <summary>Remove a symbol from this agent's watchlist.
/// Cleans up candles, indicators, and broker subscriptions.</summary>
public Task DropSymbol(string symbol);
/// <summary>Add a symbol to this agent's watchlist.
/// Loads historical candles and initializes indicators for the new symbol.</summary>
public Task AddSymbol(string symbol);
/// <summary>Replace the entire watchlist with a new set of symbols.
/// Drops the removed symbols and adds the new ones in one batch.</summary>
public Task SetSymbols(List<string> newSymbols);
/// <summary>
/// Send a message to one or more agents. Useful for coordinated
/// multi-agent strategies (e.g. a screening agent that publishes hot
/// symbols to execution agents). The payload can be a string (sent
/// verbatim as raw text) or ANY object (serialized to JSON by the
/// platform before sending — you don't serialize it yourself). The
/// receiver gets it as a string on Envelope.Message; they call
/// Envelope.Read<T>() to deserialize an object payload. The targets
/// must list this agent in their AllowedSenders.
/// </summary>
public Task Transmit(List<AgentAuth> agents, object message);
/// <summary>
/// Agents allowed to send messages TO this agent. Empty (default) =
/// no agent messages accepted. Populate this from your strategy's
/// [Initialize] method so the messaging hub picks it up before
/// connecting. (Does not affect inbound webhook messages.)
/// </summary>
public List<AgentAuth> AllowedSenders { get; set; }
/// <summary>Event raised when the agent's running state changes (started/stopped/paused).</summary>
public EventHandler<bool>? IsRunning { get; set; }
/// <summary>
/// Raised when an inbound message arrives — from another agent
/// (Envelope.Source == MessageSource.Agent) OR from an external
/// webhook POSTed to this agent (MessageSource.Webhook). The Envelope
/// carries the server-stamped source, sender identity, id, and
/// timestamp; envelope.Message is the raw payload. See the
/// Messaging & Webhooks section.
/// </summary>
public EventHandler<Envelope>? Message { get; set; }
}
/// <summary>Credentials for targeting an agent in inter-agent messaging.</summary>
public class AgentAuth
{
public string AgentName { get; set; }
public string AccessKey { get; set; }
}
Messaging & Webhooks
Every inbound message — whether transmitted by another agent or POSTed by an external system to your agent's webhook — is delivered to _agent.Message as an Envelope. The Envelope wraps the raw payload with server-stamped metadata you can trust: Source (Agent vs Webhook, set authoritatively by the platform, NOT by the sender), Sender identity, the sending account's Username, a MessageId, and a Timestamp. Use envelope.Read<T>() to deserialize a JSON payload into a typed model. To SEND, call _agent.Transmit(targets, payload) — the payload can be a string (sent verbatim) or any object (serialized to JSON for you). Webhook senders have empty Sender fields, so always check Source first.
/// <summary>
/// Where an inbound message originated. Server-stamped and authoritative:
/// Agent is set by the messaging hub when another agent transmits; Webhook
/// is set by the webhook controller when an external HTTP POST is routed to
/// this agent. A strategy can TRUST this to distinguish the two — unlike
/// anything embedded in the message body, which the sender controls.
/// </summary>
public enum MessageSource
{
Agent,
Webhook
}
/// <summary>
/// An inbound message delivered to a strategy via _agent.Message. Wraps the
/// raw payload with server-stamped metadata the strategy can trust (source,
/// sender identity, id, timestamp).
/// </summary>
public class Envelope
{
/// <summary>Authoritative, server-stamped origin of this message.</summary>
public MessageSource Source { get; set; }
/// <summary>Identity of the sending agent (reuses AgentAuth). Both
/// fields are empty for webhook messages — check Source first.</summary>
public AgentAuth Sender { get; set; } = new AgentAuth();
/// <summary>
/// Authoritative username of the account that SENT this message — works
/// across users. For agent messages it's stamped from the sender's
/// authenticated JWT (cannot be spoofed); for webhooks, from the account
/// that owns the webhook credentials. Empty if it couldn't be resolved.
/// </summary>
public string Username { get; set; } = "";
/// <summary>The raw payload as supplied by the sender. Often a JSON
/// blob — see Read<T>().</summary>
public string Message { get; set; } = "";
/// <summary>Unique id assigned by whoever routed the message
/// (messaging hub, webhook controller, or the local in-process bus).</summary>
public string MessageId { get; set; } = "";
/// <summary>When the message was routed (UTC).</summary>
public DateTimeOffset Timestamp { get; set; }
/// <summary>
/// Deserialize Message into T using System.Text.Json (case-insensitive).
/// Throws on malformed JSON — wrap in try/catch if the payload format
/// isn't guaranteed (raw-text messages, or webhooks that aren't JSON).
/// </summary>
public T Read<T>() => JsonSerializer.Deserialize<T>(Message)!;
}
// ============================================================
// RECEIVING messages (agent + webhook share one handler)
// ============================================================
//
// [Initialize]
// public async Task OnAgentBoot()
// {
// _agent.Message += OnAgentMessage;
//
// // Only needed for AGENT-to-agent messages — list who may send to
// // you. Webhook delivery is authorized by the webhook's own
// // credentials and is NOT gated by AllowedSenders.
// _agent.AllowedSenders = new List<AgentAuth>
// {
// new AgentAuth { AgentName = "Screener", AccessKey = "...key..." }
// };
// }
//
// private void OnAgentMessage(object? sender, Envelope e)
// {
// switch (e.Source)
// {
// case MessageSource.Agent:
// // Trusted peer agent. e.Sender / e.Username identify it.
// var pick = e.Read<SymbolPick>(); // typed JSON payload
// _ = _agent.AddSymbol(pick.Symbol);
// break;
//
// case MessageSource.Webhook:
// // External system (e.g. TradingView alert, a SEC-event
// // webhook). e.Sender is empty — trust only e.Source.
// try
// {
// var alert = e.Read<MyWebhookPayload>();
// _logger.LogInformation("Webhook {Id}: {Sym} {Action}",
// e.MessageId, alert.Symbol, alert.Action);
// }
// catch (JsonException)
// {
// // Not JSON — handle as raw text.
// _logger.LogInformation("Webhook raw: {Body}", e.Message);
// }
// break;
// }
// }
//
// ============================================================
// SENDING messages to other agents
// ============================================================
//
// // Object payload — serialized to JSON for you. The receiver calls
// // envelope.Read<SymbolPick>() to get it back.
// await _agent.Transmit(
// agents: new List<AgentAuth> {
// new AgentAuth { AgentName = "Executor", AccessKey = "...key..." }
// },
// message: new SymbolPick { Symbol = "NVDA", Score = 0.92m });
//
// // String payload — sent verbatim as raw text.
// await _agent.Transmit(targets, "rebalance-now");
IStorage
Persistent key-value storage available via _store. Save and retrieve state between sessions without external databases. Values are JSON-serialized and stored per-agent in ByteTrader's local SQLite database. Storage operations are serialized through a process-wide gate and retry on transient SQLite busy errors — safe to call from any thread including event handlers.
/// <summary>
/// Persistent key-value storage for agent state. Access via _store.
/// Values survive between sessions and agent restarts.
/// Use for tracking positions, cooldowns, P&L baselines, configuration —
/// any state your strategy needs to persist without an external database.
/// <para>
/// Implementation details (you don't need these to use it, but they may
/// matter for performance or troubleshooting):
/// — Backed by SQLite. Operations serialize through a process-wide gate,
/// so concurrent calls from different threads (or different agents on
/// the same dashboard) won't collide.
/// — Operations retry with exponential backoff if a sibling service
/// holds the writer lock (typically the nightly snapshot batch).
/// — Values are JSON-serialized. Use simple POCOs or records for
/// complex state; built-in primitives (decimal, int, DateTime, etc.)
/// work directly.
/// </para>
/// </summary>
public interface IStorage
{
/// <summary>Store a value by key. Accepts any JSON-serializable type.</summary>
public Task StoreValue(string key, dynamic val);
/// <summary>Read a value by key, deserialized to the specified type.
/// Returns default(T) if the key doesn't exist.</summary>
public Task<T> ReadValue<T>(string key);
/// <summary>Delete a stored value by key. No-op if the key doesn't exist.</summary>
public Task DeleteValue(string key);
}
// Example usage in your strategy:
//
// // Persist a baseline at session start
// await _store.StoreValue("dayStartEquity", account.Equity);
//
// // Read it back later in the day
// var baseline = await _store.ReadValue<decimal>("dayStartEquity");
//
// // Persist a complex object
// await _store.StoreValue("positions", new Dictionary<string, decimal> {
// ["AAPL"] = 100m,
// ["TSLA"] = 50m
// });
OrderRequest, Order & Enums
Types for placing and tracking orders. Submit an OrderRequest via IBroker.PlaceOrderAsync() to place a new order. The returned Order record represents the live order with its current status. Side and Type are strings in the request for portability across brokers; the Order record uses the strongly-typed OrderSide and OrderType enums.
public enum OrderSide
{
Buy,
Sell
}
public enum OrderType
{
Market, // Execute immediately at current market price
Limit, // Execute at specified price or better
Stop, // Trigger a market order when stop price is hit
StopLimit, // Trigger a limit order when stop price is hit
TrailingStop // Stop price trails the market by a fixed amount/percent
}
public enum OrderStatus
{
New, // Order submitted but not yet acknowledged
Accepted, // Broker accepted the order
PartiallyFilled, // Some shares filled, remainder still working
Filled, // Order completely filled
Canceled, // Order was canceled (explicit user/system request)
Rejected, // Broker rejected the order
Expired, // Order's time-in-force elapsed — Day-TIF at 16:00 ET,
// GTC after 90 days on Alpaca, etc. Distinct from Canceled.
Pending, // Order is queued (broker-specific intermediate state)
Unknown
}
/// <summary>
/// Submit this to IBroker.PlaceOrderAsync() to place a new order.
/// Side and Type are strings (not enums) so strategies can write
/// "Buy"/"Market" etc. without importing the enum types.
/// </summary>
public record OrderRequest(
string Symbol,
decimal Quantity,
string Side, // "Buy" or "Sell"
string Type, // "Market", "Limit", "Stop", "StopLimit", "TrailingStop"
decimal? LimitPrice = null,
decimal? StopPrice = null,
string TimeInForce = "Day", // "Day", "GTC", "IOC", "FOK", "OPG", "CLS"
/// <summary>
/// Set true when submitting in pre-market (04:00–09:30 ET) or
/// after-hours (16:00–20:00 ET). Each broker translates this flag
/// to its native API field (Alpaca: extended_hours boolean, Schwab:
/// session=SEAMLESS, IBKR: outsideRTH, E*TRADE: marketSession=EXTENDED,
/// TradeStation: Duration=DAY+/GTC+). Order TYPE must be "Limit"
/// when this is true — every broker rejects market/stop orders
/// outside regular hours.
/// </summary>
bool ExtendedHours = false,
/// <summary>
/// For Type="TrailingStop" only — absolute dollar amount the stop
/// trails the favorable market move by. Mutually exclusive with
/// TrailingPercent; supply exactly one. Ignored for other order types.
/// Example: on a long position, TrailingPrice=0.50 keeps the stop
/// $0.50 below the highest price observed since order placement.
/// </summary>
decimal? TrailingPrice = null,
/// <summary>
/// For Type="TrailingStop" only — percentage (as a decimal, e.g.
/// 0.02 = 2%) the stop trails the favorable market move by.
/// Mutually exclusive with TrailingPrice; supply exactly one.
/// </summary>
decimal? TrailingPercent = null
);
/// <summary>Represents an order returned by the broker (live or historical).</summary>
public record Order(
string OrderId,
string Symbol,
OrderSide Side,
OrderType Type,
decimal Quantity,
decimal? TargetPrice, // Limit / take-profit price
decimal? StopPrice,
decimal? TrailingPrice, // Trailing-stop offset in $
decimal? TrailingPercent, // Trailing-stop offset in %
OrderStatus Status,
DateTime CreatedAt
);
/// <summary>Response from an order submission (legacy — most paths now use Order/OrderUpdate).</summary>
public class OrderResponse
{
public OrderStatus Status { get; set; }
public DateTime Timestamp { get; set; }
public bool FillCompleted { get; set; }
}
/// <summary>Internal order routing model with additional execution parameters.</summary>
public class TradeOrder
{
public string? OrderId { get; set; }
public string Ticker { get; set; }
public OrderSide OrderSide { get; set; }
public OrderType OrderType { get; set; }
public int Quantity { get; set; }
public decimal? TargetPrice { get; set; }
public decimal? StopPrice { get; set; }
public decimal? TrailingPrice { get; set; }
public decimal? TrailingPercent { get; set; }
public TimeSpan? OrderExpiration { get; set; }
public string? ReferenceId { get; set; }
}
OCO Exit Orders
One-Cancels-Other order pairs for exiting open positions. Use these instead of submitting a stop sell and a limit sell as separate orders — those would both try to reserve the full position quantity, and the second one would be rejected by the broker with insufficient-qty errors. Alpaca (stocks), Schwab, TradeStation, tastytrade and the built-in Paper broker place native OCO pairs, and IBKR sends an OCA group (not yet confirmed with IBKR). E*TRADE, Coinbase and Kraken return null from PlaceOcoExitOrderAsync to signal "not supported", in which case strategies should fall back to placing the stop alone (forgoing the auto-target) or use bracket orders on entry.
/// <summary>
/// Submit a One-Cancels-Other exit pair for an open position. Stop +
/// target are linked at the broker so whichever fills first auto-cancels
/// the other.
/// <para>
/// Why OCO matters: submitting a stop sell AND a limit sell as TWO
/// separate orders both try to reserve the full position quantity, and
/// the second one gets rejected with "insufficient qty available for
/// order". OCO solves this by reserving the quantity ONCE for the pair.
/// </para>
/// <para>
/// Side is always "Sell" for long-position exits. The broker rounds
/// LimitPrice and StopPrice to its accepted tick increment ($0.01 for
/// stocks ≥ $1.00, $0.0001 below) so strategies don't need to round in
/// their ATR-based pricing math.
/// </para>
/// </summary>
public record OcoExitOrderRequest(
string Symbol,
decimal Quantity,
string Side, // "Sell" for long-position exits
decimal LimitPrice, // take-profit / target
decimal StopPrice, // stop-loss
string TimeInForce = "Day"
);
/// <summary>
/// Result of a successful OCO submission — both leg IDs so the caller
/// can wire them into its position tracking and recognize fills via
/// the OrderUpdated stream. TargetOrderId is the limit (take-profit)
/// leg; StopOrderId is the stop-loss leg.
/// </summary>
public record OcoExitOrderResult(
string TargetOrderId,
string StopOrderId
);
// Example usage in your strategy:
//
// var oco = await _broker.PlaceOcoExitOrderAsync(new OcoExitOrderRequest(
// Symbol: "HIMX",
// Quantity: 267m,
// Side: "Sell",
// LimitPrice: 21.42m, // target
// StopPrice: 21.20m // stop
// ));
//
// if (oco != null)
// {
// _logger.LogInformation("OCO placed: stopId={S} targetId={T}",
// oco.StopOrderId, oco.TargetOrderId);
// }
// else
// {
// // Broker doesn't support OCO — fall back to a stop-only exit
// // and let the watchdog handle the upside via a trailing stop.
// }
//
// Broker support matrix:
// Alpaca → ✓ stocks (native OCO)
// Schwab → ✓ stocks and options
// TradeStation → ✓ stocks, options, futures
// Tastytrade → ✓ stocks, options, futures
// Paper → ✓
// IBKR → sent as an OCA group; not yet confirmed with IBKR
// E*TRADE, Coinbase, Kraken → no OCO, returns null
Order Lifecycle Stream
The OrderUpdated event on IBroker fires for every order state transition: submitted, accepted, partially filled, filled, canceled, rejected, expired. Subscribe in your OnAgentBoot to drive your position state machine. The OrderUpdate record carries the source (LocalSubmission, Stream, Poll) so consumers can distinguish the optimistic write at submission time from a real broker-side confirmation. Out-of-order events are possible — compare EventTimestamp against the last applied timestamp for the same OrderId before mutating state. Terminal states are Filled, Canceled, Rejected, and Expired. Canceled and Expired are intentionally distinct: Canceled means an explicit cancel request (user, system, parent OCO leg), while Expired means the broker terminated the order because its time-in-force ran out (Day-TIF stop at 16:00 ET, GTC after 90 days on Alpaca, etc.). Strategies that need to detect when the broker silently drops a stop or working order — most commonly when carrying a position into extended hours — should check for both Canceled and Expired so the same logic works across all brokers.
/// <summary>
/// Where an OrderUpdate originated. Lets subscribers distinguish
/// between the optimistic write at submission time and a confirmation
/// from a real broker event source.
/// </summary>
public enum OrderUpdateSource
{
/// <summary>Synthesized at PlaceOrderAsync return — the "we just submitted it" event.</summary>
LocalSubmission,
/// <summary>Pushed by a broker streaming client (Alpaca trade updates, Schwab ACCT_ACTIVITY, etc.).</summary>
Stream,
/// <summary>Synthesized by a polling fallback diffing GetOrdersAsync output against a snapshot.</summary>
Poll
}
/// <summary>
/// Unified order lifecycle event raised by every IBroker. Concrete
/// brokers produce these from their native event stream (preferred)
/// or via a polling fallback. Consumers subscribe to a single shape
/// regardless of which broker is active.
/// <para>
/// Out-of-order events are possible during heavy fills — compare
/// EventTimestamp against the last applied timestamp for the same
/// OrderId before mutating state.
/// </para>
/// </summary>
public record OrderUpdate(
string OrderId,
string Symbol,
OrderStatus Status,
OrderSide Side,
OrderType OrderType,
string TimeInForce,
decimal RequestedQuantity,
decimal CumulativeFilledQuantity,
decimal LeavesQuantity,
decimal? AvgFillPrice,
decimal? LastFillPrice,
decimal? LastFillQuantity,
decimal? LimitPrice,
decimal? StopPrice,
DateTime EventTimestamp,
string? RejectReason = null,
OrderUpdateSource Source = OrderUpdateSource.Stream,
// Realized P&L for the closing/reducing portion of THIS fill, when the
// producing broker can compute it cheaply at the fill site (paper and
// backtest do — they run fills through average-cost math). NULL for brokers
// whose stream/poll carries no P&L (Alpaca, Schwab, IBKR, …) — for those the
// OrderHistoryRecorder derives realized P&L from its own per-symbol
// average-cost ledger. RealizedPnlPercent is a true percent (5.0 == +5%).
decimal? RealizedPnl = null,
decimal? RealizedPnlPercent = null
);
// Example usage in your strategy:
//
// protected override async Task OnAgentBoot()
// {
// _broker.OrderUpdated += OnOrderUpdated;
// // ... other subscriptions ...
// }
//
// private void OnOrderUpdated(object? sender, OrderUpdate u)
// {
// switch (u.Status)
// {
// case OrderStatus.Filled:
// _logger.LogInformation(
// "{Symbol} filled qty={Qty} @ {Avg} (source={Src})",
// u.Symbol, u.CumulativeFilledQuantity, u.AvgFillPrice, u.Source);
// // Drive your position state machine here
// break;
// case OrderStatus.Rejected:
// _logger.LogWarning("{Symbol} rejected: {Reason}",
// u.Symbol, u.RejectReason);
// break;
// case OrderStatus.Canceled:
// case OrderStatus.Expired:
// // Both are terminal — the broker is no longer holding this
// // order. For a stop-loss order that disappears mid-trade
// // (e.g. Day-TIF stop auto-cancelled at 16:00 ET while the
// // position carried into extended hours), clear your local
// // tracking and consider activating a simulated-stop watchdog
// // so you don't sit unguarded.
// _logger.LogInformation(
// "{Symbol} {Status} orderId={Id} — broker dropped this order",
// u.Symbol, u.Status, u.OrderId);
// break;
// }
// }
Multi-Leg & Spread Orders
Submit a spread (vertical, calendar, covered call, …) as ONE combo priced at the net level via _broker.PlaceMultiLegOrderAsync. Each OrderLeg names a canonical OCC contract (or an equity ticker for covered legs) plus a LegAction (BuyToOpen / SellToOpen / BuyToClose / SellToClose) and a per-combo Ratio. MultiLegOrderRequest.Quantity is the number of combos; NetLimitPrice is null for market, positive for a net debit you pay, negative for a net credit you receive — translated to each broker's debit/credit convention at the edge. PlaceMultiLegOrderAsync returns null when the connected broker doesn't support multi-leg orders, so check for null rather than legging in silently. Legs of one combo share a LegGroupId on the OrderUpdated stream so you can group their fills back into the spread.
/// <summary>Per-leg open/close intent for a spread.</summary>
public enum LegAction { BuyToOpen, BuyToClose, SellToOpen, SellToClose }
/// <summary>One leg of a spread. Symbol is a canonical OCC contract (or an equity
/// ticker for covered legs). Ratio is the per-combo contract count — a 1x2 ratio
/// spread uses Ratio 1 and 2; total leg quantity is Ratio x combo Quantity.</summary>
public record OrderLeg(string Symbol, LegAction Action, int Ratio = 1);
/// <summary>A multi-leg (spread) order priced at the combo level. Quantity is the
/// number of COMBOS. NetLimitPrice: null = market; positive = net debit you pay;
/// negative = net credit you receive.</summary>
public record MultiLegOrderRequest(
IReadOnlyList<OrderLeg> Legs,
decimal Quantity,
decimal? NetLimitPrice,
string TimeInForce = "Day");
/// <summary>The combo id plus per-leg ids where the broker exposes them.</summary>
public record MultiLegOrderResult(string ComboOrderId, IReadOnlyList<string> LegOrderIds);
// IBroker.PlaceMultiLegOrderAsync(request) returns null when the broker can't do spreads.
// Example — open a bull call spread (buy the lower strike, sell the higher):
//
// var legs = new List<OrderLeg>
// {
// new OrderLeg(longCall.Symbol, LegAction.BuyToOpen),
// new OrderLeg(shortCall.Symbol, LegAction.SellToOpen)
// };
// var combo = await _broker.PlaceMultiLegOrderAsync(
// new MultiLegOrderRequest(legs, Quantity: 1, NetLimitPrice: null)); // market
// if (combo == null)
// _logger.LogWarning("This broker doesn't support multi-leg orders");
Extended Hours Trading
Strategies can opt into pre-market (04:00–09:30 ET) and after-hours (16:00–20:00 ET) trading by setting OrderRequest.ExtendedHours=true. Each broker translates this cross-broker flag to its native API field. IBroker exposes EarliestEntryEt and LatestEntryEt (in US Eastern) so the strategy can clamp its entry window to whatever the connected broker accepts — Schwab's pre-market doesn't open until 07:00 ET, TradeStation's starts at 06:00 ET, Alpaca and IBKR honor the full 04:00 ET window. Brokers that don't support extended-hours orders at all (e.g. Tastytrade for equities) return SupportsExtendedHoursOrders=false. All extended-hours orders must be limit orders — market and stop orders are rejected by every broker outside regular hours.
// Strategies opt into pre-market and after-hours trading by:
// 1. Calling _broker.EarliestEntryEt / .LatestEntryEt to check the
// window THIS broker accepts. Pre-market start varies:
// Alpaca / IBKR / Paper → 04:00 ET
// TradeStation → 06:00 ET
// Schwab / E*TRADE → 07:00 ET
// Tastytrade (equities) → not supported (SupportsExtendedHoursOrders=false)
// 2. Setting OrderRequest.ExtendedHours = true on every order
// submitted outside regular hours.
// 3. Using ONLY limit orders outside regular hours. Market and stop
// orders are rejected by every broker in extended hours.
//
// Each broker translates the cross-broker ExtendedHours flag to its
// native API field:
//
// Alpaca → extended_hours: true (boolean)
// Schwab → session: "SEAMLESS" (enum: NORMAL|AM|PM|SEAMLESS)
// IBKR → outsideRTH: true (boolean)
// E*TRADE → marketSession: "EXTENDED" (enum: REGULAR|EXTENDED)
// TradeStation → Duration: "DAY+" / "GTC+" (suffix on duration)
// Paper → limit orders only; fills follow the symbol's session
// Tastytrade → rejects — SupportsExtendedHoursOrders=false
//
// Example: time-aware order placement that adapts to whichever broker
// the agent is configured against.
private async Task PlaceTimeAwareEntry(string symbol, decimal qty, decimal limitPrice)
{
var now = TimeZoneInfo.ConvertTimeFromUtc(
DateTime.UtcNow,
TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"));
var tEt = now.TimeOfDay;
// Broker bounds — clamp to whatever this broker actually accepts.
if (tEt < _broker.EarliestEntryEt || tEt > _broker.LatestEntryEt)
{
_logger.LogInformation("Outside {Broker} entry window ({Start}–{End} ET)",
_broker.Client, _broker.EarliestEntryEt, _broker.LatestEntryEt);
return;
}
// Determine if we're outside the regular session 09:30–16:00 ET.
var regularStart = new TimeSpan(9, 30, 0);
var regularEnd = new TimeSpan(16, 0, 0);
bool isExtendedHours = tEt < regularStart || tEt >= regularEnd;
if (isExtendedHours && !_broker.SupportsExtendedHoursOrders)
{
_logger.LogInformation("{Broker} doesn't support extended-hours equity orders",
_broker.Client);
return;
}
// In extended hours, force a Limit order (market/stop are rejected).
var orderType = isExtendedHours ? "Limit" : "Market";
var lp = isExtendedHours ? (decimal?)limitPrice : null;
var order = await _broker.PlaceOrderAsync(new OrderRequest(
Symbol: symbol,
Quantity: qty,
Side: "Buy",
Type: orderType,
LimitPrice: lp,
TimeInForce: "Day",
ExtendedHours: isExtendedHours));
}
Account & Positions
Types representing your brokerage account state. AccountInfo provides a snapshot of cash, buying power, and equity at one moment. Position tracks an individual open holding with average entry price, current market value, and unrealized P&L. The Balance class is used internally for some broker integrations that report partial balance updates.
/// <summary>Snapshot of your brokerage account state at one moment.</summary>
public record AccountInfo(
string AccountId,
decimal Cash, // Available cash
decimal BuyingPower, // Total buying power (includes margin)
decimal Equity, // Total account equity
string Currency // Account currency (e.g. "USD")
);
/// <summary>An open position in your portfolio.</summary>
public record Position(
string Symbol,
decimal Quantity, // Number of shares held (negative for shorts)
decimal AvgEntryPrice, // Average cost basis per share
decimal MarketValue, // Current market value of the position
decimal UnrealizedPnl // Unrealized profit/loss in account currency
);
/// <summary>Balance breakdown for account monitoring. Some fields may
/// be null on brokers that report partial balance updates.</summary>
public class Balance
{
public decimal? Cash { get; set; }
public decimal? MarketValue { get; set; }
public decimal? BuyingPower { get; set; }
public decimal? Equity { get; set; }
}
Candles & Intervals
OHLCV candlestick data and the timeframe enum. Candles is in the ByteTraderIndicators.Rows namespace (it lives with the indicator rows because indicators consume it as input). Access live candles via _data.Candles[(symbol, interval)] — the list is ordered oldest-first; the most recent candle is at index Count-1.
// Candles is in the ByteTraderIndicators.Rows namespace, NOT in
// BTStrategy. Add a using directive at the top of your file:
// using ByteTraderIndicators.Rows;
/// <summary>
/// OHLCV candlestick data. Accessed via _data.Candles[(symbol, interval)].
/// Each candle represents one time period of price action; lists are
/// ordered oldest-first, so the most recent candle is at index Count-1.
/// </summary>
public class Candles
{
public string Symbol { get; set; }
public decimal Open { get; set; }
public decimal High { get; set; }
public decimal Low { get; set; }
public decimal Close { get; set; }
public decimal Volume { get; set; }
public decimal? AdjustedClose { get; set; } // Split/dividend-adjusted close
public DateTime MarketDate { get; set; } // Candle's opening timestamp
}
/// <summary>Supported candle timeframe intervals.</summary>
public enum Interval
{
OneMinute,
FiveMinutes,
FifteenMinutes,
ThirtyMinutes,
OneHour,
FourHours,
OneDay,
OneWeek,
OneMonth
}
// Example: reading the most recent close from your trading symbol's 5m chart:
//
// var key = ("AAPL", Interval.FiveMinutes);
// if (_data.Candles.TryGetValue(key, out var candles) && candles.Count > 0)
// {
// var lastClose = candles[candles.Count - 1].Close;
// }
Quotes, Trades & News
Real-time tick records delivered via IData event handlers. Subscribe to QuoteUpdate (NBBO bid/ask updates), TradeUpdate (individual prints), and NewsUpdate (articles from the news provider) in your OnAgentBoot method. News routing is controlled by the SetNewsFilter method on IData — see the News Filter section.
/// <summary>Real-time quote (NBBO bid/ask). Delivered via _data.QuoteUpdate.</summary>
public record Quote(
string Symbol,
DateTime Timestamp,
decimal BidPrice, // Highest bid price
long BidSize, // Size at best bid (round lots)
decimal AskPrice, // Lowest ask price
long AskSize, // Size at best ask (round lots)
string? BidExchange = null,
string? AskExchange = null
);
/// <summary>Real-time trade tick. Delivered via _data.TradeUpdate.</summary>
public record Trade(
string Symbol,
DateTime Timestamp,
decimal Price, // Trade execution price
long Size, // Number of shares in this trade
string? Exchange = null,
string? Conditions = null
);
/// <summary>
/// News article delivered via _data.NewsUpdate. Default behavior: every
/// article streamed from the provider reaches the handler (firehose).
/// Call _data.SetNewsFilter to narrow — see the News Filter section.
/// </summary>
public record NewsArticle(
string Id,
string Headline,
string Summary,
string? Author,
DateTime CreatedAt,
string Url,
List<string> Symbols, // Tickers tagged on the article (may be empty for macro news)
string Source,
List<string>? ImageUrls = null
);
News Filter Configuration
By default, NewsUpdate fires for every article streamed from the provider — the full firehose covering all US equities. Most strategies want to narrow this. Call _data.SetNewsFilter(watchlist, scope) once from OnAgentBoot to limit delivery to articles tagged with your trading symbols + an optional watchlist of peer tickers, with NewsScope controlling whether untagged general market news (Fed, sector commentary, economic data) is included.
/// <summary>
/// Controls whether untagged general market news (articles with no
/// ticker tags — Fed announcements, sector commentary, economic data)
/// flows through in addition to symbol-tagged news.
/// </summary>
public enum NewsScope
{
/// <summary>
/// Only news articles tagged with one of your trading symbols
/// (ActiveSymbols) or your watchlist symbols. General market news
/// with no ticker tags is excluded.
/// </summary>
TaggedOnly,
/// <summary>
/// All news articles tagged with one of your trading symbols or
/// your watchlist symbols, PLUS general market news with no tags.
/// </summary>
All
}
// SetNewsFilter is a method on IData. Default (if you never call it):
// every article passes through.
//
// Once called, the filter is active:
// — News for your trading symbols (ActiveSymbols) is ALWAYS delivered.
// You do NOT need to repeat them in the watchlist parameter.
// — News for any symbol in `watchlist` is also delivered. Use this for
// peer / watchlist tickers you want news for but don't trade — no
// historical / indicator side effects, this only widens the news
// routing filter.
// — `scope` independently controls whether untagged market news is in.
//
// Atomic; takes effect on the very next article. Case-insensitive symbol
// matching. Call any time from [Initialize] or runtime hooks. Reverting
// to the firehose at runtime is not supported in this version.
[Initialize]
public async Task OnAgentBoot()
{
// ... other setup ...
// Restrict news to articles tagged on my trading symbols + a peer
// watchlist, plus include macro news (Fed / sector commentary).
await _data.SetNewsFilter(
watchlist: new List<string> { "SPY", "QQQ", "VIX" },
scope: NewsScope.All);
}
Market Events
Structured, real-time market events delivered via _data.MarketEventUpdate as a typed MarketEvent — distinct from news. Covers SEC catalysts (earnings with parsed EPS/revenue surprise, insider Form 4 transactions, activist 13D stakes, buybacks, offerings, bankruptcy, delisting, and 8-K items such as cybersecurity incidents, debt acceleration, PIPE financings, shareholder votes and reverse splits, …) AND the platform's own derived signals (TradeSignal long/short, AfterHoursMove extended-hours movers, PickPerformance scorecards). Each event carries severity (Info / Notable / Critical), form type, the parsed Earnings / Insider detail when applicable, and a structured PayloadJson for the derived-signal types (deserialize with evt.ReadPayload<T>()). Requires the agent's Market Events feature to be enabled. Delivery is the full firehose by default — every event for every symbol, plus market-wide events that carry no Symbol; call _data.SetMarketEventFilter(symbols) to voluntarily narrow to specific tickers (market-wide events always still pass). Every event type listed on the Market data page (/data#event-types) arrives here, including Form 144 proposed sales, 10b5-1 plan changes, offerings with deal terms and late filings; read the type-specific detail from PayloadJson, which also carries knownAt (when the information became public).
/// <summary>
/// A structured market event delivered via _data.MarketEventUpdate. Covers SEC/FINRA
/// catalysts AND the platform's own derived signals. This is NOT a news article — it
/// carries the full structured detail of the event.
/// </summary>
public class MarketEvent
{
/// <summary>Category, e.g. "Earnings", "InsiderTransaction", "ActivistStake",
/// "Offering", "Bankruptcy", "TradeSignal", "AfterHoursMove", "PickPerformance".</summary>
public string EventType { get; set; }
/// <summary>Ticker the event concerns. NULL for market-wide events (e.g. the daily
/// performance scorecard) — those still reach you on the firehose.</summary>
public string? Symbol { get; set; }
public string? Cik { get; set; } // SEC filer id, for EDGAR events
public string Source { get; set; } // "SEC-EDGAR", "FINRA", "ByteTrader"
public string Severity { get; set; } // Info / Notable / Critical
public string Title { get; set; }
public string? Summary { get; set; }
public string? FormType { get; set; } // "8-K", "4", "SC 13D", "10-Q", ...
public string? ItemNumbersCsv { get; set; } // 8-K items, e.g. "2.02,9.01"
public string? AccessionNumber { get; set; }
public DateTime? FiledAt { get; set; }
public string DedupKey { get; set; } // stable id — same event => same key
/// <summary>Structured payload for the derived-signal types (TradeSignal /
/// AfterHoursMove / PickPerformance). JSON — use ReadPayload<T>(). Null for plain
/// catalysts (their detail is in Earnings / Insider).</summary>
public string? PayloadJson { get; set; }
public EarningsDetail? Earnings { get; set; } // present only for Earnings events
public InsiderDetail? Insider { get; set; } // present only for InsiderTransaction events
/// <summary>Deserialize PayloadJson into T (case-insensitive). Only call it for the
/// derived-signal event types that populate PayloadJson, or wrap in try/catch.</summary>
public T ReadPayload<T>();
}
public static class MarketEventSeverity
{
public const string Info = "Info";
public const string Notable = "Notable";
public const string Critical = "Critical";
}
/// <summary>Parsed earnings figures — attached to an Earnings MarketEvent.</summary>
public class EarningsDetail
{
public string? FiscalPeriod { get; set; }
public DateTime? PeriodEnd { get; set; }
public decimal? EpsActual { get; set; }
public decimal? EpsPriorYear { get; set; }
public decimal? EpsSurprisePct { get; set; } // percent, e.g. 5.0 == +5%
public decimal? RevenueActual { get; set; }
public decimal? RevenuePriorYear { get; set; }
public decimal? RevenueSurprisePct { get; set; }
public string? GuidanceText { get; set; }
}
/// <summary>Parsed insider Form 4 figures — attached to an InsiderTransaction MarketEvent.</summary>
public class InsiderDetail
{
public string? InsiderName { get; set; }
public string? InsiderTitle { get; set; }
public bool IsDirector { get; set; }
public bool IsOfficer { get; set; }
public bool IsTenPercentOwner { get; set; }
public string? TransactionCode { get; set; } // "P" purchase, "S" sale, "A" grant, ...
public DateTime? TransactionDate { get; set; }
public decimal? Shares { get; set; }
public decimal? PricePerShare { get; set; }
public decimal? TransactionValue { get; set; }
public string? OwnershipType { get; set; }
public decimal? SharesOwnedAfter { get; set; }
}
// ============================================================
// SUBSCRIBING and handling
// ============================================================
//
// [Initialize]
// public async Task OnAgentBoot()
// {
// _data.MarketEventUpdate += OnMarketEvent;
//
// // OPTIONAL — narrow to specific tickers. Omit this call for the full
// // firehose (default). Market-wide events (no Symbol) always pass.
// // await _data.SetMarketEventFilter(new List<string> { "AAPL", "NVDA" });
// }
//
// private void OnMarketEvent(object? sender, MarketEvent e)
// {
// switch (e.EventType)
// {
// case "Earnings" when e.Earnings is { } x:
// _logger.LogInformation(
// "{Sym} earnings: EPS {Eps} ({Surprise:+0.0;-0.0}% surprise)",
// e.Symbol, x.EpsActual, x.EpsSurprisePct);
// break;
//
// case "InsiderTransaction" when e.Insider is { } i:
// // e.g. only react to insider PURCHASES of size
// if (i.TransactionCode == "P" && i.TransactionValue >= 250_000m)
// _logger.LogInformation("{Sym} insider buy: {Who} {Val:C0}",
// e.Symbol, i.InsiderName, i.TransactionValue);
// break;
//
// case "TradeSignal":
// // Derived signal — structured numbers live in PayloadJson.
// var sig = e.ReadPayload<TradeSignalPayload>();
// if (sig.Direction == "Long" && sig.Score >= 70)
// _ = _agent.AddSymbol(e.Symbol!);
// break;
//
// case "AfterHoursMove":
// // Critical-severity = a big extended-hours move.
// if (e.Severity == MarketEventSeverity.Critical)
// _logger.LogInformation("{Sym}: {Summary}", e.Symbol, e.Summary);
// break;
// }
// }
//
// // Your own shape for the TradeSignal PayloadJson (only the fields you need):
// public class TradeSignalPayload
// {
// public string Direction { get; set; } // "Long" / "Short"
// public double Score { get; set; }
// public decimal Price { get; set; }
// public List<string> Factors { get; set; }
// }
Fundamentals & Snapshots
The daily market snapshot delivered via _data.Snapshot and the SnapshotRefresh event. Contains corporate actions (splits, dividends) and a per-symbol MarketOverview with 1 year of daily candles, yesterday's full-day minute candles, a multi-day percent-change history, and a comprehensive Fundamental record (valuation, margins, debt metrics, volume averages, beta, short interest, and more). Snapshot refresh fires once when the daily snapshot rolls over — typical use case: rebuild your trading universe.
/// <summary>
/// Daily snapshot data accessible via _data.Snapshot. The
/// SnapshotRefresh event fires once when the snapshot rolls over each
/// day — typical use case: rebuild your trading universe.
/// </summary>
public class SnapshotData
{
public List<StockSplit> Splits { get; set; }
public List<Dividend> Dividends { get; set; }
/// <summary>Per-symbol market overview, keyed by symbol.</summary>
public Dictionary<string, MarketOverview> Overview { get; set; }
}
/// <summary>Per-symbol market overview with historical context.</summary>
public class MarketOverview
{
public string Symbol { get; set; }
public List<PercentChangeRecord> PercentChanges { get; set; } = new();
public Fundamental Fundamentals { get; set; }
/// <summary>1 year of daily bars (~252 trading days), oldest-first.</summary>
public List<Candles> DailyCandles { get; set; } = new();
/// <summary>Yesterday's full-day 1-minute bars.</summary>
public List<Candles> MinuteCandles { get; set; } = new();
}
public class StockSplit
{
public int SymbolId { get; set; }
public string Symbol { get; set; } = string.Empty;
public DateTime ExecutionDate { get; set; }
public decimal SplitFrom { get; set; } // e.g. 1 (1-for-4 split)
public decimal SplitTo { get; set; } // e.g. 4
public DateTime CreatedAt { get; set; }
}
public class Dividend
{
public int SymbolId { get; set; }
public string Symbol { get; set; } = string.Empty;
public decimal CashAmount { get; set; }
public string? Currency { get; set; }
public string? DividendType { get; set; }
public DateTime ExDividendDate { get; set; }
public DateTime? RecordDate { get; set; }
public DateTime? PayDate { get; set; }
public int? Frequency { get; set; }
public DateTime CreatedAt { get; set; }
}
public class PercentChangeRecord
{
public string MarketDateString { get; set; }
public DateTime? MarketDate { get; set; }
public DateTime? PreviousMarketDate { get; set; }
public decimal? PercentChange { get; set; }
public decimal? AbsoluteChange { get; set; }
public decimal? VolumePercentChange { get; set; }
public string? Symbol { get; set; }
}
/// <summary>
/// Comprehensive fundamental data for a symbol. Source: end-of-day
/// data feed; refreshed once per trading day.
/// </summary>
public class Fundamental
{
public int SymbolId { get; set; }
public DateTime MarketDate { get; set; }
public string Symbol { get; set; }
// --- Price Range ---
public decimal? High52 { get; set; }
public decimal? Low52 { get; set; }
// --- Valuation ---
public decimal? PeRatio { get; set; }
public decimal? PegRatio { get; set; }
public decimal? PbRatio { get; set; }
public decimal? PrRatio { get; set; }
public decimal? PcfRatio { get; set; }
public decimal? MarketCap { get; set; }
public decimal? MarketCapFloat { get; set; }
public decimal? BookValuePerShare { get; set; }
// --- Earnings / Revenue ---
public decimal? EpsTtm { get; set; }
public decimal? Eps { get; set; }
public decimal? EpsChange { get; set; }
public decimal? EpsChangePercentTtm { get; set; }
public decimal? EpsChangeYear { get; set; }
public decimal? RevChangeYear { get; set; }
public decimal? RevChangeTtm { get; set; }
public decimal? RevChangeIn { get; set; }
// --- Profitability ---
public decimal? GrossMarginTtm { get; set; }
public decimal? GrossMarginMrq { get; set; }
public decimal? NetProfitMarginTtm { get; set; }
public decimal? NetProfitMarginMrq { get; set; }
public decimal? OperatingMarginTtm { get; set; }
public decimal? OperatingMarginMrq { get; set; }
public decimal? ReturnOnEquity { get; set; }
public decimal? ReturnOnAssets { get; set; }
public decimal? ReturnOnInvestment { get; set; }
// --- Financial Health ---
public decimal? CurrentRatio { get; set; }
public decimal? QuickRatio { get; set; }
public decimal? InterestCoverage { get; set; }
public decimal? TotalDebtToCapital { get; set; }
public decimal? LtDebtToEquity { get; set; }
public decimal? TotalDebtToEquity { get; set; }
// --- Dividends ---
public decimal? DividendYield { get; set; }
public decimal? DividendAmount { get; set; }
public decimal? DividendPayAmount { get; set; }
public decimal? DivGrowthRate3Year { get; set; }
public int? DividendFreq { get; set; }
// --- Volume / Liquidity ---
public decimal? Beta { get; set; }
public decimal? Vol1DayAvg { get; set; }
public decimal? Vol10DayAvg { get; set; }
public decimal? Vol3MonthAvg { get; set; }
public long? Avg1DayVolume { get; set; }
public long? Avg10DaysVolume { get; set; }
public long? Avg3MonthVolume { get; set; }
public decimal? SharesOutstanding { get; set; }
public long? DtnVolume { get; set; }
// --- Short Interest ---
public decimal? ShortIntToFloat { get; set; }
public decimal? ShortIntDayToCover { get; set; }
// --- Funds / ETFs ---
public decimal? FundLeverageFactor { get; set; }
}
Instruments & Asset Classes
ByteTrader is multi-asset: one strategy can trade equities, options, futures, and crypto. _data.ResolveInstrument(symbol) returns an InstrumentInfo carrying the symbol's AssetClass (Equity / Option / Future / Crypto / Kalshi), contract Multiplier (equity & crypto = 1, option = 100, futures per-root), TickSize, SessionType (USEquityRth / Crypto24x7 / FuturesCme / Kalshi), and contract detail — Strike / Expiry / Right for options, BaseCcy / QuoteCcy for crypto. The string symbol stays the universal key everywhere; this record is just looked up on demand at the compute sites that need a multiplier, session, or contract detail. Equities resolve to the safe default (Equity, multiplier 1, RTH, precision 2), so a stocks-only strategy needs nothing new — mixed-class strategies branch on info.AssetClass to size notional (price × qty × Multiplier) and gate sessions correctly.
/// <summary>The asset class of a tradable instrument. Equity is 0 — the safe,
/// backward-compatible default (anything not positively identified is Equity).</summary>
public enum AssetClass { Equity = 0, Option = 1, Future = 2, Crypto = 3, Kalshi = 4 }
/// <summary>Trading-session model. USEquityRth (0) reproduces equity behavior.</summary>
public enum SessionType
{
USEquityRth = 0, // 09:30-16:00 ET + 04:00/20:00 ET extended hours
Crypto24x7 = 1, // 24/7, UTC-day bookkeeping
FuturesCme = 2, // CME-style near-24h session with a daily break
Kalshi = 3 // per-market hours; closes on event settlement
}
/// <summary>Resolved metadata for a symbol. Every field beyond Symbol is optional
/// and defaulted so an equity resolves to (Equity, Multiplier 1, USEquityRth,
/// precision 2). Looked up on demand via _data.ResolveInstrument(symbol).</summary>
public record InstrumentInfo(
string Symbol,
AssetClass AssetClass = AssetClass.Equity,
string? UnderlyingSymbol = null, // option/future underlying ticker
decimal Multiplier = 1m, // equity+crypto = 1, option = 100, futures per-root
decimal? TickSize = null,
DateTime? Expiry = null,
decimal? Strike = null,
string? Right = null, // "C" / "P" for options
string? BaseCcy = null, // crypto base ccy (e.g. "BTC")
string? QuoteCcy = null, // crypto quote ccy (e.g. "USD")
SessionType SessionType = SessionType.USEquityRth,
int PricePrecision = 2)
{
public bool IsEquity => AssetClass == AssetClass.Equity;
}
// Example — branch per class when trading mixed symbols:
//
// var info = _data.ResolveInstrument(symbol);
// if (info.AssetClass == AssetClass.Crypto) { /* 24/7, fractional qty */ }
// var notional = price * qty * info.Multiplier; // options x100, futures per-root
Option Chains
_data.GetOptionChainAsync(underlying, from, to, contractType) fetches the option chain for an underlying from the agent's option-capable providers (Schwab fills greeks / IV / open interest; Alpaca covers contracts and quotes only). It returns an OptionChain with separate Calls and Puts lists of OptionChainEntry — each carries a canonical OCC Symbol you can place directly via PlaceOrderAsync (or pass to ResolveInstrument), plus StrikePrice, ExpirationDate, OptionType, bid / ask, volume / open interest, and provider-dependent greeks (Delta, Gamma, Theta, Vega, ImpliedVolatility). from / to bound the expirations; contractType filters to "CALL" or "PUT" (null = both). Returns null when no connected provider serves options. Combine with the multi-leg order API to open defined-risk spreads.
/// <summary>One contract row of an option chain. Symbol is canonical OCC
/// ("AAPL260619C00150000") — pass it straight to PlaceOrderAsync or
/// ResolveInstrument. Greeks/IV/OI are provider-dependent and may be null.</summary>
public record OptionChainEntry(
string Symbol,
string UnderlyingSymbol,
string OptionType, // "CALL" / "PUT"
decimal StrikePrice,
DateTime ExpirationDate,
decimal? Bid,
decimal? Ask,
long? Volume,
long? OpenInterest,
decimal? Delta,
decimal? Gamma,
decimal? Theta,
decimal? Vega,
decimal? ImpliedVolatility);
/// <summary>An option chain for one underlying. Calls and puts are separate lists.</summary>
public record OptionChain(
string UnderlyingSymbol,
Quote? UnderlyingQuote,
List<OptionChainEntry> Calls,
List<OptionChainEntry> Puts);
// IData.GetOptionChainAsync(underlying, from, to, contractType, ct) — null = no
// provider serves options. contractType filters "CALL"/"PUT" (null = both).
// Example — pick the nearest-expiry ATM call and buy one contract:
//
// var chain = await _data.GetOptionChainAsync(
// "AAPL", to: _clock.UtcNow.AddDays(30), contractType: "CALL");
// var spot = chain?.UnderlyingQuote != null
// ? (chain.UnderlyingQuote.BidPrice + chain.UnderlyingQuote.AskPrice) / 2m : 0m;
// var atm = chain?.Calls.Where(c => c.StrikePrice >= spot)
// .OrderBy(c => c.StrikePrice).FirstOrDefault();
// if (atm != null)
// await _broker.PlaceOrderAsync(new OrderRequest(atm.Symbol, 1, "Buy", "Market"));
Market Depth (Level 2)
Level-2 order-book streaming for microstructure signals. Depth is OFF by default (it's bandwidth-heavy) — call _data.SubscribeDepth(symbols) from [Initialize] to opt in. Only crypto venues (Kraken, Coinbase) expose a book today; it's a no-op for Level-1 equity / option providers. After subscribing, DepthUpdate fires on every book update and GetOrderBook(symbol) returns the latest book as a pull alternative. An OrderBook carries best-first Bids and Asks (each a BookLevel of Price + resting Size), convenience BestBid / BestAsk / BestBidSize / BestAskSize, and DepthWithin(levels) which totals the resting size across the top N levels on each side — handy for order-book-imbalance reads.
/// <summary>One resting-order price level in a book: a price and the size
/// resting there (decimal so fractional crypto quantities survive).</summary>
public record BookLevel(decimal Price, decimal Size);
/// <summary>A Level-2 order-book snapshot. Bids best-first (descending price),
/// Asks best-first (ascending). Crypto exchanges only (Kraken, Coinbase).</summary>
public record OrderBook(
string Symbol,
DateTime Timestamp,
IReadOnlyList<BookLevel> Bids,
IReadOnlyList<BookLevel> Asks)
{
public decimal BestBid => Bids.Count > 0 ? Bids[0].Price : 0m;
public decimal BestBidSize => Bids.Count > 0 ? Bids[0].Size : 0m;
public decimal BestAsk => Asks.Count > 0 ? Asks[0].Price : 0m;
public decimal BestAskSize => Asks.Count > 0 ? Asks[0].Size : 0m;
/// <summary>Total resting size across the top N levels on each side.</summary>
public (decimal Bid, decimal Ask) DepthWithin(int levels)
{
decimal b = 0m, a = 0m;
for (int i = 0; i < levels && i < Bids.Count; i++) b += Bids[i].Size;
for (int i = 0; i < levels && i < Asks.Count; i++) a += Asks[i].Size;
return (b, a);
}
}
// IData: SubscribeDepth(symbols) to opt in, DepthUpdate event, GetOrderBook(symbol).
// Example — opt in at boot and read order-book imbalance:
//
// [Initialize]
// public async Task OnAgentBoot()
// {
// _data.DepthUpdate += OnDepth;
// await _data.SubscribeDepth(new() { "BTC/USD" }); // no-op for equities
// }
//
// private void OnDepth(object? sender, OrderBook book)
// {
// var (bid, ask) = book.DepthWithin(10);
// if (ask > 0 && bid > ask * 2) { /* heavy bid-side imbalance */ }
// }
On-Demand Data (Bars & Fundamentals)
Two pull-style IData methods for fetching data outside the live stream and the once-daily snapshot. GetHistoricalBarsAsync(symbol, interval, from, to) pulls an arbitrary OHLC range from the agent's providers (first provider that serves the interval wins) — use it to warm a long look-back indicator at [Initialize], do multi-timeframe analysis, or size up a symbol before subscribing. GetFundamentalsAsync(symbol) pulls the latest computed fundamentals (P/E, margins, market cap, dividend, 52-week range, …) for a single symbol — a fresh read beyond the daily snapshot's Overview. Both return an empty list / null when no connected provider serves the request (e.g. backtests v1).
// Two pull-style IData methods — fetch data outside the live stream and the
// once-daily snapshot. Both return empty/null when no provider serves the request.
/// <summary>Arbitrary historical OHLC range for any symbol/interval.</summary>
public Task<List<Candles>> GetHistoricalBarsAsync(
string symbol, Interval interval, DateTime from, DateTime to,
CancellationToken ct = default);
/// <summary>Latest computed fundamentals for one symbol (P/E, margins,
/// market cap, dividend, 52-week range, ...).</summary>
public Task<Fundamental?> GetFundamentalsAsync(string symbol, CancellationToken ct = default);
// Example — warm a 200-day SMA at boot, then check valuation:
//
// [Initialize]
// public async Task OnAgentBoot()
// {
// var daily = await _data.GetHistoricalBarsAsync(
// "AAPL", Interval.OneDay, _clock.UtcNow.AddYears(-1), _clock.UtcNow);
// var sma200 = daily.TakeLast(200).Average(c => c.Close);
//
// var f = await _data.GetFundamentalsAsync("AAPL");
// if (f?.PeRatio > 40m) { /* rich valuation — skip */ }
// }
Indicator Rows
Technical indicator output types. All indicators implement IBaseRow with a Timestamp property. Access live indicator data via _data.Indicators[(symbol, indicatorName)] — the list is ordered oldest-first; cast each row to the specific row type to access its outputs. The indicatorName string matches the name you assigned in the indicator profile on the Indicators page (not the indicator's class name) — multiple instances of the same indicator class (e.g. EMA9 and EMA21) coexist by name. Configure which indicators are computed via indicator profiles in the desktop app.
// Indicator rows live in the ByteTraderIndicators.Rows namespace:
// using ByteTraderIndicators.Rows;
//
// Every row implements IBaseRow. Access live indicator data by name
// from the indicator profile assigned to the agent — NOT by class name:
//
// var key = ("AAPL", "EMA9_5"); // profile-defined name
// var rows = _data.Indicators[key];
// var ema = ((EmaRow)rows[rows.Count - 1]).Ema;
/// <summary>Base interface for every indicator output row.</summary>
public interface IBaseRow
{
public DateTime Timestamp { get; set; }
}
// ============================================================
// TREND
// ============================================================
/// <summary>Simple Moving Average</summary>
public class SmaRow : IBaseRow
{
public DateTime Timestamp { get; set; }
public decimal Close { get; set; }
public decimal? Sma { get; set; }
}
/// <summary>Exponential Moving Average</summary>
public class EmaRow : IBaseRow
{
public DateTime Timestamp { get; set; }
public decimal Close { get; set; }
public decimal? Ema { get; set; }
}
/// <summary>Hull Moving Average</summary>
public class HmaRow : IBaseRow
{
public DateTime Timestamp { get; set; }
public decimal Price { get; set; }
public decimal HMA { get; set; }
}
/// <summary>MACD (Moving Average Convergence Divergence)</summary>
public class MacdRow : IBaseRow
{
public DateTime Timestamp { get; set; }
public decimal ClosingPrice { get; set; }
public decimal? ShortEma { get; set; } // Fast EMA (default 12)
public decimal? LongEma { get; set; } // Slow EMA (default 26)
public decimal? Macd { get; set; } // MACD line (Short - Long)
public decimal? Signal { get; set; } // Signal line (9-period EMA of MACD)
public bool FirstIntersection { get; set; } // True on signal-line crossover
}
/// <summary>Supertrend — ATR-based trend-following overlay</summary>
public class SupertrendRow : IBaseRow
{
public DateTime Timestamp { get; set; }
public decimal TrueRange { get; set; }
public decimal ATR { get; set; }
public decimal UpperBand { get; set; }
public decimal LowerBand { get; set; }
public decimal Supertrend { get; set; } // The trailing-stop level
public bool IsUptrend { get; set; }
}
/// <summary>VStop — volatility-based trailing stop</summary>
public class VstopRow : IBaseRow
{
public DateTime Timestamp { get; set; }
public decimal Atr { get; set; }
public decimal Stop { get; set; } // The stop level
public bool IsLong { get; set; } // Direction of the trailing stop
}
// ============================================================
// MOMENTUM / OSCILLATORS
// ============================================================
/// <summary>Relative Strength Index</summary>
public class RsiRow : IBaseRow
{
public DateTime Timestamp { get; set; }
public decimal ClosingPrice { get; set; }
public decimal? Change { get; set; }
public decimal? Gain { get; set; }
public decimal? Loss { get; set; }
public decimal? AvgGain { get; set; }
public decimal? AvgLoss { get; set; }
public decimal? RS { get; set; }
public decimal? RSI14Day { get; set; }
public decimal? RSI { get; set; } // The RSI value (0-100)
}
/// <summary>Stochastic Oscillator</summary>
public class StochasticRow : IBaseRow
{
public DateTime Timestamp { get; set; }
public decimal K { get; set; } // Fast line (0-100)
public decimal D { get; set; } // Slow / signal line (0-100)
}
/// <summary>Commodity Channel Index</summary>
public class CciRow : IBaseRow
{
public DateTime Timestamp { get; set; }
public decimal TypicalPrice { get; set; }
public decimal CCI { get; set; } // The CCI value
}
/// <summary>ADX (Average Directional Index) — trend strength</summary>
public class AdxRow : IBaseRow
{
public DateTime Timestamp { get; set; }
public decimal ClosingPrice { get; set; }
public decimal High { get; set; }
public decimal Low { get; set; }
public decimal? TR { get; set; }
public decimal? PlusDM1 { get; set; }
public decimal? MinusDM1 { get; set; }
public decimal? TR14 { get; set; }
public decimal? PlusDM14 { get; set; }
public decimal? MinusDM14 { get; set; }
public decimal? PlusDI14 { get; set; } // +DI (bullish pressure)
public decimal? MinusDI14 { get; set; } // -DI (bearish pressure)
public decimal? DI14Diff { get; set; }
public decimal? DI14Sum { get; set; }
public decimal? DX { get; set; } // Directional index (pre-smoothing)
public decimal? ADX { get; set; } // ADX value (trend strength, 0-100)
}
// ============================================================
// VOLATILITY
// ============================================================
/// <summary>Bollinger Bands</summary>
public class BollingerbandRow : IBaseRow
{
public DateTime Timestamp { get; set; }
public decimal? MiddleBand { get; set; } // Middle band (SMA)
public decimal? UpperBand { get; set; } // Upper band (+N SD)
public decimal? LowerBand { get; set; } // Lower band (-N SD)
public decimal? SD { get; set; } // Standard deviation
}
/// <summary>Average True Range</summary>
public class AtrRow : IBaseRow
{
public DateTime Timestamp { get; set; }
public decimal TrueRange { get; set; }
public decimal ATR { get; set; }
}
/// <summary>Keltner Channels — ATR-based bands around an EMA</summary>
public class KeltnerRow : IBaseRow
{
public DateTime Timestamp { get; set; }
public decimal Middle { get; set; } // EMA basis
public decimal Upper { get; set; }
public decimal Lower { get; set; }
}
/// <summary>Choppiness Index — sideways-vs-trending regime detector</summary>
public class ChoppinessRow : IBaseRow
{
public DateTime Timestamp { get; set; }
public decimal Choppiness { get; set; } // 0-100; >61.8 = chop, <38.2 = trend
}
// ============================================================
// VOLUME / ORDER FLOW
// ============================================================
/// <summary>On-Balance Volume</summary>
public class ObvRow : IBaseRow
{
public DateTime Timestamp { get; set; }
public long Volume { get; set; }
public decimal Obv { get; set; } // Running cumulative OBV
}
/// <summary>Money Flow Index</summary>
public class MfiRow : IBaseRow
{
public DateTime Timestamp { get; set; }
public decimal TypicalPrice { get; set; }
public decimal RawMoneyFlow { get; set; }
public decimal PositiveMoneyFlow { get; set; }
public decimal NegativeMoneyFlow { get; set; }
public decimal Mfi { get; set; } // 0-100; >80 overbought, <20 oversold
}
/// <summary>Session VWAP — Volume-Weighted Average Price reset daily</summary>
public class SessionVwapRow : IBaseRow
{
public DateTime Timestamp { get; set; }
public decimal? Vwap { get; set; }
public decimal? StdDev { get; set; }
public List<decimal> UpperBands { get; set; } // Configurable σ-band offsets above VWAP
public List<decimal> LowerBands { get; set; } // Configurable σ-band offsets below VWAP
}
/// <summary>Relative Volume — current vs N-day same-time-of-day average</summary>
public class RvolRow : IBaseRow
{
public DateTime Timestamp { get; set; }
public long Volume { get; set; }
public decimal AverageHistoricalVolume { get; set; }
public decimal RVOL { get; set; } // 1.0 = average, 2.0 = 2x normal
}
/// <summary>Cumulative Volume Delta — signed volume order-flow proxy</summary>
public class CvdRow : IBaseRow
{
public DateTime Timestamp { get; set; }
public long Volume { get; set; }
public long SignedVolume { get; set; } // +buys, -sells (uptick/downtick)
public long Cvd { get; set; } // Running cumulative
}
/// <summary>Volume Spike Detector — Z-score-based outlier flagging</summary>
public class VolumeSpikeRow : IBaseRow
{
public DateTime Timestamp { get; set; }
public long Volume { get; set; }
public decimal Mean { get; set; }
public decimal StdDev { get; set; }
public decimal RelVolStDev { get; set; } // Z-score of current bar's volume
public bool IsSpike { get; set; } // True if Z >= threshold (e.g. +2)
public bool IsLowSpike { get; set; } // True if Z <= -threshold
}
// ============================================================
// STRUCTURE / LEVELS
// ============================================================
/// <summary>Daily Pivot Points — classic floor-trader pivots</summary>
public class PivotRow : IBaseRow
{
public DateTime Timestamp { get; set; }
public decimal P { get; set; } // Pivot point
public decimal R1 { get; set; } // Resistance 1
public decimal S1 { get; set; } // Support 1
public decimal R2 { get; set; } // Resistance 2
public decimal S2 { get; set; } // Support 2
}
/// <summary>Market Structure — Break-of-Structure (BOS) detection</summary>
public class MarketStructureRow : IBaseRow
{
public DateTime Timestamp { get; set; }
public bool IsSwingHigh { get; set; } // This bar is a confirmed swing high
public bool IsSwingLow { get; set; } // This bar is a confirmed swing low
public bool BullishBOS { get; set; } // Broke last swing high → bullish BOS
public bool BearishBOS { get; set; } // Broke last swing low → bearish BOS
public decimal LastSwingHigh { get; set; }
public decimal LastSwingLow { get; set; }
}
// ============================================================
// TREND / MOVING AVERAGES (additional)
// ============================================================
/// <summary>KAMA — Kaufman Adaptive Moving Average</summary>
public class KamaRow : IBaseRow
{
public DateTime Timestamp { get; set; }
public decimal Price { get; set; }
public decimal KAMA { get; set; }
}
/// <summary>VIDYA — Variable Index Dynamic Average</summary>
public class VidyaRow : IBaseRow
{
public DateTime Timestamp { get; set; }
public decimal VIDYA { get; set; }
}
/// <summary>T3 — Tillson T3 Moving Average</summary>
public class T3Row : IBaseRow
{
public DateTime Timestamp { get; set; }
public decimal Price { get; set; }
public decimal T3 { get; set; }
}
// ============================================================
// MOMENTUM / OSCILLATORS (additional)
// ============================================================
/// <summary>TSI — True Strength Index</summary>
public class TsiRow : IBaseRow
{
public DateTime Timestamp { get; set; }
public decimal TSI { get; set; }
}
/// <summary>Aroon — time-since-extreme trend indicator</summary>
public class AroonRow : IBaseRow
{
public DateTime Timestamp { get; set; }
public decimal Up { get; set; } // Aroon Up (0-100)
public decimal Down { get; set; } // Aroon Down (0-100)
public decimal? Oscillator { get; set; } // Up - Down
}
/// <summary>DMI — Directional Movement Index (+DI / -DI / ADX)</summary>
public class DmiRow : IBaseRow
{
public DateTime Timestamp { get; set; }
public decimal PlusDI { get; set; }
public decimal MinusDI { get; set; }
public decimal ADX { get; set; }
}
/// <summary>VROC — Volume Rate of Change</summary>
public class VrocRow : IBaseRow
{
public DateTime Timestamp { get; set; }
public long Volume { get; set; }
public decimal VROC { get; set; }
}
/// <summary>Rolling Correlation vs the configured benchmark series</summary>
public class RollingCorrelationRow : IBaseRow
{
public DateTime Timestamp { get; set; }
public decimal Correlation { get; set; } // -1..+1
}
// ============================================================
// VOLATILITY / BANDS / STOPS (additional)
// ============================================================
/// <summary>ATR Bands — bands offset from a basis by a multiple of ATR</summary>
public class AtrBandsRow : IBaseRow
{
public DateTime Timestamp { get; set; }
public decimal Middle { get; set; }
public decimal Upper { get; set; }
public decimal Lower { get; set; }
public decimal ATR { get; set; }
}
/// <summary>Donchian Channels — rolling high/low channel</summary>
public class DonchianRow : IBaseRow
{
public DateTime Timestamp { get; set; }
public decimal Upper { get; set; }
public decimal Lower { get; set; }
public decimal Middle { get; set; }
}
/// <summary>Chande-Kroll Stop — volatility-based long/short stops</summary>
public class ChandeKrollRow : IBaseRow
{
public DateTime Timestamp { get; set; }
public decimal LongStop { get; set; }
public decimal ShortStop { get; set; }
}
/// <summary>Garman-Klass volatility (annualized)</summary>
public class GarmanKlassRow : IBaseRow
{
public DateTime Timestamp { get; set; }
public decimal Volatility { get; set; } // annualized
}
/// <summary>Historical (close-to-close) Volatility (annualized)</summary>
public class HistoricalVolRow : IBaseRow
{
public DateTime Timestamp { get; set; }
public decimal HV { get; set; } // annualized
}
/// <summary>Parabolic SAR — stop-and-reverse trend stop</summary>
public class PsarRow : IBaseRow
{
public DateTime Timestamp { get; set; }
public decimal Close { get; set; }
public decimal? Psar { get; set; } // The SAR stop level
public decimal? Ep { get; set; } // Extreme point
public decimal? EpPsar { get; set; }
public decimal? AccFactor { get; set; } // Acceleration factor
public decimal? EpPsarAcc { get; set; }
public bool IsUptrend { get; set; }
public bool IsDowntrend { get; set; }
}
// ============================================================
// VOLUME / ORDER FLOW (additional)
// ============================================================
/// <summary>Accumulation/Distribution Line</summary>
public class AdRow : IBaseRow
{
public DateTime Timestamp { get; set; }
public decimal MoneyFlowMultiplier { get; set; }
public decimal MoneyFlowVolume { get; set; }
public decimal AdLine { get; set; } // Running A/D line
}
/// <summary>Chaikin Money Flow</summary>
public class CmfRow : IBaseRow
{
public DateTime Timestamp { get; set; }
public decimal MoneyFlowMultiplier { get; set; }
public decimal MoneyFlowVolume { get; set; }
public decimal Cmf { get; set; }
}
/// <summary>Ease of Movement</summary>
public class EomRow : IBaseRow
{
public DateTime Timestamp { get; set; }
public decimal RawEom { get; set; }
public decimal SmoothedEom { get; set; }
}
/// <summary>IVR — current vs historical same-time volume rank</summary>
public class IvrRow : IBaseRow
{
public DateTime Timestamp { get; set; }
public long Volume { get; set; }
public decimal AverageHistoricalVolume { get; set; }
public decimal IVR { get; set; }
}
/// <summary>Money Flow EMA — EMA of price*volume money flow</summary>
public class MoneyFlowEmaRow : IBaseRow
{
public DateTime Timestamp { get; set; }
public decimal MoneyFlow { get; set; }
public decimal MoneyFlowEma { get; set; }
}
/// <summary>PVT — Price-Volume Trend</summary>
public class PvtRow : IBaseRow
{
public DateTime Timestamp { get; set; }
public decimal PVT { get; set; }
}
/// <summary>TDVP — Time-of-Day Volume Percentile</summary>
public class TdvpRow : IBaseRow
{
public DateTime Timestamp { get; set; }
public long Volume { get; set; }
public decimal Percentile { get; set; } // 0-100
}
/// <summary>VFI — Volume Flow Indicator</summary>
public class VfiRow : IBaseRow
{
public DateTime Timestamp { get; set; }
public decimal VFI { get; set; }
public decimal Signal { get; set; }
}
/// <summary>Volume Acceleration — velocity + acceleration of volume</summary>
public class VolumeAccelerationRow : IBaseRow
{
public DateTime Timestamp { get; set; }
public long Volume { get; set; }
public decimal Velocity { get; set; }
public decimal Acceleration { get; set; }
}
/// <summary>Volume Profile — volume traded at a price bucket</summary>
public class VolumeProfileRow : IBaseRow
{
public decimal PriceBucket { get; set; }
public long Volume { get; set; }
public DateTime Timestamp { get; set; }
}
/// <summary>Volume Z-Score — standardized current-bar volume</summary>
public class VolumeZScoreRow : IBaseRow
{
public DateTime Timestamp { get; set; }
public long Volume { get; set; }
public decimal Mean { get; set; }
public decimal StdDev { get; set; }
public decimal ZScore { get; set; }
}
/// <summary>VPI — Volume Pace Indicator (cumulative vs historical pace)</summary>
public class VpiRow : IBaseRow
{
public DateTime Timestamp { get; set; }
public long CumulativeToday { get; set; }
public decimal AverageHistoricalCumulative { get; set; }
public decimal VPI { get; set; }
}
/// <summary>Return Z-Score — standardized per-bar return</summary>
public class ReturnZScoreRow : IBaseRow
{
public DateTime Timestamp { get; set; }
public decimal Return { get; set; }
public decimal Mean { get; set; }
public decimal StdDev { get; set; }
public decimal ZScore { get; set; }
}
// ============================================================
// STRUCTURE / PATTERN (additional)
// ============================================================
/// <summary>Fractal — Bill Williams swing fractals</summary>
public class FractalRow : IBaseRow
{
public DateTime Timestamp { get; set; }
public bool IsFractalHigh { get; set; }
public bool IsFractalLow { get; set; }
}
/// <summary>Inside / Outside bar pattern flags</summary>
public class InsideOutsideRow : IBaseRow
{
public DateTime Timestamp { get; set; }
public bool IsInsideBar { get; set; }
public bool IsOutsideBar { get; set; }
}
// ============================================================
// That is the COMPLETE library — 51 indicator row types. Configure
// which ones run by creating an Indicator Profile in ByteTrader and
// attaching it to your agent. Each indicator in the profile has a
// NAME (the dictionary key in _data.Indicators), a TYPE (one of the
// class names above), a TIMEFRAME (Interval enum), and a JSON
// CONFIGURATION blob (period, multiplier, lookback, etc). Multiple
// instances of the same TYPE coexist by NAME — e.g. "EMA9" and "EMA21".