Some checks failed
Build and Test / build (push) Has been cancelled
- Kilocode AI agent rules and guidelines - Setup and implementation guides - Architecture documentation - Build and verification references
6.3 KiB
6.3 KiB
Mandatory Coding Patterns
These patterns MUST be followed in all code you write for the NT8 SDK.
Thread Safety - Dictionary Access
ALL access to shared dictionaries MUST use locks.
❌ WRONG - No Lock
_activeOrders[orderId] = orderStatus; // DANGEROUS!
✅ CORRECT - With Lock
lock (_lock)
{
_activeOrders[orderId] = orderStatus;
}
Rule
Every class with shared state MUST have:
private readonly object _lock = new object();
Every access to shared collections MUST be inside:
lock (_lock)
{
// Dictionary/List operations here
}
Error Handling - Try-Catch Required
ALL public methods MUST have try-catch blocks.
❌ WRONG - No Error Handling
public async Task<string> SubmitOrder(OrderRequest request)
{
var orderId = GenerateOrderId();
await _nt8Adapter.SubmitToNT8(orderStatus);
return orderId;
}
✅ CORRECT - With Error Handling
public async Task<string> SubmitOrder(OrderRequest request)
{
if (request == null)
throw new ArgumentNullException("request");
try
{
request.Validate();
}
catch (ArgumentException ex)
{
_logger.LogError("Order validation failed: {0}", ex.Message);
throw;
}
try
{
var orderId = GenerateOrderId();
await _nt8Adapter.SubmitToNT8(orderStatus);
return orderId;
}
catch (Exception ex)
{
_logger.LogError("Order submission failed: {0}", ex.Message);
throw;
}
}
Pattern Template
public ReturnType MethodName(Type parameter)
{
// 1. Validate parameters (throw ArgumentNullException/ArgumentException)
if (parameter == null)
throw new ArgumentNullException("parameter");
// 2. Try-catch for operation-specific errors
try
{
// Main logic
}
catch (SpecificException ex)
{
_logger.LogError("Specific error: {0}", ex.Message);
// Handle or re-throw
throw;
}
catch (Exception ex)
{
_logger.LogError("Unexpected error: {0}", ex.Message);
throw;
}
}
Logging - Structured and Consistent
Use structured logging with string.Format (NOT string interpolation).
Log Levels
LogTrace - Detailed Flow
_logger.LogTrace("Entering method {0} with parameter {1}", methodName, param);
LogDebug - Normal Operations
_logger.LogDebug("Order {0} state is {1}", orderId, state);
LogInformation - Important Events
_logger.LogInformation("Order {0} submitted successfully at {1}", orderId, timestamp);
_logger.LogInformation("Order {0} filled: {1} contracts @ {2:F2}", orderId, qty, price);
LogWarning - Recoverable Issues
_logger.LogWarning("Order validation failed: {0}", validationError);
_logger.LogWarning("Maximum active orders reached: {0}", maxOrders);
LogError - Failures
_logger.LogError("Failed to submit order {0} to NT8: {1}", orderId, ex.Message);
_logger.LogError("Invalid state transition: {0} -> {1}", fromState, toState);
LogCritical - System Integrity Issues
_logger.LogCritical("Emergency flatten failed for {0}: {1}", symbol, ex.Message);
❌ WRONG - String Interpolation
_logger.LogInformation($"Order {orderId} submitted"); // C# 6+ feature!
✅ CORRECT - string.Format
_logger.LogInformation("Order {0} submitted", orderId);
XML Documentation - Required
ALL public and protected members MUST have XML documentation.
❌ WRONG - No Documentation
public interface IOrderManager
{
Task<string> SubmitOrder(OrderRequest request);
}
✅ CORRECT - With Documentation
/// <summary>
/// Order management interface - manages complete order lifecycle
/// </summary>
public interface IOrderManager
{
/// <summary>
/// Submit new order for execution
/// </summary>
/// <param name="request">Order request with all parameters</param>
/// <returns>Unique order ID for tracking</returns>
/// <exception cref="ArgumentNullException">Request is null</exception>
/// <exception cref="ArgumentException">Request validation fails</exception>
Task<string> SubmitOrder(OrderRequest request);
}
Template
/// <summary>
/// Brief description of what this does (one line)
/// </summary>
/// <param name="paramName">What this parameter represents</param>
/// <returns>What this method returns</returns>
/// <exception cref="ExceptionType">When this exception is thrown</exception>
public ReturnType MethodName(Type paramName)
{
// Implementation
}
Constructor Pattern
❌ WRONG - No Validation
public BasicOrderManager(ILogger logger, INT8OrderAdapter adapter)
{
_logger = logger;
_adapter = adapter;
}
✅ CORRECT - Validate Dependencies
public BasicOrderManager(ILogger<BasicOrderManager> logger, INT8OrderAdapter adapter)
{
if (logger == null)
throw new ArgumentNullException("logger");
if (adapter == null)
throw new ArgumentNullException("adapter");
_logger = logger;
_adapter = adapter;
_activeOrders = new Dictionary<string, OrderStatus>();
_completedOrders = new Dictionary<string, OrderStatus>();
// Register callbacks
_adapter.RegisterOrderCallback(OnNT8OrderUpdate);
_logger.LogInformation("BasicOrderManager initialized");
}
Event Raising Pattern
NEVER raise events inside locks (prevents deadlocks).
❌ WRONG - Event Inside Lock
lock (_lock)
{
order.State = newState;
OrderStateChanged?.Invoke(this, eventArgs); // DEADLOCK RISK!
}
✅ CORRECT - Event Outside Lock
OrderState previousState;
OrderState newState;
lock (_lock)
{
previousState = order.State;
order.State = newState;
// Update state inside lock
}
// Raise event OUTSIDE lock
RaiseOrderStateChanged(orderId, previousState, newState, reason);
Verification Checklist
Before completing ANY method, verify:
- Parameter validation (ArgumentNullException/ArgumentException)
- Try-catch on operation
- Logging at appropriate level
- Lock around shared state access
- Events raised outside locks
- XML documentation on public members
- C# 5.0 syntax only (no $, ?., =>, etc.)