Skip to main content

Leg Handler and Order Management

In Buildalgos.com, a Leg represents a fully managed trading position. It is created with addLeg() and then automatically tracks stop-loss, target, re-entry conditions, and lifecycle events.

Each addLeg(...) call spawns an internal LegHandler object and returns a unique legID (UUID).

Why Use addLeg Instead of placeOrder?

FeatureaddLegplaceOrder
Automatic SL / Target
Trailing stop-loss
Re-entry after SL / Target
Wait-Trade (delayed entry)
Group square-offsManual
Position trackingAutoManual
Best forSystematic
strategies
One-off discretionary
trades

addLeg() Signature

leg_id = self.addLeg(
transactionType='buy', # "buy" or "sell"
optionType='PE', # "CE" | "PE" (ignored for FUT/CASH)
qty=75,
Symbol: Optional[str] = None,
strikeSelection={'strikeBy': 'moneyness','strikeVal': 0,'asof': 'None','roundoff': None},
expiry={'expType': 'weekly','expNo': 0},
target={'isTarget': True,'targetOn': '%','targetValue': 50},
SL={'isSL': True,'SLon': '%','SLvalue': 35},
trailSL={'isTrailSL': False,'trailSLon': 'val','trailSL_X': 1,'trailSL_Y': 1},
reEntryTg={'isReEntry': False,'reEntryOn': 'asap','reEntryVal': 0,'reEntryMaxNo': 20},
reEntrySL={'isReEntry': False,'reEntryOn': 'asap','reEntryVal': None,'reEntryMaxNo': 20},
waitTrade={'isWT': False,'wtOn': 'val-up','wtVal': 1,'triggers': []},
segment='OPT', # "OPT" | "FUT"
entryValidity='Day', # currently only "DAY"
squareoff='this', # "this" | "all" | [legIDs]
legName:Optional[str] = None,
webhook={'is': False,'entryMessage': {},'exitMessage': {}}
)

This structure allows for flexible, reusable, and fully-managed execution flows for any options or futures strategy.

Top Level Parameters

ParameterValuesDescription
transactionType'buy' or 'sell'Buy or sell leg
symbolstr or NoneOptional: direct symbol override; else uses strikeSelection
optionType'CE' or 'PE'Option type (for options); otherwise None
qtyintQuantity (usually multiple of lot size)
segment"OPT" | "FUT"Segment to trade
entryValidity'Day'Order validity
remarkstrOptional note, e.g. 'Entering Leg'
legNamestrOptional unique ID, e.g. 'lg_ac380_1'

Nested Parameters Dictionaries

strikeSelection :

KeyTypeExample ValuesDescription
strikeBystr

'premium above', 'premium near',
'premium below', 'moneyness',
'delta above', 'delta below',
'delta near'

Method used to select the strike price
strikeValint

1–9999 (for 'premium'), -10 to 10 (for 'moneyness'), or -1 to 1 (for 'delta').

Value used according to strike-selection logic
asofstr or None

'09:30:00', 'None' (default)

Time reference for strike selection
roundoffint or None

None, 100, 200, 500, 1000

Round strike to nearest value (e.g., 100)

expiry Selection:

KeyTypeExample ValueDescription
expTypestr'weekly'Expiry type (weekly/monthly)
expNoint00 = nearest, 1 = next

Stop-Loss (SL) & Target (target):

KeyChoices / TypeEffect / Description

isSL /
isTarget

True / False (bool)

Enable/disable SL or target logic

SLon /
targetOn

"val" (absolute ₹)"%" (percentage)"mtm" (₹ P&L)

How exit threshold is computed

SLvalue /
targetValue

number(float/int)Magnitude of SL/target

Trailing SL (trailSL):

Note : Value must be between 0-100% for %

KeyTypeExample ValueDescription
isTrailSLboolTrueEnable trailing SL
trailSLonstr'%', 'val'Based on value or %
trailSL_Xfloat2Distance (₹ or %) that triggers a trailing SL adjustment
trailSL_Yfloat0.98Amount (₹ or %) by which SL is tightened each time trailSL_X is hit

Re-Entry Rules (reEntrySL, reEntryTg):

KeyType / ChoicesDescription
isReEntrybool (True/False)Enables re-entry after SL/target
reEntryOnstr
Choices:
  • "asap", "asap-rev"
  • "cost", "costrev"
  • "withWT", "withWT-rev"
  • "action"
  • "asap": immediately
  • "asap-rev": reverse transactionType
  • "cost": re-enter at exit cost
  • "cost-rev": cost price + reverse
  • "withWT": re-enter with waitTrade
  • "withWT-rev": reverse + waitTrade
  • "action": based on predefined CE/PE action logic
reEntryValNone or self.act
  • Default: None
  • If reEntryOn == "action" → set reEntryVal = self.act
reEntryMaxNointMax allowed re-entry attempts (range 1–20)

Wait‑Trade (waitTrade):

Delays order entry until the instrument's price changes by a defined amount or percentage.

KeyTypeAllowed Values / ExamplesDescription
isWTboolTrue, FalseEnable/disable wait-trade logic
wtOnstr
"val-up" → price ↑ by ₹X
"val-down" → price ↓ by ₹X
"%val-up" → price ↑ by X%
"%val-down" → price ↓ by X%
Price-change condition required to place the leg
wtValfloat1, 2.5, …Required move (₹ or %) — depends on wtOn
triggerslistOptional list of other leg definitionsAuto-trigger extra legs when the wait condition is met

webhook (Custom Webhooks):

KeyTypeExample ValueDescription
isboolFalseWhether webhook is active
entryMessagedict{}Custom webhook payload on entry
exitMessagedict{}Custom webhook payload on exit