Learn NinjaScript: Saving User Preferences Between Sessions
The user clicks your toggle button. They close the chart. They reopen it the next morning. The toggle is back to its default — their choice is gone. This is what happens when you rely only on [NinjaScriptProperty] serialization for runtime state: NT saves property values into the chart template XML, but anything that changes after the dialog closes (a button press, a counter, a remembered selection) isn’t in that XML and gets reset.
The fix is a small sidecar file: you pick a path under NT’s user-app-data folder, write JSON when the state changes, read JSON when the indicator loads, and the toggle remembers itself across every session forever. This post covers the path conventions, the serialization pattern, when to save, and the pitfalls that bite when you forget you’re doing disk I/O inside an indicator.
⚙️ What NinjaScript Already Persists
Anything decorated with [NinjaScriptProperty] (or [XmlSerialize] alongside it) serializes into the chart template when the user saves — Period, the input color, a boolean toggle in the settings dialog. On next load, NT deserializes the template and populates those properties before OnStateChange(SetDefaults) so by the time your indicator runs, the values are already restored.
What doesn’t persist: private fields, runtime state, anything set after the properties dialog closes. A click handler setting currentMode = Mode.Expanded modifies a private field that NT has no awareness of. Closing and reopening the chart resets it to whatever SetDefaults assigns.
📁 Where to Save Your Own State
NT’s user-app-data directory is %USERPROFILE%\Documents\NinjaTrader 8\. Do not write inside bin/ — that’s regenerated on every compile. The conventional sub-folder for third-party state is db/cache/, but for sanity pick your own namespaced folder: db/cache/mdtPrefs/, one file per indicator class. Per-indicator files are easier to debug than one shared registry.
private static string GetPrefsPath(string indicatorName)
{
string root = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string dir = Path.Combine(root, "NinjaTrader 8", "db", "cache", "mdtPrefs");
Directory.CreateDirectory(dir);
return Path.Combine(dir, indicatorName + ".json");
}
Directory.CreateDirectory is a no-op if the folder already exists, so it’s safe to call on every path resolution. Using Path.Combine (rather than string concatenation with forward slashes) gives you Windows-correct separators.
💾 Serialization Format
JSON is the easy default. It’s human-readable (important when debugging — you can cat the file and see the current state), it’s forward-compatible (adding a new field doesn’t invalidate old saves as long as defaults are sane), and .NET’s System.Text.Json ships in-box so you don’t need a package.
Plain text works for trivial state (a single boolean written as “true\n”); binary is almost never worth it in this context — the files are tiny and human-readability is valuable during development. Avoid XML here; it’s verbose for what amounts to a preferences blob and introduces a second serialization stack alongside NT’s own.
⏱️ When to Save
- On state change (preferred). The moment
resetRequestedflips, the moment the user clicks the toggle button, the moment the remembered selection updates — write the new value to disk immediately. Small files, low frequency; the I/O cost is invisible. - On
State.Terminated(fallback). If the state changes often enough that per-change writes cause noticeable lag, batch updates in memory and write once on terminate. Loses state if NT crashes instead of shutting down cleanly. - Never on every tick. Writing inside
OnBarUpdatefor anything more frequent than bar close is asking for disk thrashing. If you find yourself wanting to save per-tick, you want an in-memory cache, not a file.
🛠️ The Anchor Example — Persisted Toggle on MySma
A tiny MySmaPrefs class for the persisted shape, a load on DataLoaded, a save on every toggle. The indicator remembers whether the user wanted the extended display the next time the chart opens:
using System;
using System.IO;
using System.Text.Json;
private class MySmaPrefs
{
public bool ExtendedDisplay { get; set; } = false;
public int PreferredPeriod { get; set; } = 20;
}
private MySmaPrefs prefs = new MySmaPrefs();
private string prefsPath;
private void LoadPrefs()
{
prefsPath = GetPrefsPath(nameof(MySma));
try
{
if (File.Exists(prefsPath))
{
string json = File.ReadAllText(prefsPath);
var loaded = JsonSerializer.Deserialize<MySmaPrefs>(json);
if (loaded != null) prefs = loaded;
}
}
catch (Exception ex)
{
Print($"MySma: prefs load failed, using defaults. {ex.Message}");
}
}
private void SavePrefs()
{
try
{
string json = JsonSerializer.Serialize(prefs,
new JsonSerializerOptions { WriteIndented = true });
File.WriteAllText(prefsPath, json);
}
catch (Exception ex)
{
Print($"MySma: prefs save failed. {ex.Message}");
}
}
The load path is defensive: file missing is normal on first run, corrupted JSON shouldn’t crash the indicator, both cases fall through to the defaults. The save path logs but doesn’t throw — disk being full or the folder permissions being wrong shouldn’t break the chart. Wiring it into OnStateChange and a click handler closes the loop:
protected override void OnStateChange()
{
if (State == State.DataLoaded)
{
LoadPrefs();
// apply prefs.PreferredPeriod, prefs.ExtendedDisplay to the indicator
}
}
private void OnToggleClicked(object sender, RoutedEventArgs e)
{
prefs.ExtendedDisplay = !prefs.ExtendedDisplay;
SavePrefs();
ChartControl.InvalidateVisual();
}
Close the chart, reopen it a week later, the toggle is still in whichever position the user left it. Same file works across chart templates, workspaces, computer reboots — as long as nameof(MySma) stays stable (don’t rename the class casually) and the JSON file lives at the conventional path.
📝 Pitfalls Checklist
- Writing to disk on every tick. Disk thrashing in live mode. If the state changes frequently, debounce — save on
OnBarUpdatewithIsFirstTickOfBar, not every tick. Better: change the design so the frequent mutation is in-memory and only snapshots to disk on user action. - No “file missing” handling.
File.ReadAllTextthrows if the file doesn’t exist. Wrap inFile.Existsortry/catch, and make sure defaults populate in the missing-file branch. First-run users will have no file; this is normal. - JSON schema changes breaking old saves. Add a field to
MySmaPrefsand old saves deserialize fine (new field gets default value); rename a field and old saves silently drop the renamed value. Add; don’t rename. When you must rename, version the schema or migrate during load. - Hardcoded paths.
C:\Users\me\Documents\NinjaTrader 8\...works on your machine and breaks for every other user. Always resolve viaEnvironment.SpecialFolder.MyDocuments. - Cross-chart collisions. Two instances of
MySmaon different charts share the same prefs file. If that’s the intent (one setting, multiple displays), fine. If the charts need independent state, include the chart title or symbol in the filename — otherwise user interaction on one chart leaks to the other. - Blocking I/O on the UI thread. Saving inside a click handler runs on the UI thread. For a 200-byte JSON blob, the write is instant and fine. For anything large, dispatch the write to a background thread so clicks stay responsive.


