Logging in Strategy
In StockSharp, the Strategy class inherits from BaseLogReceiver, which allows you to use built-in tools to log all actions and events occurring during the operation of a trading strategy.
Logging Levels
StockSharp supports the following logging levels (listed in order of increasing importance):
- Verbose - the most detailed logging level for tracing
- Debug - messages for debugging
- Info - regular informational messages
- Warning - warnings about potential problems
- Error - error messages
Logging Methods in Strategy
The strategy provides the following methods for writing messages to the log:
LogVerbose
The LogVerbose method is designed to record detailed messages for tracing:
protected override void OnStarted(DateTimeOffset time)
{
base.OnStarted(time);
LogVerbose("Strategy started with parameters: Long SMA={0}, Short SMA={1}", LongSmaLength, ShortSmaLength);
// ...
}
LogDebug
The LogDebug method is used for debug messages:
private void ProcessCandle(ICandleMessage candle)
{
LogDebug("Processing candle: {0}, Open={1}, Close={2}, High={3}, Low={4}, Volume={5}",
candle.OpenTime, candle.OpenPrice, candle.ClosePrice, candle.HighPrice, candle.LowPrice, candle.TotalVolume);
// ...
}
LogInfo
The LogInfo method is used for regular informational messages:
private void CalculateSignal(decimal shortSma, decimal longSma)
{
bool isShortGreaterThanLong = shortSma > longSma;
LogInfo("Signal: {0}, Short SMA={1}, Long SMA={2}",
isShortGreaterThanLong ? "Buy" : "Sell", shortSma, longSma);
// ...
}
LogWarning
The LogWarning method is used to record warnings:
public void RegisterOrder(Order order)
{
if (order.Volume <= 0)
{
LogWarning("Attempt to register an order with invalid volume: {0}", order.Volume);
return;
}
// ...
}
LogError
The LogError method is used to record error messages:
try
{
// Some actions
}
catch (Exception ex)
{
LogError("Error while performing operation: {0}", ex.Message);
Stop();
}
There is also an overload LogError that directly accepts an exception:
try
{
// Some actions
}
catch (Exception ex)
{
LogError(ex);
Stop();
}
Configuring the Logging Level
The Strategy class contains a LogLevel property that determines which messages will be written to the log:
// Set the logging level for the strategy
strategy.LogLevel = LogLevels.Info;
With the selected logging level, only messages of that level and higher levels will be recorded. For example, if LogLevels.Info
is set, Verbose and Debug messages will be ignored.
LogLevel Parameter
For convenient logging level configuration in the strategy constructor, you can add a parameter:
public class SmaStrategy : Strategy
{
private readonly StrategyParam<LogLevels> _logLevel;
public SmaStrategy()
{
_logLevel = Param(nameof(LogLevel), LogLevels.Info)
.SetDisplay("Logging Level", "Level of log message detail", "Logging Settings");
}
public override LogLevels LogLevel
{
get => _logLevel.Value;
set => _logLevel.Value = value;
}
// ...
}
Examples of Use in a Real Strategy
Logging Strategy Start and Stop
protected override void OnStarted(DateTimeOffset time)
{
base.OnStarted(time);
LogInfo("Strategy {0} started at {1}. Instrument: {2}, Portfolio: {3}",
Name, time, Security?.Code, Portfolio?.Name);
// ...
}
protected override void OnStopped()
{
LogInfo("Strategy {0} stopped. Position: {1}, P&L: {2}",
Name, Position, PnL);
base.OnStopped();
}
Logging Trades
protected override void OnNewMyTrade(MyTrade trade)
{
LogInfo("{0} {1} {2} at price {3}. Volume: {4}",
trade.Order.Direction == Sides.Buy ? "Bought" : "Sold",
trade.Order.Security.Code,
trade.Order.Type,
trade.Trade.Price,
trade.Trade.Volume);
base.OnNewMyTrade(trade);
}
Logging Order Registration Errors
protected override void OnOrderRegisterFailed(OrderFail fail, bool calcRisk)
{
LogError("Order registration error {0}: {1}",
fail.Order.TransactionId, fail.Error.Message);
base.OnOrderRegisterFailed(fail, calcRisk);
}
Viewing Logs
Messages written to the strategy log can be viewed:
- In the Designer program on the "Logs" panel
- In log files, if FileLogListener is configured
- In the user interface through LogControl, if GuiLogListener is used