Learn NinjaScript: Adding Button Controls to the Chart
Settings-dialog toggles are fine for things that rarely change, but some actions want a one-click button right on the chart: “recalculate this level now”, “freeze what I’m seeing”, “clear the zones”, “reset the session VWAP.” NT doesn’t give you a first-class API for that — but the chart is a WPF control, and WPF buttons work fine inside an indicator when you know where to attach them and how to clean up without leaving ghosts behind.
This post covers the full pattern: picking the right host container, creating and attaching the button on State.DataLoaded, the Dispatcher marshaling that keeps NT’s background threads from blowing up the UI, and the cleanup in State.Terminated that prevents stacked ghost buttons after a recompile. The anchor is MySma with a Reset button that clears the plot and starts fresh.
⚙️ Where the Button Lives
The chart is a ChartControl, and it has a ChartPanels collection — one panel per sub-chart area. For an on-chart button, the right host is usually a Grid that NT provides at the top of the chart area, accessible via ChartControl.Parent cast to a Grid. You add your button as a child of that grid and position it with the WPF alignment properties.
For indicators that live in a sub-panel, the host changes: the panel itself (ChartPanels[PanelIndex]) is the container. This post focuses on the price-panel case, which covers the majority of use cases — freeze/reset/recompute-style buttons for overlay indicators.
🏗️ Adding the Button
The creation itself is pure WPF — a Button, some content, some styling, a click handler. The NT-specific part is when and where to add it:
private Button resetButton;
private Grid chartGrid;
protected override void OnStateChange()
{
if (State == State.DataLoaded)
{
// Capture the chart host grid once data has loaded.
chartGrid = ChartControl.Parent as Grid;
if (chartGrid == null) return;
resetButton = new Button
{
Content = "Reset SMA",
Width = 92,
Height = 24,
Margin = new Thickness(8, 28, 8, 0),
HorizontalAlignment = HorizontalAlignment.Left,
VerticalAlignment = VerticalAlignment.Top,
Background = Brushes.Transparent,
Foreground = Brushes.Gainsboro,
BorderBrush = new SolidColorBrush(Color.FromArgb(120, 148, 163, 184)),
Cursor = Cursors.Hand,
FontSize = 11,
FontWeight = FontWeights.SemiBold
};
resetButton.Click += OnResetClicked;
// Add from the UI thread — next section.
ChartControl.Dispatcher.InvokeAsync(() => chartGrid.Children.Add(resetButton));
}
}
State.DataLoaded is the right hook — by that time ChartControl is alive, the host grid exists, and the indicator’s data is ready to be manipulated. SetDefaults fires too early (no chart yet); Historical fires too often.
🛡️ Dispatcher-Safe Adds
NT’s OnStateChange doesn’t always run on the UI thread. If you call chartGrid.Children.Add(button) directly from a background thread, WPF throws a cross-thread exception — InvalidOperationException: The calling thread cannot access this object because a different thread owns it. The fix is to marshal the mutation through the UI thread’s dispatcher, which every WPF control exposes as .Dispatcher.
Use InvokeAsync for adds you don’t need to block on, Invoke if you need a return value or must wait. Either dispatches the closure onto the UI thread and runs it there. This same pattern matters for any mutation of WPF state from NinjaScript background threads — cleaning up the button, changing its content, toggling visibility.
🧹 Cleanup
Recompile cycles are the ghost-button generator. When the user hits F5 in the NinjaScript editor, NT disposes the indicator instance and creates a new one — but the button you added to chartGrid.Children sticks around because nobody removed it. Three recompiles later there are four copies stacked.
protected override void OnStateChange()
{
// ... DataLoaded branch ...
else if (State == State.Terminated)
{
if (resetButton != null && chartGrid != null)
{
resetButton.Click -= OnResetClicked;
ChartControl?.Dispatcher.InvokeAsync(() =>
{
chartGrid.Children.Remove(resetButton);
});
}
resetButton = null;
chartGrid = null;
}
}
private void OnResetClicked(object sender, RoutedEventArgs e)
{
// Mark a reset and re-process bars on the background thread.
resetRequested = true;
ChartControl.InvalidateVisual();
}
Three things happen in Terminated: unwire the click event (prevents the new indicator instance from getting a stale callback), remove the button from the grid via the dispatcher, and null out the captured references so the old WPF objects can be GC’d. The ChartControl?. null-conditional guards against the rare case where the chart has already torn down.
🛠️ The Anchor Example — MySma With a Reset Button
The click handler sets a resetRequested flag that the next OnBarUpdate reads. Doing mutation work on the UI thread risks jank — any non-trivial recompute should queue up for the background thread:
private bool resetRequested;
protected override void OnBarUpdate()
{
if (CurrentBar < Period) return;
if (resetRequested)
{
for (int i = 0; i < Math.Min(CurrentBar, Values[0].Count); i++)
Values[0].Reset(i);
resetRequested = false;
}
Values[0][0] = SMA(Period)[0];
}
The button, the dispatcher add, the click handler, the cleanup, and the bar-level reset loop — that’s the whole pattern. Swap the SMA reset for whatever state your indicator cares about: clearing a zone list, re-anchoring a VWAP, toggling a signal filter on or off.
📝 Pitfalls Checklist
- Adding the button without dispatcher marshaling. Cross-thread
InvalidOperationExceptionthe first timeState.DataLoadedruns off the UI thread. Always route WPF mutations through.Dispatcher.InvokeAsync. - Not removing the button in
Terminated. Every recompile stacks another button. After a day of development you have six copies of “Reset” across the top of the chart. Always pair the add with a remove. - Heavy work in the click handler. Click runs on the UI thread. If you iterate 50,000 bars inside
OnResetClicked, the chart hangs. Set a flag, invalidate, and do the work inOnBarUpdate. - Click handler that throws. An unhandled exception in a button click silently swallows in WPF — users click, nothing happens, no error. Wrap the handler body in
try/catchand log to NT’s output window so you can see why. - Styling out of sync with NT’s theme. A white
Buttonon NT’s dark chart looks like a misplaced dialog control. Use transparent backgrounds, subtle borders, and the same typography weight NT uses — restrained styling blends in rather than shouting for attention. - Capturing
ChartControl.Parentand holding it forever. If the user drags the indicator to a new chart window, the old parent reference is stale and adding to it has no visible effect. Capture onDataLoaded, clear onTerminated; don’t treat the reference as permanent.


