Reuse a condition¶
Give a calculation or condition a name with define. Keep your rule readable without writing imperative code.
//@version=1
symbol: TCS
run: daily
size: 5% per instrument
define trend_is_up = ema(20) > ema(50)
define rsi_is_strong = rsi(14) > 50
entry:
long when: trend_is_up and rsi_is_strong
exit:
long when: close < ema(50)
Definitions combine supported indicators, math and logic. They do not introduce loops or external calls.
Name a value or a condition¶
define fast_average = ema(20)
define trend_is_up = fast_average > ema(50)
fast_average names a numeric calculation; trend_is_up names a true-or-false condition. Use the condition directly after when:. Compare a numeric definition with something, such as close > fast_average, when you need a condition.
A definition describes a calculation evaluated with the current strategy data. It is not a remembered value from the moment you first typed the definition. With a universe, price-based calculations use the instrument currently being evaluated.
Use a distinct identifier such as trend_is_up: letters, digits and underscores, without starting with a digit. Define names before using them, and avoid replacing built-in price or function names.
Longer calculations¶
define score:
trend = rank(momentum)
value_score = rank(value)
result = trend + value_score
A block ends with result =. Define each binding before referring to it. Self-reference and forward references are rejected. Score inputs must be available to the strategy.
In this block, trend and value_score are intermediate values; the final result is what score represents. They are local to the block. You could use score in hold: long top 2 by score, with a fixed universe and compatible sizing. rank combines cross-sectional inputs; it does not make missing momentum or value data available.
Change periods without changing the rule¶
//@version=1
symbol: TCS
run: daily
size: 5% per instrument
define above_fast_average = close > ema(20)
define above_slow_average = close > ema(50)
entry:
long when: above_fast_average and above_slow_average
exit:
long when: close < ema(50)
The two definitions describe the same comparison at different periods. To change the fast horizon, edit 20 in its definition; the entry still requires both conditions. Definitions in the current language do not accept custom parameter lists such as define above_average(period). Built-in/provider functions such as ema(20) have their own documented arguments.
Use definitions to remove repeated calculations or explain an idea in the rule. A one-line rule that is already clear does not need a new name.
For two directional rules, read long and short rules.