Skip to main content

Strategy Methods

getCurrentData

Purpose

Fetches the latest available price data for all symbols at the current candle's timestamp. Typically used inside the strategy loop (e.g., runOnCandleClose) to access real-time LTPs in Live Deployment and Close in Backtesting for decision-making.

Signature

getCurrentData() -> dict[str, float]

Returns

A dictionary where each key is a symbol string (spot, futures, or option), and each value is the Last Traded Price (LTP) or current price at the time of execution.

Example Use

def runOnCandleClose(self):
prices = self.getCurrentData()
print(prices)
# Output:
# {
# "NIFTY-I": 23985.25,
# "NIFTY24JUL24000CE": 105.2,
# "NIFTY24JUL24000PE": 120.75
# }

getTimestampData

Purpose

Fetches candle and market data for a specific symbol and timestamp, adjusted to the desired timeframe. This method supports Spot, Futures, and Options instruments.

Signature

getTimestampData(symbol: str, ts: datetime.datetime, timeframe: int) -> dict

Parameters

NameTypeDescription
symbolstr

Instrument symbol (e.g., 'NIFTY', 'NIFTY12JUN2525100CE')

tsdatetime.datetime

Timestamp to query. Time is floored/rounded to candle start.

timeframeint

Timeframe in minutes (e.g., 1, 5, 15).

Returns

A dictionary containing the OHLCV + Greeks + metadata for that specific symbol and candle.

Example Outputs

Spot/Futures Response:

{
'datetime': datetime.datetime(2025, 6, 9, 9, 30),
'open': 25093.9,
'high': 25094.85,
'low': 25082.4,
'close': 25083.65,
'volume': 0,
'oi': 0,
'symbol': 'NIFTY',
'exp': datetime.datetime(1970, 1, 1, 5, 30),
'strike': 0.0,
'type': 'SP'
}

Option Response:

{
'datetime': datetime.datetime(2025, 6, 9, 9, 30),
'open': 147.65,
'high': 153.35,
'low': 146.1,
'close': 149.6,
'volume': 1549727,
'oi': 6207450,
'symbol': 'NIFTY12JUN2525100CE',
'exp': datetime.date(2025, 6, 12),
'strike': 25100.0,
'type': 'CE',
'iv': 0.1676,
'delta': 0.4853,
'theta': -26.56,
'gamma': 0.0010,
'vega': 9.4357
}

Notes

  • For Options, additional greeks and option chain data (IV, delta, gamma, etc.) are provided.
  • For SPOT/FUT, option-specific fields like greeks are omitted or defaulted.
  • This method is optimized for minute-level resolution and assumes preloaded/in-memory data from getCandleData.

getTradingDay

Purpose

Returns the date of a specific trading day based on its relative position from the current trading day. This is helpful when you need to access historical trading days (e.g., for fetching past expiry, candles, or indicators).

Signature

getTradingDay(idx: int) -> datetime.date

Parameters

NameTypeDescription
idxint
Relative offset from the current trading day:
  • -1 = current trading day
  • -2 = previous trading day
  • -N = Nth previous trading day

Returns

A datetime.date object corresponding to the specified trading day.

Example Use

today = self.getTradingDay(-1)
yesterday = self.getTradingDay(-2)
print(today) # datetime.date(2025, 7, 5)
print(yesterday) # datetime.date(2025, 7, 4)

set_data

Purpose

Locks the strike selection for a specific data object (getSyntheticFut, getCombinedPremium, getCandleDataSym) to the current strike at the time of invocation. This ensures consistency across future candles—even if market conditions change.

Signature

set_data(name: str)

Parameters

NameTypeDescription
namestr

The unique name identifier passed to the data method (e.g., "myATMdata").

Example Use

self.getCandleDataSym(name="myATMdata", dataType="opt", strike={"by":"atm"}, ...)
...
self.set_data(name="myATMdata") # Lock ATM strike as of current candle

What It Does

  • Stores the resolved strike value (e.g., ATM = 25400 at 9:30).
  • Future calls to getSyntheticFut, getCombinedPremium, or getCandleDataSym with the same name will return candles for that fixed strike, regardless of evolving ATM.
  • Ensures strike consistency for multi-leg option strategies, premium combinations, or synthetic future construction.

reset_data

Purpose

Reverses the effect of set_data() — re-enables dynamic strike resolution using the original rules (e.g., ATM, ITM, delta-based).

Signature

reset_data(name: str)

Parameters

NameTypeDescription
namestrThe name of the data object previously locked using set_data.

Example Use

self.reset_data(name="myATMdata")  # Reverts to using live ATM every candle

What It Does

  • Clears any previously locked strike from set_data.
  • Resumes live/dynamic strike selection as per rules.

reset_cm

Purpose

Resets the cached data for datapoints. Useful when you need to recalculate indicator data or refresh computed values during runtime.

Signature

reset_cm()

reset_cm_min

Purpose

Same as reset_cm, but specifically targets minute-level data cache.

Signature

reset_cm_min()

finish

Purpose

Ends the strategy execution for the current day, stopping all further evaluation and event processing — but does not square off positions.

Signature

finish()

Example Use

if self.mtm() < -1000:
self.finish() # Stop trading, keep existing positions open

What It Does

  • Immediately halts further execution of runOnCandleClose, runNewDay, etc.
  • All active triggers, entry logic, and data updates are stopped for the session.
  • Open positions are left untouched — must be squared off manually or with a separate call (squareoff_all or leg-level squareoff).

getExpiry

Purpose

Returns the upcoming expiry date based on the expiry type (weekly/monthly) and the position in the expiry sequence.

Signature

getExpiry(expType: str = "weekly", expNo: int = 0) -> datetime.date

Parameters

NameTypeDescription
expTypestr

Type of expiry: "weekly" or "monthly"

expNoint

Sequence number starting from 0:

  • 0 = current expiry
  • 1 = next expiry, and so on

Returns

A datetime.date object representing the Nth upcoming expiry date for the given expiry type.

Example Use

this_week_exp = self.getExpiry(expType="weekly", expNo=0)
next_month_exp = self.getExpiry(expType="monthly", expNo=1)

Notes

  • weekly expiry works for NIFTY and SENSEX.
  • monthly expiry works for NIFTY, SENSEX, and BANKNIFTY.

getFromExpiry

Purpose

Returns the most recently expired weekly or monthly expiry date based on the selected expiry type.

Signature

getFromExpiry(expType: str = "weekly") -> datetime.date

Parameters

NameTypeDescription
expTypestrType of expiry: "weekly" or "monthly"

Returns

A datetime.date representing the last expired weekly or monthly expiry.

Example Use

last_weekly_exp = self.getFromExpiry(expType="weekly")
last_monthly_exp = self.getFromExpiry(expType="monthly")

calculateDTE

Purpose

Calculates the number of trading days remaining until a future expiry. Counts only valid exchange trading days.

Signature

calculateDTE(expType: str = "weekly", expNo: int = 0) -> int

Parameters

NameTypeDescription
expTypestr

Expiry type: "weekly" or "monthly"

expNoint

Sequence of the expiry:

  • 0 = current expiry
  • 1 = next expiry, etc.

Returns

int — Number of trading days left (excluding weekends and holidays) from today until the target expiry.

Example Use

dte = self.calculateDTE(expType="weekly", expNo=0)
print(f"Days to expiry: {dte}")

calculateDFE

Purpose

Calculates the number of trading days since the last expiry. Counts only valid exchange trading days.

Signature

calculateDFE(expType: str = "weekly") -> int

Parameters

NameTypeDescription
expTypestrExpiry type: "weekly" or "monthly"

Returns

int — Number of trading days passed since the last expired weekly or monthly expiry.

Example Use

dfe = self.calculateDFE(expType="monthly")
print(f"Trading days since last monthly expiry: {dfe}")

getATM

Purpose

Returns the at-the-money (ATM) strike for the underlying index (e.g., NIFTY), optionally rounded to a specified strikeDiff, and optionally based on a specific time (asof).

Signature

getATM(strikeDiff: int = 50, asof: Optional[str] = None) -> int

Parameters

NameTypeDescription
strikeDiffint

The strike interval to round to.

  • Default is 50 (for NIFTY)
  • Can be set to custom values like 100, 500, 1000.
asofstr or None

Time in "HH:MM:SS" (e.g., "09:30:00").
If not provided, the current candle’s time is used.

Returns

int — The ATM strike price rounded to the nearest strikeDiff.

Example Use

# Get current ATM rounded to nearest 50
atm = self.getATM()
# Get ATM as of 09:30 AM rounded to 100
atm_930 = self.getATM(strikeDiff=100, asof="09:30:00")

What It Does

  • Internally fetches the spot price (e.g., NIFTY) as per asof time.
  • Rounds it to the nearest multiple of strikeDiff.
  • Returns an integer strike price suitable for constructing options.

getStrike

Purpose

Rounding helper that calculates the nearest valid strike given a raw LTP and desired strike interval.Used internally by getATM and option symbol constructors.

Signature

Example Use

getStrike(ltp: float, strikeDiff: int = None) -> float

Parameters

NameTypeDescription
ltpfloatLast traded price or raw float price.
strikeDiffintOptional strike difference for rounding (instrument default if omitted).

Returns

float — Nearest valid strike price as per the rounding rule.

Example Use

strike = self.getStrike(ltp=25412)              # Returns 25400
strike_custom = self.getStrike(ltp=25412, strikeDiff=1000) # Returns 25000

strikeDiff

Purpose

Returns the default strike interval based on the underlying symbol (e.g., NIFTY = 50, BANKNIFTY = 100).

Signature

strikeDiff -> int

Notes

  • Automatically inferred from the underlying associated with the strategy or leg.
  • Used as default in getATM, getStrike, and option data fetching helpers.

contructOptionSymbol

Purpose

Constructs a valid option trading symbol (e.g., NIFTY11JUL2525000CE) using specified expiry, strike, and option type. Mainly used when you already know the parameters.

Signature

contructOptionSymbol(
optype: str = "CE",
expiry: datetime.date,
symbolName: str = "NIFTY",
strike: Optional[float] = None
) -> str

Parameters

NameTypeDescription
optypestr
  • "CE" or "PE"
  • Defines Call / Put
expirydatetime
date
  • Expiry date
  • Use getExpiry() or getFromExpiry()
symbolNamestr(optional)
  • Underlying symbol (e.g., "NIFTY")
  • Defaults to strategy’s configured name
strikefloat(optional)
  • Strike price
  • If None, uses ATM via getATM()

Returns

str — Fully qualified option symbol string.

Example Use

symbol = self.contructOptionSymbol(
optype="CE",
expiry=self.getExpiry("weekly", 0),
strike=25000
)
# Returns: "NIFTY11JUL2525000CE"

getOptSymbol

Purpose

Dynamically resolves the best-fit option symbol based on rules such as moneyness, premium, or delta, evaluated at the given time (asof).

Signature

getOptSymbol(
strike: dict,
exp: dict,
opType: str,
asof: Optional[str] = None
) -> str

Parameters

NameTypeDescription
strikedictRule to determine the strike. Structure varies by method.
expdict

Expiry specifier. Format: {"expType": "weekly", "expNo": 0}

opTypestr"CE" or "PE"
asofstr
or
None

Time in "HH:MM:SS" format. Uses current candle if not specified.

Example Use

symbol = self.getOptSymbol(
strike={"by": "moneyness", "at": "otm2"},
exp={"expType": "weekly", "expNo": 0},
opType="PE"
)
# Returns: "NIFTY11JUL2524700PE"

squareoff_all

Purpose

Closes all open positions managed by the strategy, regardless of leg or entry time.

Signature

squareoff_all(remark: str = "")

Parameters

NameTypeDescription
remarkstrOptional. Adds a note or reason in the exit logs.

Effect

Places market exit orders for all open legs.

Example Usage

self.squareoff_all(remark="Target hit for the day")

Notes

Commonly used in:

  • EOD position squaring
  • Risk management exits
  • Rule-based stop conditions

squareoff_legs

Purpose

Closes only selected legs (positions), using their legIDs.

Signature

squareoff_legs(legs: list[str], remark: str = "squaring off legs")

Parameters

NameTypeDescription
legslist[str]

List of legIDs (returned by addLeg(...))
to be squared off.

remarkstrOptional. Comment to annotate the exit reason.

Example Use

self.squareoff_legs(["leg_hedge1", "leg_entry2"], remark="manual hedge unwind")

Notes

Useful for partial exits (e.g., closing hedge leg but keeping directional trade open).


turnoffTriggers

Purpose

Deactivates all pending entry triggers (i.e., legs in "Wait" or "Trade" state), preventing further orders from being placed.

Signature

turnoffTriggers()

Effect

  • Resets the trigger system.
  • Existing open positions are not affected.
  • Does not square off legs, only stops new trigger evaluations.

Example Use

if self.mtm > 2000:
self.turnoffTriggers() # Lock gains, prevent re-entries

Use Cases

  • After hitting a global profit or loss cap
  • Before time-based shutdowns (e.g., post 15:00)

action_active

Purpose

Checks whether any leg under a given action is still active, i.e., not fully exited.

Signature

action_active(actionName: str) -> bool

Parameters

NameTypeDescription
actionNamestr

The name of the action (defined via self.actions_all in init).

Returns

boolTrue if any leg associated with the actionName is still active (i.e., not in ["DONE", "NA"]); otherwise False.

What It Checks

  • Auto-detects leg states associated with the specified action.
  • Returns False if all legs are fully processed (either "DONE" or "NA").

Example Use

if not self.action_active("act_mainEntry"):
# Safe to re-enter or move to next action
self.placeOrder(...)

action_active_exl_WT

Purpose

Similar to action_active, but excludes legs in WT (WaitTrade) state from being considered active.

Signature

action_active_exl_WT(actionName: str) -> bool

Returns

boolTrue if any leg under the action is active, excluding WT state; otherwise False.

Example Use

if not self.action_active_exl_WT("act_hedge"):
self.turnoffTriggers()

Use Cases

  • Prevent double entries if action is already live.
  • Implement clean action transitions in multi-action or hierarchical strategies.
  • Differentiate between pending triggers and executed trades

placeOrder

Purpose

Places a simple market or limit order instantly for any tradable symbol — without managing it as a leg (i.e., no SL, Target, Trail, re-entry, etc.).

Signature

placeOrder(
symbol: str,
transactionType: str, # "buy" or "sell"
qty: int,
price: Optional[float] = None,
remark: str = ""
)

Parameters

NameTypeDescription
symbolstr

Full trading symbol (e.g., "NIFTY11JUL2524800CE")

transaction
Type
str

"buy" or "sell"

qtyint

Quantity of units to buy/sell (not lots — actual lot size multiplied value)

price
or None
float

If None, a market order is placed at current price. Otherwise, a limit order is placed at the specified price.

remarkstr

Optional. Descriptive tag or reason for audit/logging.

Returns

No return value. Internally logs and sends the order to the broker or paper trade engine.

Example Use

# Market order to buy 75 qty of NIFTY CE
self.placeOrder(
symbol="NIFTY11JUL2524800CE",
transactionType="buy",
qty=75,
remark="Manual buy before data release"
)
# Limit order to sell at ₹112.5
self.placeOrder(
symbol="NIFTY11JUL2524800PE",
transactionType="sell",
qty=75,
price=112.5,
remark="Fade the IV spike"
)