HX101 C# For Trading Scripts
HX101 teaches only the C# you need before building indicators and strategies. The goal is not general software engineering. The goal is to read bars, hold state, calculate risk, and avoid runtime errors.
Lesson 1: Values
Trading scripts mostly use these types:
| Type | Use |
|---|---|
int | Bar indexes, periods, counts, tick values. |
double | Prices, indicator values, quantities, PnL. |
bool | Feature toggles and signal flags. |
string | Order names, drawing tags, status text. |
DateTime | Bar timestamps and session filters. |
enum | Controlled options such as direction, mode, or signal type. |
Use DateTime[0] for the current bar timestamp. Use System.DateTime.Now only when you need the computer clock.
double close = Close[0];
double priorClose = Close[1];
bool barClosedUp = Close[0] > Open[0];
int currentHour = DateTime[0].Hour;
Lesson 2: Conditions
Most trading logic is a chain of guarded decisions.
if (CurrentBar < 20)
return;
bool crossedUp = Close[0] > Close[1] && Close[1] <= Close[2];
if (crossedUp)
Print("Signal at " + DateTime[0]);
Never read Close[20] unless you first proved that at least 21 bars exist.
Lesson 3: Methods
Move repeated calculations into small methods. A method should answer one question.
private double TicksToPrice(int ticks)
{
return ticks * TickSize;
}
private bool IsTradingHour()
{
int hour = DateTime[0].Hour;
return hour >= 9 && hour < 16;
}
Lesson 4: State
State is information that must survive across bars.
private double _entryPrice;
private int _entryBar = -1;
private bool _targetHit;
private void ResetTradeState()
{
_entryPrice = 0;
_entryBar = -1;
_targetHit = false;
}
State must be reset in State.Configured and again when a trade fully exits.
Lesson 5: Collections
Use collections for grouped values. For bar-aligned output, use Series<T>.
private readonly List<double> _recentRanges = new();
private Series<double> _signal;
private Series<int> _barState;
Series<double> is the normal plotted output type. Series<int> is useful for internal bar classifications, but it is not a price plot by itself.
Exercise
Build a helper class or method set that calculates:
- Stop price from entry price and stop ticks.
- Target price from entry price and target ticks.
- Risk/reward from stop ticks and target ticks.
- Whether the current bar is inside a trading window.
Completion check:
- No bar read happens before enough bars exist.
DateTime[0]is used for bar time.- Helper methods do not place orders or draw UI.