Skip to main content

Strategy Variables

symbolName​

Purpose​

Represents the primary instrument's trading symbol, typically configured at the strategy level (e.g., NIFTY, BANKNIFTY).

Type​

symbolName: str

Details​

  • Used as the default underlying symbol for most data and option queries
  • Auto-configured from the runEvents(...) setup or through the strategy UI.
  • Used when constructing option symbols or retrieving expiry-specific data.

underlyingName​

Purpose​

Provides the underlying instrument's base name used for constructing or mapping related instruments (e.g., futures or options).Internally used for symbol formation or mapping to the correct instrument type.

Type​

underlyingName: str

Example​

underlying = self.underlyingName  # "NIFTY"

name​

Purpose​

Returns the strategy’s registered name or label — useful for logging, display, or strategy-level identification.

Type​

name: str

Details​

  • Set automatically when a strategy is initialized.
  • Used for naming logs, reports, or runtime sessions.
  • Helpful in dashboards or notifications to distinguish between multiple strategies.

Example​

print(f"Running strategy: {self.name}")

currentCandle​

Purpose​

Represents the exact timestamp of the candle that is currently being processed or has just closed.

Type​

currentCandle: datetime.datetime

Details​

  • This is the main driver for all time-sensitive strategy logic.
  • Especially useful when you need to perform time arithmetic (e.g., checking time before/after the current candle).
  • Generally represents the close time of the candle.

Example Usage​

# Square off at 15:15
if (self.currentCandle + datetime.timedelta(minutes=1)).time() == datetime.time(15, 15, 0):
self.squareoff_all()

candleTime​

Purpose​

Gives the time portion (HH:MM:SS) of the current candle in string format (e.g., "09:20:00"), useful for time-based strategy decisions.

Type​

candleTime: str

Details​

  • Used primarily for time-based entry/exit logic.
  • Eliminates need for datetime conversion when you're only comparing HH:MM.
  • Follows standard 24-hour HH:MM:SS format.

Example Usage​

# Run entry logic at a specific time
if self.candleTime == "09:20:00":
self.log("Time to check entry conditions.")

currentDay​

Purpose​

Holds the current trading date (not timestamp), allowing day-based logic and expiry comparisons.

Type​

currentDay: datetime.date

Details​

Useful for:

  • Checking monthly boundaries
  • Filtering date-specific logic
  • Tagging logs or trades with the current day
  • Reflects the trading date for the currently running candle.

Example Usage​

if self.currentDay.day == 1:
self.log("First trading day of the month.")

day_week​

Purpose​

Returns the weekday name (e.g., Monday, Thursday) of the current trading day.

Type​

day_week: str

Details​

  • Derived from currentDay.
  • Useful for weekday-specific logic (e.g., expiry logic on Thursdays).

Example Usage​

if self.day_week == "Thursday":
self.log("It's expiry day!")

expiries​

Purpose​

Provides a chronological list of upcoming expiry dates for the current symbolName.

Type​

expiries: list[datetime.date]

Details​

  • Used for selecting near or far expiry options.
  • Can be passed into functions like getOptSymbol() or constructOptionSymbol().
  • Sorted in ascending order, with the earliest expiry at index 0.

Example Usage​

nearest_expiry = self.expiries[0]
dte = (nearest_expiry - self.currentDay).days
self.log(f"Days to expiry: {dte}")

prevexpiries​

Purpose​

Returns a list of past expiry dates — helpful for analysis, backtests, or calculating DFE.

Type​

prevexpiries: list[datetime.date]

Details​

  • Sorted in ascending order (earliest to latest).
  • Often used with calculateDFE() or historical volatility studies.

Example Usage​

last_expiry = self.prevexpiries[-1]
days_since_expiry = (self.currentDay - last_expiry).days
self.log(f"Days since last expiry: {days_since_expiry}")

position​

Purpose​

Returns a list of currently open positions (i.e., trades that have been executed but not yet exited). Each position contains complete entry metadata.

Type​

position: list[dict]

Details​

  • Each dictionary in the list represents one active trade.
  • If no positions are currently open, self.position == [].

Commonly used to:

  • Check if a leg is active
  • Analyze entry details like price, time, and symbol
  • Apply position-based filters or constraints

Example Usage​

if self.position == []:
self.log("No positions currently open.")
else:
for pos in self.position:
self.log(f"Open Position: {pos['symbol']} @ {pos['entryPrice']}")

Sample Output​

[{'entryTime': datetime.datetime(2025, 5, 26, 9, 26, 59),
'entryDate': datetime.date(2025, 5, 26),
'entryPrice': 219.1999969482422,
'symbol': 'NIFTY29MAY2525050CE',
'qty': 75,
'transactionType': 'buy',
'entryRemarks': 'Entrying Leg'}]

Best Use Cases​

  • Prevent overlapping entries (e.g., check if self.position != []).
  • Logging open trades with timestamps and remarks.
  • Filtering legs by symbol, price, or direction in custom logic.

_triggers​

Purpose​

Stores a list of all trigger objects currently active within the strategy — typically used for time-based, condition-based, or leg-based execution logic.

Type​

_triggers: list[dict]

Details​

  • This is an internal attribute (_triggers, with underscore) primarily used by the framework to track execution triggers created via legs, time conditions, or custom user logic.
  • If no triggers are registered or active, self._triggers == [].
  • Triggers are often associated with waitTrade, reEntry, trailSL, or other leg-level automated flows.

Example Usage​

if self._triggers == []:
self.log("No active triggers at the moment.")
else:
for trig in self._triggers:
self.log(f"Trigger for: {trig.get('symbol', 'unknown')}")

⚠️ Internal Use​

Although accessible, _triggers is an internal construct. If you're building strategies, it's typically better to use high-level features like waitTrade, reEntry, or trailSL.


mtm​

Purpose​

Returns the total mark-to-market (MTM) profit or loss for the current day, combining:

  • Intraday booked profits/losses
  • Current unrealized PnL of open positions

Signature​

def mtm(self) -> float

Returns​

float — Net PnL (positive or negative) for the trading day as of the current candle.

Example Usage​

if self.mtm > 1000:
self.finish() # Stop strategy if net profit exceeds ₹1000

Notes​

  • Includes all trades executed since market open.
  • MTM is reset each day, unless you’re carrying forward positions.
  • Ideal for intraday target/SL logic.

open_mtm​

Purpose​

Returns the unrealized PnL of all currently open positions (running trades only).

Signature​

def open_mtm(self) -> float

Returns​

float — Live mark-to-market value of current open positions only.

Notes​

  • Ignores booked trades — focuses only on floating PnL.
  • Useful for Trailing SLs

old_mtm​

Purpose​

Returns the combined PnL of:

  • Booked trades from previous open position dates (i.e., past days’ open positions)
  • Current running open position PnL (same as open_mtm)

Signature​

def old_mtm(self) -> float

Returns​

float — Total PnL carried over from older position(s) plus current unrealized value.

When to Use​

  • For carry-forward strategies, where trades span multiple days
  • To evaluate legacy PnL including ongoing trades