strategy

Manage entries, exits, and track position metrics for backtesting strategies. The strategy namespace provides order creation, cancellation, and real-time P&L tracking. Use with @script.strategy() decorator to enable position management.

Quick Example

  from pynecore.lib import (
    close, high, low, strategy, ta, bar_index, script
)
from pynecore.types import Persistent

@script.strategy(title="Simple Strategy", initial_capital=10000)
def main():
    sma20: Persistent[float] = ta.sma(close, 20)
    
    if bar_index == 20:
        strategy.entry("long", strategy.long, qty=1)
    
    if ta.crossunder(close, sma20):
        strategy.close("long", comment="Exit on cross below")
    
    # Check performance
    pnl: float = strategy.netprofit
    position: float = strategy.position_size
  

Functions

strategy.entry()

Create a new order to open or add to a position. Modifies existing unfilled orders with the same id.

ParameterTypeDescription
idstrOrder identifier
directionintTrade direction: strategy.long or strategy.short
qtyfloat | NoneQuantity in units (optional, uses strategy default if None)
limitfloat | NoneLimit price for entry (optional)
stopfloat | NoneStop price for entry (optional)
oca_namestr | NoneOne-Cancels-All group identifier (optional)
oca_typeintOCA behavior type (optional)
commentstr | NoneOrder comment (optional)
alert_messagestr | NoneAlert message text (optional)

Returns: None

  strategy.entry("long_1", strategy.long, qty=2.5)
strategy.entry("entry_limit", strategy.long, qty=1, limit=100.5)
  

strategy.exit()

Create price-based exit orders (take-profit, stop-loss, or trailing stop). Modifies existing unfilled orders with the same id.

ParameterTypeDescription
idstrExit order identifier
from_entrystr | NoneEntry id to exit (optional, exits from any entry if None)
qtyfloat | NoneExit quantity (optional)
qty_percentfloat | NoneExit as % of position (optional)
profitfloat | NoneTake-profit in currency units (optional)
limitfloat | NoneLimit price for take-profit (optional)
lossfloat | NoneStop-loss in currency units (optional)
stopfloat | NoneStop price for stop-loss (optional)
trail_pricefloat | NoneTrailing stop price offset (optional)
trail_pointsfloat | NoneTrailing stop in points (optional)
trail_offsetfloat | NoneTrailing offset (optional)
oca_namestr | NoneOCA group identifier (optional)
commentstr | NoneOrder comment (optional)
comment_profitstr | NoneTP comment (optional)
comment_lossstr | NoneSL comment (optional)
comment_trailingstr | NoneTrailing stop comment (optional)
alert_messagestr | NoneAlert text (optional)
alert_profitstr | NoneTP alert (optional)
alert_lossstr | NoneSL alert (optional)
alert_trailingstr | NoneTrailing alert (optional)
disable_alertboolSuppress alerts if True (optional)

Returns: None

  strategy.exit("tp_sl", qty_percent=100, profit=500, loss=200)
strategy.exit("trail", trail_points=50, comment="Trailing stop")
  

strategy.close()

Exit a position opened by entries with a specific id. Closes the position immediately at market price.

ParameterTypeDescription
idstrEntry id to close
commentstr | NoneOrder comment (optional)
qtyfloat | NonePartial close quantity (optional)
qty_percentfloat | NonePartial close as % of position (optional)
alert_messagestr | NoneAlert text (optional)
immediatelyboolClose at market immediately (optional)

Returns: None

  strategy.close("long_1", comment="Exit signal")
strategy.close("entry_a", qty_percent=50)
  

strategy.close_all()

Close the entire open position immediately at market price, regardless of entry ids.

ParameterTypeDescription
commentstr | NoneOrder comment (optional)
alert_messagestr | NoneAlert text (optional)
immediatelyboolClose immediately (optional)

Returns: None

  strategy.close_all(comment="Exit all positions")
  

strategy.order()

Create a new order to open, add to, or exit a position. Modifies existing unfilled orders with the same id.

ParameterTypeDescription
idstrOrder identifier
directionintTrade direction: strategy.long or strategy.short
qtyfloat | NoneQuantity in units (optional)
limitfloat | NoneLimit price (optional)
stopfloat | NoneStop price (optional)
oca_namestr | NoneOCA group identifier (optional)
oca_typeintOCA behavior type (optional)
commentstr | NoneOrder comment (optional)
alert_messagestr | NoneAlert text (optional)
disable_alertboolSuppress alerts if True (optional)

Returns: None

  strategy.order("hedge", strategy.short, qty=1, limit=99.5)
  

strategy.cancel()

Cancel a pending or unfilled order by id. Cancels all orders sharing the same id.

ParameterTypeDescription
idstrOrder identifier to cancel

Returns: None

  strategy.cancel("limit_order")
  

strategy.cancel_all()

Cancel all pending or unfilled orders regardless of id.

Returns: None

  strategy.cancel_all()
  

Variables

NameTypeDescription
position_sizefloatCurrent position size (> 0 = long, < 0 = short, 0 = flat). Returns NaN if no position.
position_avg_pricefloatAverage entry price of current position. Returns NaN if flat.
opentradesintCount of open (unfilled entry) positions.
openprofitfloatCurrent unrealized P&L for all open positions in currency units.
closedtradesintTotal count of closed trades for the entire trading range.
wintradesintCount of winning trades.
losstradesintCount of losing trades.
eventradesintCount of breakeven trades.
netprofitfloatTotal realized P&L for all closed trades in currency units.
grossprofitfloatTotal P&L from winning trades in currency units.
grosslossfloatTotal P&L from losing trades in currency units.
equityfloatCurrent equity = initial_capital + netprofit + openprofit.
max_drawdownfloatMaximum equity drawdown from peak in currency units.
max_drawdown_percentfloatMaximum drawdown as % of initial capital.
max_runupfloatMaximum equity run-up from entry in currency units.
max_runup_percentfloatMaximum run-up as % of initial capital.
initial_capitalfloatInitial capital set in strategy properties.

Constants

NameTypeDescription
longintDirection constant for strategy.entry() and strategy.order(). Creates a buy/long position.
shortintDirection constant for strategy.entry() and strategy.order(). Creates a sell/short position.
fixedQtyTypeQuantity type for strategy properties. Fixed number of units per entry.
cashQtyTypeQuantity type for strategy properties. Fixed currency amount per entry.
percent_of_equityQtyTypeQuantity type for strategy properties. Percentage of equity per entry.

Compatibility

Not yet implemented:

  • strategy.account_currency — Account currency from properties
  • strategy.convert_to_account() — Currency conversion to account currency
  • strategy.convert_to_symbol() — Currency conversion to symbol currency
  • strategy.default_entry_qty() — Calculate default order quantity
  • strategy.margin_liquidation_price — Margin call liquidation price
  • strategy.max_contracts_held_* — Maximum contract tracking variables
  • All percentage variables: strategy.netprofit_percent, strategy.grossprofit_percent, strategy.grossloss_percent, strategy.openprofit_percent, strategy.avg_trade_percent, strategy.avg_winning_trade_percent, strategy.avg_losing_trade_percent
  • strategy.position_entry_name — Entry order name for current position