Skip to main content

Strategy Framework

The MZpack strategy framework organizes trading logic into a structured pipeline: patterns define trading conditions through decision trees of signals and filters, which trigger entries with protective orders, managed by position management and risk management rules. This page covers each component in detail.

note

Every MZpack strategy inherits the settings documented on this page. In the NinjaTrader strategy properties they all appear under the MZpack category; the tables below are grouped by topic and follow the order of that category. Settings specific to an individual strategy are documented in Built-in Strategies.

Strategy Settings

SettingDefaultDescription
Settings preset(empty)Name that gives this strategy instance its own indicator and pattern template files. Empty means all instances share one set of templates in Documents\NinjaTrader 8\mzpack\strategy\<namespace>\<strategy>\templates; entering a name appends it to each file (VP.ES.xml instead of VP.xml)
BacktestingfalseRun the strategy in the historical state for the Strategy Analyzer. Increases loading time — do not enable it for chart trading. See Backtesting
OperatingAutoOperating mode — Auto or Manual. See Operating Modes
Handle order errorstrueIgnore real-time order errors instead of stopping the strategy, and handle protective orders moved on the chart. Resolves a Rithmic execution issue. Read-only
Trace ordersfalseWrite NinjaScript order tracing to the Output window (sets NinjaTrader's TraceOrders). Useful for diagnosing order submission

Operating Modes

ModeDescription
AutoEntries are submitted automatically when a pattern validates
ManualEntries are not submitted — patterns and signals are only displayed on the chart, and positions are opened by hand from Chart Trader

Patterns

A pattern is a set of conditions that, when satisfied, produce a determined trading direction (Long or Short). Patterns are the central organizing unit of any MZpack strategy.

Pattern Types

TypePurpose
EntryOpens a new position when validated
ExitCloses an existing position when validated (optional)
ReversalCloses the current position and opens one in the opposite direction
ScaleInAdds to an existing position
ScaleOutReduces an existing position

How a Pattern Works

When a pattern is evaluated, three steps occur in sequence:

  1. Signals tree — the signals decision tree is evaluated. If a determined direction (Long or Short) results, proceed to step 2. Otherwise the pattern is not validated.
  2. Filters tree — the filters decision tree is evaluated starting from the bar at which signals validated. If the direction is confirmed, proceed to step 3.
  3. Entry — a position is opened according to the entry configuration and the determined direction.

The signals tree must contain at least one signal. The filters tree is optional — if no filters are present, the pattern proceeds directly from signals to entry.

Pattern Localization

A pattern can be localized to constrain where its signals and filters must occur:

  • Price range — signals/filters must occur within a specified number of ticks
  • Bar range — signals/filters must occur within a specified number of bars
  • Session — signals/filters must occur within the current trading session

Price and bar ranges can be set independently for the signals tree and the filters tree.

Allowed Direction

Each pattern has an AllowedDirection property that restricts which directions the pattern can validate: Long, Short, or Any (both). The resulting direction from the decision trees must be consistent with the allowed direction.

Decision Trees

Signals and filters are organized into logical decision trees. Each tree has a root logical node, and supports three types of nodes:

  • Logical node — performs AND, OR, or CONJUNCTION operations on its child nodes
  • Signal/Filter node — a terminal node that evaluates market data and returns a direction (Long, Short, Any, or None)
  • Action node — performs auxiliary calculations without affecting the resulting direction, but can return None to terminate tree evaluation

Logic Operations

Each logical node combines the directions of its children using one of three operations:

OperationInputResult
ANDNone, NoneNone
ANDLong, NoneNone
ANDLong, ShortNone
ANDLong, LongLong
ANDLong, AnyLong
ORNone, NoneNone
ORLong, NoneLong
ORLong, ShortNone
ORLong, AnyLong
CONJUNCTIONNone, NoneNone
CONJUNCTIONLong, NoneLong
CONJUNCTIONShort, LongAny
CONJUNCTIONLong, AnyAny

AND requires all children to agree on direction. OR accepts any single valid direction. CONJUNCTION combines differing directions into Any — useful when you want coherent signals in a range without requiring a specific order.

Short-Circuit Evaluation

By default, AND nodes use short-circuit evaluation: if the first child returns None, the remaining children are skipped. This improves performance but makes the result dependent on the order of signals in the tree. For ranged patterns where signal order matters, consider using a CONJUNCTION root node with separate Long and Short branches.

Tree Structure Rules

  • The root node is always a logical node
  • Logical nodes cannot be terminal (leaf) nodes — they must have children
  • Signal/filter nodes must be terminal nodes
  • The signals tree must have at least one signal node
  • The filters tree root can be terminal (empty), meaning no filters are used

Invalid tree structures raise an error on strategy initialization.

Signals

A signal processes incoming market data and determines a trading direction based on indicator values. Each signal has:

  • Direction — the current output: Long, Short, Any, or None
  • Entry price — an optional price for opening the position
  • Chart range — the bar/price range where the signal was validated (for pattern localization)

Calculation Modes

ModeDescription
OnEachTickSignal is recalculated on every incoming tick
OnBarCloseSignal is recalculated only when a bar closes
NotApplicableUsed for Level 2 (DOM) signals that process market depth events independently

Market Data Sources

SourceDescription
Level1Order flow data (tick data) — used by most signals
Level2Market depth / DOM data — used by DOM-based signals
CustomCustom event source

Built-in Signals

The framework includes these ready-to-use signals:

SignalIndicatorDescription
TradesClusterSignalmzBigTradeDetects a cluster of trades at a given side within a bar/price range
BigTradeSignalmzBigTradeLONG for sell trades, SHORT for buy trades
FootprintImbalanceSignalmzFootprintLONG for buy imbalances, SHORT for sell imbalances
FootprintAbsorptionSignalmzFootprintLONG for sell absorptions, SHORT for buy absorptions
FootprintSRZonesSignalmzFootprintSearches for S/R zones (imbalance or absorption type)
ClusterZonesSignalmzFootprintSearches for consecutive cluster zones in the current bar
BarJoinedPOCsSignalmzFootprintValidates if the bar has a given number of joined POCs
BarDeltaSignalmzFootprintLONG for positive delta, SHORT for negative delta
CumulativeDeltaSignalmzFootprintLONG for positive session cumulative delta, SHORT for negative
DeltaRateSignalmzFootprintLONG for positive delta rate, SHORT for negative delta rate
OrderflowBarMetricsSignalmzFootprintSignal based on orderflow metrics of the bar
DeltaDivergenceSignalmzDeltaDivergenceDetects delta-price divergence patterns
RelativeToProfileSignalmzVolumeProfileSHORT if price above VWAP/VAH, LONG if below VWAP/VAL
VolumeProfileDeltaSignalmzVolumeProfileLONG for negative profile delta, SHORT for positive
DOMImbalanceSignalmzMarketDepthDetects DOM imbalance; entry at best bid (LONG) or best offer (SHORT)
DOMBlockSignalmzMarketDepthDetects large limit orders in the DOM
BarIcebergsSignalmzVolumeDeltaLONG for icebergs on bid side, SHORT for icebergs on ask side
BarVolumeSignalVolumeValidates if bar volume meets a minimum threshold
BarMetricsSignalPrice ActionSignal based on price action patterns inside the bar
BarWickSignalOHLCLONG for bars with low wick only, SHORT for bars with high wick only
UpDownBarSignalOHLCLONG for bullish bars, SHORT for bearish bars

Custom signals can be created by extending the Signal base class.

Filters

Filters are structurally identical to signals — they process market data and return a direction. The distinction is organizational: filters are placed in the filters tree, which is evaluated after the signals tree validates. This separation lets you define primary trading conditions as signals and confirmations as filters.

For example, a strategy might use big-trade clusters and absorption zones as signals, and DOM imbalance as a filter to confirm the entry direction before opening a position.

Entry Configuration

When a pattern validates, a position is opened according to the entry configuration.

Order Methods

MethodDescription
MarketSubmits a market order for immediate execution
LimitSubmits a limit order at the price generated by the pattern, with optional shift in ticks
StopLimitSubmits a stop-limit order

For limit orders, additional options include:

  • Limit entry shift — offset in ticks added to the pattern-generated price
  • Limit entry price chase — moves the pending limit order tick-by-tick as price moves away
  • Cancel limit order — cancels unfilled limit orders after a specified number of ticks, bars, or milliseconds

Protective Orders

Order TypeDescription
Stop LossCloses the position at a specified number of ticks or a fixed price from entry
Profit TargetTakes profit at a specified number of ticks or a fixed price from entry
Break-evenMoves the stop loss to the entry price (plus an optional shift) after price moves a specified number of ticks in your favor
TrailA trailing stop that activates after a specified profit threshold, then follows price at a defined distance and step size

Each entry also specifies a Quantity (number of contracts) and a Signal name for order identification.

Position Management

ATM Modes

MZpack strategies support two ATM (Advanced Trade Management) approaches:

ModeDescription
MZpack ATMUses MZpack's built-in order management with Entry, Trail, and Break-even classes
NinjaTrader ATMDelegates order management to a NinjaTrader ATM strategy template
SettingDefaultDescription
Position managementMZpackWhich layer manages the position — MZpack (built-in Entry, Trail, and Break-even classes) or NinjaTraderATM (a NinjaTrader ATM strategy template)
NinjaTrader ATM: template(none)Name of the NinjaTrader ATM template to apply. The drop-down lists the ATM templates installed in NinjaTrader. Applies when Position management = NinjaTraderATM
NinjaTrader ATM: entry methodMarketOrder type used to open the ATM position — Market, Limit, or StopLimit. Applies when Position management = NinjaTraderATM

Opposite Pattern Action

When a position is open and the pattern validates in the opposite direction, the strategy's behavior is controlled by the OppositePatternAction setting:

ActionDescription
NoneKeep the current position, ignore the opposite signal
CloseClose the current position
ReverseClose the current position and open a new one in the opposite direction
UnmanagedSignals continue to be calculated after entering a position — can be used for scaling in

Position Lifecycle

The position progresses through these states:

StateDescription
FlatNo position open
EntrySubmittingEntry order has been submitted
LongLimitPending / ShortLimitPendingLimit order is pending, not yet filled
LongMarketPending / ShortMarketPendingMarket order is pending
Long / ShortPosition is filled

Trading Times

The strategy can be restricted to specific trading hours using the Trading Times setting:

  • In Auto mode, no entries are made outside trading times. Open positions are closed and pending orders are cancelled when trading times end.
  • In Manual mode, trading times do not affect the strategy — signals continue to display regardless of the time.

Risk Management

Risk management enforces daily limits that apply at the account level (not per instrument). All limits reset overnight if the strategy is not in a position.

LimitDescription
DailyLossLimitMaximum loss allowed in a single day. The strategy stops trading when realized + unrealized PnL reaches this negative threshold.
DailyMaxDrawdownA trailing daily loss limit. Tracks the peak account value for the day and stops trading if the account drops by this amount from the peak.
DailyProfitLimitMaximum profit target for the day. The strategy stops trading when realized + unrealized PnL reaches this positive threshold.
DailyTradesLimitMaximum number of trades (filled entries) allowed per day.

When a risk limit is reached, the current position is closed automatically and no further entries are made for the rest of the day.

note

Risk management tracks both realized and unrealized PnL. An open position's floating profit or loss counts toward daily limits.

Backtesting

MZpack strategies can be backtested in the NinjaTrader Strategy Analyzer (order flow strategies, using Tick Replay) or against a Market Replay connection (strategies that need bid/ask volumes or the order book). Enable the Backtesting parameter — or set EnableBacktesting = true in code — so the strategy runs in the historical state.

See Backtesting for the full workflow, Tick Replay prerequisites, and how to choose between the two paths.

Visualization

The strategy framework provides several visualization options, configured in the Visual category of the strategy properties.

Pattern on Chart

Enable Pattern on chart: show to display a colored area on the chart when a pattern validates. The area is drawn over the bar/price range in which the pattern was found, with separate strokes for the signals portion and the filters portion, and for Long and Short directions.

SettingDefaultDescription
Pattern on chart: showtrueDraw the validated pattern's area on the chart
Pattern on chart: Buy signal(s)Green, solid, 3 px, 25 % opacityStroke of the area covering the signals of a Long pattern
Pattern on chart: Sell signal(s)Red, solid, 3 px, 25 % opacityStroke of the area covering the signals of a Short pattern
Pattern on chart: Buy filter(s)Green, solid, 3 px, 10 % opacityStroke of the area covering the filters of a Long pattern
Pattern on chart: Sell filter(s)Red, solid, 3 px, 10 % opacityStroke of the area covering the filters of a Short pattern

Entry/Exit Markup

Enable Entry/Exit: markup to display entry and exit markers on the chart. This is most useful in Manual operating mode, where it shows where the strategy would have entered and exited.

SettingDefaultDescription
Entry/Exit: markupNoneMarker style drawn at the entry and exit price — None, Marker (triangle only), or MarkerAndText (triangle plus the entry/exit label)
Entry/Exit: Buy markerLimeMarker color for Long entries and exits
Entry/Exit: Sell markerRedMarker color for Short entries and exits

Pattern Dashboard

Enable Pattern dashboard: show to display a real-time view of the decision tree on the chart, showing the current state (direction) of each signal and filter on every bar. This is particularly useful in Manual mode for discretionary trading.

The dashboard is a grid: one row per signal or filter node, one column per bar. Each cell is stroked with the color of the direction that node returned on that bar.

SettingDefaultDescription
Pattern dashboard: showfalseShow the decision-tree dashboard on the chart
Pattern dashboard: LONGGreenCell stroke when the node returned Long
Pattern dashboard: SHORTRedCell stroke when the node returned Short
Pattern dashboard: ANYRoyalBlueCell stroke when the node returned Any (both directions)
Pattern dashboard: NONEDimGrayCell stroke when the node returned None (no direction)
Pattern dashboard: legendfalseShow the legend that names the signal or filter in each row
Pattern dashboard: positionBottomEdge of the chart panel the grid is anchored to — Top or Bottom
Pattern dashboard: offset, px0Vertical offset from the anchor edge in pixels; positive values move the grid up, negative values move it down
Pattern dashboard: row height, px28Height of one dashboard row in pixels, range: 10–100
Pattern dashboard: fontArial 12Font of the dashboard cell and legend text

Partially Visible Mode

When a strategy uses multiple indicators, the chart can become cluttered. Partially Visible mode shows only the indicator plots that are relevant to validated signals. Three strategy indicator classes support this mode:

Strategy IndicatorPartially Visible Property
StrategyBigTradeIndicatorITrade.View.PartiallyVisible
StrategyFootprintIndicatorIFootprintBar.PartiallyVisible
StrategyMarketDepthIndicatorIMarketDepthBlock.PartiallyVisible

Toggle Partially Visible mode by clicking the "eye" button next to the indicator name in the chart. See Algo Strategy — Partially Visible for a full code sample.

Logging

MZpack strategies include a built-in logging system for debugging and monitoring.

Log Levels

Log level is a bitmask — multiple levels can be combined:

LevelDescription
NONENo logging
NV_PATTERN_OBCLog not-validated pattern state on each bar close (for debugging)
V_PATTERNLog pattern when validated
ORDERLog order events: submitted, working, filled, partially filled, cancelled, rejected
ENTRYLog entry details
POSITIONLog position state changes
PROPERTIESLog strategy properties on initialization
ALLAll of the above

Log Targets

TargetDescription
NoneLogging disabled
NinjaScriptOutputNinjaTrader Output window
FileText file in Documents\NinjaTrader 8\mzpacklog\
AllBoth Output window and file

Logging Settings

Each Log: toggle sets one bit of the log level bitmask described above.

SettingDefaultDescription
Log: targetNinjaScriptOutputWhere log records are written — None, File, NinjaScriptOutput, or All
Log: Validated PATTERNtrueLog each pattern when it validates (V_PATTERN)
Log: not Validated PATTERN on Bar ClosefalseLog the state of patterns that did not validate, on each bar close (NV_PATTERN_OBC). Verbose — intended for debugging a pattern that never fires
Log: ORDERfalseLog order events: submitted, working, filled, partially filled, cancelled, rejected (ORDER)
Log: ENTRYtrueLog entry details (ENTRY)
Log: POSITIONtrueLog position state changes (POSITION)
Log: PROPERTIEStrueLog the strategy properties on initialization (PROPERTIES)
Log: timetruePrefix each log record with a timestamp
note

Logging is disabled automatically in the Strategy Analyzer — the log target and level are forced to None while the strategy runs there.

Alerts

The strategy can play a sound when a signal or a pattern validates. Alerts fire in real time only.

SettingDefaultDescription
Signal alert: enablefalsePlay a sound whenever an individual signal validates
Signal alert: soundmzpack_alert1.wavSound file for the signal alert
Entry pattern alert: enablefalsePlay a sound when an Entry pattern validates
Entry pattern alert: soundmzpack_alert5.wavSound file for the entry pattern alert
Exit pattern alert: enablefalsePlay a sound when an Exit pattern validates
Exit pattern alert: soundmzpack_alert6.wavSound file for the exit pattern alert
tip

See Sound Files for the full list of pre-installed sounds and how to add custom WAV files.

Control Panel

The optional Control Panel is a panel on the right side of the chart that provides runtime controls for the strategy. It has two tabs: Properties, a property grid for the strategy's settings, and a tab named after the strategy holding its custom controls — operating mode switches, direction selectors, and any control the strategy adds. The panel is disabled while historical data is loading.

SettingDefaultDescription
Control Panel: showfalseShow the control panel on the right side of the chart
Control Panel: width300Panel width in pixels
Control Panel: show propertiestrueInclude the Properties tab with the strategy property grid. Disable to show only the strategy's own controls

Multi-Data Series

Strategies can use multiple timeframes or instruments by adding additional data series. Each MZpack indicator and signal can be attached to a specific data series by index, enabling multi-timeframe analysis within a single strategy.