Skip to main content

Algo.Strategy

Algo.Strategy is the pattern-oriented strategy engine. You define patterns containing signals and filters organized into decision trees. The framework evaluates them on each market event and manages entries, exits, and trailing stops automatically.

Namespace: MZpack.NT8.Algo Inheritance: Strategy : ViewModelBase Source: [INSTALL PATH]/API/Strategy.cs

Architecture

Strategy
├── Patterns
│ ├── Entry Pattern
│ │ ├── SignalsTree (Decision Tree)
│ │ │ └── Root LogicalNode
│ │ │ ├── Signal A (AND)
│ │ │ ├── Signal B (AND)
│ │ │ └── OR Node
│ │ │ ├── Signal C
│ │ │ └── Signal D
│ │ └── FiltersTree (Decision Tree)
│ │ └── Root LogicalNode
│ │ └── Filter X
│ ├── Exit Pattern
│ │ └── SignalsTree
│ │ └── Signal E
│ ├── Reversal Pattern
│ ├── ScaleIn Pattern
│ └── ScaleOut Pattern
├── Positions
│ └── Position
│ └── Entry[] (Market / Limit / StopLimit)
│ └── Exit / Trail — stop loss, profit target, trailing stop
├── TradingTimes[]
└── RiskManagement

Core Properties

PropertyTypeDescription
NamestringStrategy name
MZpackStrategyMZpackStrategyBaseParent NinjaTrader strategy
PatternsPatternsCollection of entry/exit patterns
PatternPatternEntry pattern (shortcut to Patterns.Get(PatternType.Entry))
ExitPatternPatternExit pattern (shortcut)
PositionsPositionsPosition management collection
TradingTimesList<TradingTime>Time windows when trading is allowed
RiskManagementRiskManagementDaily limits (loss, drawdown, profit, trade count)
SessionBreakboolReset strategy on new session (default: true)
IsOpeningPositionEnabledboolAllow opening positions (default: true)
OppositePatternActionOppositePatternActionWhat to do when opposite signal fires
DashboardDashboardViewDashboard visualization

Initialization

Use Initialize() to wire up patterns, entries, and positions:

// Basic: entry pattern only
strategy.Initialize(entryPattern);

// Entry + exit patterns
strategy.Initialize(entryPattern, exitPattern);

// Entry + exit + custom entries
strategy.Initialize(entryPattern, exitPattern, new Entry[] { entry1, entry2 });

// Entry + exit + entries + attempt count
strategy.Initialize(entryPattern, exitPattern, entries, attempts: 1);

Lifecycle

OnBarUpdate / OnMarketData / OnMarketDepth


Pattern.OnMarketEvent(e, source, isFirstTickOfBar)

├── SignalsTree.OnMarketEvent() ← evaluate signals decision tree
│ └── each Signal.OnMarketEvent()
│ └── SignalCalculate → direction (Long / Short / None)

├── FiltersTree.OnMarketEvent() ← evaluate filters (if signals passed)
│ └── each Filter.OnMarketEvent()

▼ pattern validated?

├── YES → Strategy.OnEntryPatternValidated()
│ └── Position.Enter(direction, time)
│ └── Entry.Submit() → NinjaTrader order

└── NO → Strategy.OnEntryPatternNotValidated()

Virtual Methods (Override Points)

MethodWhen to Override
OnValidateEntryPatternFilter(object e, MarketDataSource source)Add custom entry validation logic beyond the decision tree
OnValidateExitPatternFilter(object e, MarketDataSource source)Add custom exit validation logic
OnPositionOpenFilter(DateTime time)Block position opening based on custom conditions
OnEntryPatternValidated(Pattern sender, DateTime time)Custom action when entry pattern validates
OnExitPatternValidated(Pattern sender, DateTime time)Custom action when exit pattern validates
OnOrderFilled(Order order)Custom logic when an order fills
OnOrderUpdate(Order order, OrderState orderState)Custom logic on order state changes
OnPositionUpdate(Position, double, int, MarketPosition)Custom logic on position changes
OnRender(ChartControl, ChartScale)Custom chart rendering

Logging

MethodDescription
Log(LogLevel level, DateTime time, string text)Write to log if level is enabled
LogHeader()Log strategy header info
LogNinjaScriptProperties()Log all NinjaScript properties

Enums

OppositePatternAction

ValueDescription
NoneKeep current position, ignore opposite signal
CloseClose current position
ReverseClose current position and open opposite
UnmanagedPosition direction managed by signals

LogLevel (Flags)

ValueDescription
NONENo logging
NV_PATTERN_OBCNot-validated pattern on bar close
V_PATTERNValidated pattern
ORDEROrder events
ENTRYEntry events
POSITIONPosition state changes
PROPERTIESNinjaScript properties
ALLAll of the above

LogTarget (Flags)

ValueDescription
NoneNo output
FileWrite to log file
NinjaScriptOutputWrite to NinjaTrader Output window
AllBoth file and output window

Example: Algo.Strategy with BigTradeSignal

public class MyAlgoStrategy : MZpackStrategyBase
{
StrategyBigTradeIndicator btIndicator;

public MyAlgoStrategy()
{
OnCreateIndicators = () =>
{
btIndicator = new StrategyBigTradeIndicator(this, "BT");
btIndicator.TradeFilterEnable = true;
btIndicator.TradeFilterMin = 100;
return new List<TickIndicator> { btIndicator };
};

OnCreateAlgoStrategy = () =>
{
var strategy = new Strategy("BigTradeAlgo", this);
strategy.OppositePatternAction = OppositePatternAction.Close;
strategy.SessionBreak = true;

// Create entry signal
var signal = new BigTradeSignal(strategy,
MarketDataSource.Level1,
SignalCalculate.OnEachTick);

// Create entry pattern with AND logic
var entryPattern = new Pattern(strategy,
Logic.And, new Range(),
isShortCircuitANDEvaluation: true);
entryPattern.Signals.Root.Add(signal);

// Create entries with stop loss and profit target
var entry = new Entry(strategy);
entry.Quantity = 1;
entry.EntryMethod = EntryMethod.Market;
entry.StopLossTicks = 20;
entry.ProfitTargetTicks = 40;

strategy.Initialize(entryPattern, null,
new Entry[] { entry }, attempts: 1);
return strategy;
};
}
}

See Also