Quick Answer
Object reference not set to an instance of an object is the message of a NullReferenceException. It is not a compile error: the cBot builds, starts, and then stops (or logs an error in a handler) at the moment it tries to use something that is null, that is, a variable that points to nothing. In a cBot it happens in four places: a lookup that found nothing (Positions.Find when no position matches), a field that was never assigned (an indicator that is declared but not created in OnStart), a value read too early (a lookup done before the position exists) and a nullable value used without a check (StopLoss, which can be empty).
The fix is always the same idea: find out which variable is null on that line, and decide what the cBot should do when it is. Then check for null before you use it, and assign every field before the first handler runs.
From the author: I build cBots in cTrader Automate and convert strategies from Pine Script and MQL5 to C#. In MQL5, a missing handle gives
INVALID_HANDLE, an array read out of range gives an error and a position lookup givesfalse. In C#, the same mistake becomes anulland a crash that points at a line that looks fine.
Key Facts
| What you see | Usual cause | Fix |
|---|---|---|
| Crash on position.Pips | Positions.Find(...) found no position | Check position != null first |
| Crash on _sma.Result | The indicator was never created | Assign it in OnStart |
| Find returns null after you opened a trade | The lookup ran before the trade | Look up when you need the value |
| InvalidOperationException on StopLoss.Value | The stop loss is empty (double?) | Check HasValue, or use ?? |
| Crash on result.Position.Id | The order failed and there is no position | Check result.IsSuccessful first |
| Crash only on some runs | A field is set in one code path only | Set it at declaration or in OnStart |
What the Error Means
A variable of a reference type (an indicator, a Position, a Bars object, a string) holds either an object or null. Using a member of null (variable.Something) throws the exception, and C# does not warn you at build time. In cTrader, an unhandled exception in a handler is logged for the cBot with the handler name and the message, and the handler stops at that line. Read the log line: it names the method, and often the line.
The Broken cBot
This cBot only prints. It has no order calls. Each marked line can throw a NullReferenceException:
using cAlgo.API;
using cAlgo.API.Indicators;
namespace cAlgo.Robots
{
[Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
public class BrokenBot : Robot
{
private SimpleMovingAverage _sma; // declared, never created
protected override void OnBar()
{
var position = Positions.Find("MyBot", SymbolName); // null when there is no such position
Print("Pips {0}", position.Pips); // NullReferenceException when position is null
Print("SMA {0}", _sma.Result.Last(1)); // NullReferenceException: _sma is null
}
}
}
The log shows the handler and the message Object reference not set to an instance of an object. In a real cBot, the first line that throws stops the handler, so the second problem only shows after the first is fixed.
Cause 1: A Lookup That Found Nothing
Positions.Find(label, symbolName) looks for an open position with that label. According to the cTrader reference, it returns a single Position, and when no position matches, community answers from cTrader staff treat the result as null. Check the reference and the behavior in your version, then guard every use:
var position = Positions.Find("MyBot", SymbolName);
if (position == null)
{
Print("No open position for MyBot");
return;
}
Print("Pips {0}", position.Pips);
For several matches, FindAll returns an array that you can loop over. An empty loop is safe. Note that the reference lists the older Find(label, Symbol) overloads as deprecated and replaced by a version that takes the symbol name as a string, so prefer the string version.
Cause 2: A Field That Was Never Assigned
A field such as private SimpleMovingAverage _sma; is null until you assign it. Create indicators in OnStart, before any handler that uses them:
protected override void OnStart()
{
_sma = Indicators.SimpleMovingAverage(Bars.ClosePrices, 14);
}
If OnStart throws before it reaches the line (for example because an earlier line failed), the field stays null, and every later handler crashes. Keep OnStart short, put the indicator creation first, and print a line at the end of it.
Cause 3: A Lookup Done Too Early
A known case from the cTrader community: the cBot stored the result of Positions.Find("b1") in a variable before it opened the trade, so the variable stayed null even after the position existed. The answer from cTrader staff was to call Find at the moment you need the value, inside the check:
// not like this: the value is read once and stays null
// var buy = Positions.Find("b1", SymbolName);
if (Positions.Find("b1", SymbolName) == null)
{
// no buy position yet: open one here
}
A stored Position is a snapshot of the position as it was found. For the current state, look it up again.
Cause 4: A Nullable Value Without a Check
Position.StopLoss and TakeProfit are double?: they hold a number or nothing, and the reference lists them as read only. Reading .Value on an empty one throws an InvalidOperationException, a close relative of the null error, and comparing or calculating with an empty value gives wrong results:
double sl = position.StopLoss ?? 0.0; // 0.0 when there is no stop loss
if (position.StopLoss.HasValue)
Print("Stop at {0}", position.StopLoss.Value);
else
Print("No stop loss");
Choose the fallback on purpose. 0.0 can mean "no stop" in your logic, and then a calculation with it must handle that case.
Cause 5: The Result of a Failed Order
An order call returns a result object. When the order fails, the Position inside the result can be empty, and result.Position.Id crashes. Check the success first, as in the CS0029 guide:
var result = ExecuteMarketOrder(TradeType.Buy, SymbolName, volume, "MyBot");
if (!result.IsSuccessful)
{
Print("Order failed: {0}", result.Error);
return;
}
Print("Opened position {0}", result.Position.Id);
The Fixed cBot
using cAlgo.API;
using cAlgo.API.Indicators;
namespace cAlgo.Robots
{
[Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
public class FixedBot : Robot
{
private SimpleMovingAverage _sma;
protected override void OnStart()
{
_sma = Indicators.SimpleMovingAverage(Bars.ClosePrices, 14);
Print("Started, SMA created");
}
protected override void OnBar()
{
if (Bars.Count < 20)
return;
var position = Positions.Find("MyBot", SymbolName);
if (position == null)
Print("No open position for MyBot");
else
Print("Pips {0}, stop {1}", position.Pips, position.StopLoss ?? 0.0);
Print("SMA {0}", _sma.Result.Last(1));
}
}
}
The bot only prints. The Bars.Count check at the top avoids the runtime error described in cBot index out of range. Compare the values with the chart, and test on a demo account before you add orders.
How to Find the Null Variable Fast
- Read the log line: the handler name and the line.
- Look at each
.on that line. The word before every dot could be null. - Print the suspects with
Print("x is null: {0}", x == null);before the line. - Use the debugger in cTrader Automate (a breakpoint on the line) and hover over the variables. Check how debugging works in your version.
- Fix the cause, not only the symptom: assign the field, guard the lookup, or check the result.
Similar Errors
| Error | Message | What it means |
|---|---|---|
| NullReferenceException | Object reference not set to an instance of an object | A null was used |
| InvalidOperationException | Nullable object must have a value | .Value read on an empty double? |
| ArgumentOutOfRangeException | Index was out of range | An index beyond the data |
| CS0165 | Use of unassigned local variable | A variable is read before it has a value |
| CS0103 | The name 'x' does not exist in the current context | A name is unknown |
Checklist: What to Check When Your cBot Crashes With a Null Error
- Read the log for the handler and the message.
- Find the variable before each dot on the failing line.
- Check every field is assigned in
OnStart, before the first handler. - Guard every
Findwith!= null, and look it up when you need it. - Check
HasValueor use??forStopLossandTakeProfit. - Check
IsSuccessfulbefore you use the position of an order result. - Print the values and build again.
- Test on a demo account before the cBot trades with real money.
Common Mistakes
- Declaring an indicator field and forgetting to create it.
- Using the result of
Findwithout a null check. - Storing a lookup in a field and expecting it to stay current.
- Reading
.Valueon an empty nullable. - Using
result.Positionafter a failed order. - Putting a lot of code in
OnStart, so that a failure stops the creation of fields below it.
FAQ
Related Guides
- cTrader cBot crash: index was out of range: the other common runtime error after the cBot builds.
- cTrader C# error CS0165: a variable is read before it has a value.
- cTrader C# error CS0029: the order result and its position.
- cTrader C# error CS0120: a member that needs a cBot object is used without one.
- cTrader C# error CS1061: the object is found, the member is not.
- cTrader C# error CS0161: a method that does not return on every path.
- Pine Script strategy.entry to cTrader C#: orders, labels and position lookups.
- Pine Script strategy.exit to cTrader C#: stop loss and take profit in pips.
- What to check in a trading bot before going live: a pre-live checklist for stops, lot size, spread and trade results.
- cTrader order failed: TradeResult error codes: read
IsSuccessfulandErrorwhen an order call is refused. - cTrader cBot crashed: Error # with a long number: find the exception behind a crash.
Fix Compile Errors Without Guessing
If a cBot or an Expert Advisor does not build, paste the code and the error message into the CodeFlowOS Error Fixer. It suggests a minimal fix, explains each error and shows what changed. A fix uses 1 credit, with up to 3 attempts included, and the compiler check is optional. Outputs are not guaranteed, and code that compiles can still have wrong trading logic, so always review the result. Before a bot goes live, the Code Review is free during the early-bird period. CodeFlowOS also converts strategies between Pine Script, MQL5 and cTrader C#: try the converter page.
This article is educational. It does not describe trading performance and is not financial advice. Always build the code in cTrader Automate and backtest it before using it on a live account.