strategy – Basic strategy classes

Strategies are the classes that you define that implement the trading logic, when to buy, when to sell, etc.

Buying and selling can be done in two ways:

Positions are higher level abstractions for placing orders. They are escentially a pair of entry-exit orders and provide easier tracking for returns and PnL than using individual orders.

Strategy

class pyalgotrade.strategy.BaseStrategy(barFeed, broker)

Bases: object

Base class for strategies.

Parameters:

Note

This is a base class and should not be used directly.

getFeed()

Returns the pyalgotrade.barfeed.BaseBarFeed that this strategy is using.

getBroker()

Returns the pyalgotrade.broker.Broker used to handle order executions.

getCurrentDateTime()

Returns the datetime.datetime for the current pyalgotrade.bar.Bars.

marketOrder(instrument, quantity, onClose=False, goodTillCanceled=False, allOrNone=False)

Submits a market order.

Parameters:
  • instrument (string.) – Instrument identifier.
  • quantity (int/float.) – The amount of shares. Positive means buy, negative means sell.
  • onClose (boolean.) – True if the order should be filled as close to the closing price as possible (Market-On-Close order). Default is False.
  • goodTillCanceled (boolean.) – True if the order is good till canceled. If False then the order gets automatically canceled when the session closes.
  • allOrNone (boolean.) – True if the order should be completely filled or not at all.
Return type:

The pyalgotrade.broker.MarketOrder submitted.

limitOrder(instrument, limitPrice, quantity, goodTillCanceled=False, allOrNone=False)

Submits a limit order.

Parameters:
  • instrument (string.) – Instrument identifier.
  • limitPrice (float.) – Limit price.
  • quantity (int/float.) – The amount of shares. Positive means buy, negative means sell.
  • goodTillCanceled (boolean.) – True if the order is good till canceled. If False then the order gets automatically canceled when the session closes.
  • allOrNone (boolean.) – True if the order should be completely filled or not at all.
Return type:

The pyalgotrade.broker.LimitOrder submitted.

stopOrder(instrument, stopPrice, quantity, goodTillCanceled=False, allOrNone=False)

Submits a stop order.

Parameters:
  • instrument (string.) – Instrument identifier.
  • stopPrice (float.) – Stop price.
  • quantity (int/float.) – The amount of shares. Positive means buy, negative means sell.
  • goodTillCanceled (boolean.) – True if the order is good till canceled. If False then the order gets automatically canceled when the session closes.
  • allOrNone (boolean.) – True if the order should be completely filled or not at all.
Return type:

The pyalgotrade.broker.StopOrder submitted.

stopLimitOrder(instrument, stopPrice, limitPrice, quantity, goodTillCanceled=False, allOrNone=False)

Submits a stop limit order.

Parameters:
  • instrument (string.) – Instrument identifier.
  • stopPrice (float.) – Stop price.
  • limitPrice (float.) – Limit price.
  • quantity (int/float.) – The amount of shares. Positive means buy, negative means sell.
  • goodTillCanceled (boolean.) – True if the order is good till canceled. If False then the order gets automatically canceled when the session closes.
  • allOrNone (boolean.) – True if the order should be completely filled or not at all.
Return type:

The pyalgotrade.broker.StopLimitOrder submitted.

enterLong(instrument, quantity, goodTillCanceled=False, allOrNone=False)

Generates a buy pyalgotrade.broker.MarketOrder to enter a long position.

Parameters:
  • instrument (string.) – Instrument identifier.
  • quantity (int.) – Entry order quantity.
  • goodTillCanceled (boolean.) – True if the entry order is good till canceled. If False then the order gets automatically canceled when the session closes.
  • allOrNone (boolean.) – True if the orders should be completely filled or not at all.
Return type:

The pyalgotrade.strategy.position.Position entered.

enterShort(instrument, quantity, goodTillCanceled=False, allOrNone=False)

Generates a sell short pyalgotrade.broker.MarketOrder to enter a short position.

Parameters:
  • instrument (string.) – Instrument identifier.
  • quantity (int.) – Entry order quantity.
  • goodTillCanceled (boolean.) – True if the entry order is good till canceled. If False then the order gets automatically canceled when the session closes.
  • allOrNone (boolean.) – True if the orders should be completely filled or not at all.
Return type:

The pyalgotrade.strategy.position.Position entered.

enterLongLimit(instrument, limitPrice, quantity, goodTillCanceled=False, allOrNone=False)

Generates a buy pyalgotrade.broker.LimitOrder to enter a long position.

Parameters:
  • instrument (string.) – Instrument identifier.
  • limitPrice (float.) – Limit price.
  • quantity (int.) – Entry order quantity.
  • goodTillCanceled (boolean.) – True if the entry order is good till canceled. If False then the order gets automatically canceled when the session closes.
  • allOrNone (boolean.) – True if the orders should be completely filled or not at all.
Return type:

The pyalgotrade.strategy.position.Position entered.

enterShortLimit(instrument, limitPrice, quantity, goodTillCanceled=False, allOrNone=False)

Generates a sell short pyalgotrade.broker.LimitOrder to enter a short position.

Parameters:
  • instrument (string.) – Instrument identifier.
  • limitPrice (float.) – Limit price.
  • quantity (int.) – Entry order quantity.
  • goodTillCanceled (boolean.) – True if the entry order is good till canceled. If False then the order gets automatically canceled when the session closes.
  • allOrNone (boolean.) – True if the orders should be completely filled or not at all.
Return type:

The pyalgotrade.strategy.position.Position entered.

enterLongStop(instrument, stopPrice, quantity, goodTillCanceled=False, allOrNone=False)

Generates a buy pyalgotrade.broker.StopOrder to enter a long position.

Parameters:
  • instrument (string.) – Instrument identifier.
  • stopPrice (float.) – Stop price.
  • quantity (int.) – Entry order quantity.
  • goodTillCanceled (boolean.) – True if the entry order is good till canceled. If False then the order gets automatically canceled when the session closes.
  • allOrNone (boolean.) – True if the orders should be completely filled or not at all.
Return type:

The pyalgotrade.strategy.position.Position entered.

enterShortStop(instrument, stopPrice, quantity, goodTillCanceled=False, allOrNone=False)

Generates a sell short pyalgotrade.broker.StopOrder to enter a short position.

Parameters:
  • instrument (string.) – Instrument identifier.
  • stopPrice (float.) – Stop price.
  • quantity (int.) – Entry order quantity.
  • goodTillCanceled (boolean.) – True if the entry order is good till canceled. If False then the order gets automatically canceled when the session closes.
  • allOrNone (boolean.) – True if the orders should be completely filled or not at all.
Return type:

The pyalgotrade.strategy.position.Position entered.

enterLongStopLimit(instrument, stopPrice, limitPrice, quantity, goodTillCanceled=False, allOrNone=False)

Generates a buy pyalgotrade.broker.StopLimitOrder order to enter a long position.

Parameters:
  • instrument (string.) – Instrument identifier.
  • stopPrice (float.) – Stop price.
  • limitPrice (float.) – Limit price.
  • quantity (int.) – Entry order quantity.
  • goodTillCanceled (boolean.) – True if the entry order is good till canceled. If False then the order gets automatically canceled when the session closes.
  • allOrNone (boolean.) – True if the orders should be completely filled or not at all.
Return type:

The pyalgotrade.strategy.position.Position entered.

enterShortStopLimit(instrument, stopPrice, limitPrice, quantity, goodTillCanceled=False, allOrNone=False)

Generates a sell short pyalgotrade.broker.StopLimitOrder order to enter a short position.

Parameters:
  • instrument (string.) – Instrument identifier.
  • stopPrice (float.) – The Stop price.
  • limitPrice (float.) – Limit price.
  • quantity (int.) – Entry order quantity.
  • goodTillCanceled (boolean.) – True if the entry order is good till canceled. If False then the order gets automatically canceled when the session closes.
  • allOrNone (boolean.) – True if the orders should be completely filled or not at all.
Return type:

The pyalgotrade.strategy.position.Position entered.

onEnterOk(position)

Override (optional) to get notified when the order submitted to enter a position was filled. The default implementation is empty.

Parameters:position (pyalgotrade.strategy.position.Position.) – A position returned by any of the enterLongXXX or enterShortXXX methods.
onEnterCanceled(position)

Override (optional) to get notified when the order submitted to enter a position was canceled. The default implementation is empty.

Parameters:position (pyalgotrade.strategy.position.Position.) – A position returned by any of the enterLongXXX or enterShortXXX methods.
onExitOk(position)

Override (optional) to get notified when the order submitted to exit a position was filled. The default implementation is empty.

Parameters:position (pyalgotrade.strategy.position.Position.) – A position returned by any of the enterLongXXX or enterShortXXX methods.
onExitCanceled(position)

Override (optional) to get notified when the order submitted to exit a position was canceled. The default implementation is empty.

Parameters:position (pyalgotrade.strategy.position.Position.) – A position returned by any of the enterLongXXX or enterShortXXX methods.
onStart()

Override (optional) to get notified when the strategy starts executing. The default implementation is empty.

onFinish(bars)

Override (optional) to get notified when the strategy finished executing. The default implementation is empty.

Parameters:bars (pyalgotrade.bar.Bars.) – The last bars processed.
onIdle()

Override (optional) to get notified when there are no events.

Note

In a pure backtesting scenario this will not be called.

onBars(bars)

Override (mandatory) to get notified when new bars are available. The default implementation raises an Exception.

This is the method to override to enter your trading logic and enter/exit positions.

Parameters:bars (pyalgotrade.bar.Bars.) – The current bars.
onOrderUpdated(order)

Override (optional) to get notified when an order gets updated.

Parameters:order (pyalgotrade.broker.Order.) – The order updated.
run()

Call once (and only once) to run the strategy.

stop()

Stops a running strategy.

attachAnalyzer(strategyAnalyzer)

Adds a pyalgotrade.stratanalyzer.StrategyAnalyzer.

debug(msg)

Logs a message with level DEBUG on the strategy logger.

info(msg)

Logs a message with level INFO on the strategy logger.

warning(msg)

Logs a message with level WARNING on the strategy logger.

error(msg)

Logs a message with level ERROR on the strategy logger.

critical(msg)

Logs a message with level CRITICAL on the strategy logger.

resampleBarFeed(frequency, callback)

Builds a resampled barfeed that groups bars by a certain frequency.

Parameters:
  • frequency – The grouping frequency in seconds. Must be > 0.
  • callback – A function similar to onBars that will be called when new bars are available.
Return type:

pyalgotrade.barfeed.BaseBarFeed.

class pyalgotrade.strategy.BacktestingStrategy(barFeed, cash_or_brk=1000000)

Bases: pyalgotrade.strategy.BaseStrategy

Base class for backtesting strategies.

Parameters:

Note

This is a base class and should not be used directly.

setDebugMode(debugOn)

Enable/disable debug level messages in the strategy and backtesting broker. This is enabled by default.

Position

class pyalgotrade.strategy.position.Position(strategy, entryOrder, goodTillCanceled, allOrNone)

Bases: object

Base class for positions.

Positions are higher level abstractions for placing orders. They are escentially a pair of entry-exit orders and allow to track returns and PnL easier that placing orders manually.

Parameters:
  • strategy (pyalgotrade.strategy.BaseStrategy.) – The strategy that this position belongs to.
  • entryOrder (pyalgotrade.broker.Order) – The order used to enter the position.
  • goodTillCanceled (boolean.) – True if the entry order should be set as good till canceled.
  • allOrNone (boolean.) – True if the orders should be completely filled or not at all.

Note

This is a base class and should not be used directly.

getShares()

Returns the number of shares. This will be a possitive number for a long position, and a negative number for a short position.

Note

If the entry order was not filled, or if the position is closed, then the number of shares will be 0.

entryActive()

Returns True if the entry order is active.

entryFilled()

Returns True if the entry order was filled.

exitActive()

Returns True if the exit order is active.

exitFilled()

Returns True if the exit order was filled.

getEntryOrder()

Returns the pyalgotrade.broker.Order used to enter the position.

getExitOrder()

Returns the pyalgotrade.broker.Order used to exit the position. If this position hasn’t been closed yet, None is returned.

getInstrument()

Returns the instrument used for this position.

getReturn(includeCommissions=True)

Calculates cumulative percentage returns up to this point. If the position is not closed, these will be unrealized returns.

Parameters:includeCommissions (boolean.) – True to include commisions in the calculation.
getPnL(includeCommissions=True)

Calculates PnL up to this point. If the position is not closed, these will be unrealized PnL.

Parameters:includeCommissions (boolean.) – True to include commisions in the calculation.
cancelEntry()

Cancels the entry order if its active.

cancelExit()

Cancels the exit order if its active.

exitMarket(goodTillCanceled=None)

Submits a market order to close this position.

Parameters:goodTillCanceled (boolean.) – True if the exit order is good till canceled. If False then the order gets automatically canceled when the session closes. If None, then it will match the entry order.

Note

  • If the position is closed (entry canceled or exit filled) this won’t have any effect.
  • If the exit order for this position is pending, an exception will be raised. The exit order should be canceled first.
  • If the entry order is active, cancellation will be requested.
exitLimit(limitPrice, goodTillCanceled=None)

Submits a limit order to close this position.

Parameters:
  • limitPrice (float.) – The limit price.
  • goodTillCanceled (boolean.) – True if the exit order is good till canceled. If False then the order gets automatically canceled when the session closes. If None, then it will match the entry order.

Note

  • If the position is closed (entry canceled or exit filled) this won’t have any effect.
  • If the exit order for this position is pending, an exception will be raised. The exit order should be canceled first.
  • If the entry order is active, cancellation will be requested.
exitStop(stopPrice, goodTillCanceled=None)

Submits a stop order to close this position.

Parameters:
  • stopPrice (float.) – The stop price.
  • goodTillCanceled (boolean.) – True if the exit order is good till canceled. If False then the order gets automatically canceled when the session closes. If None, then it will match the entry order.

Note

  • If the position is closed (entry canceled or exit filled) this won’t have any effect.
  • If the exit order for this position is pending, an exception will be raised. The exit order should be canceled first.
  • If the entry order is active, cancellation will be requested.
exitStopLimit(stopPrice, limitPrice, goodTillCanceled=None)

Submits a stop limit order to close this position.

Parameters:
  • stopPrice (float.) – The stop price.
  • limitPrice (float.) – The limit price.
  • goodTillCanceled (boolean.) – True if the exit order is good till canceled. If False then the order gets automatically canceled when the session closes. If None, then it will match the entry order.

Note

  • If the position is closed (entry canceled or exit filled) this won’t have any effect.
  • If the exit order for this position is pending, an exception will be raised. The exit order should be canceled first.
  • If the entry order is active, cancellation will be requested.
isOpen()

Returns True if the position is open.

getAge()

Returns the duration in open state.

Return type:datetime.timedelta.

Note

  • If the position is open, then the difference between the entry datetime and the datetime of the last bar is returned.
  • If the position is closed, then the difference between the entry datetime and the exit datetime is returned.

Table Of Contents

Previous topic

broker – Order management classes

Next topic

stratanalyzer – Strategy analyzers

This Page