broker – Order management classes

Base module and classes

class pyalgotrade.broker.Order(orderId, type_, action, instrument, quantity)

Bases: object

Base class for orders.

Parameters:
  • orderId (string.) – The order id.
  • type (Order.Type) – The order type
  • action (Order.Action) – The order action.
  • instrument (string.) – Instrument identifier.
  • quantity (int/float.) – Order quantity.

Note

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

Valid type parameter values are:

  • Order.Type.MARKET
  • Order.Type.LIMIT
  • Order.Type.STOP
  • Order.Type.STOP_LIMIT

Valid action parameter values are:

  • Order.Action.BUY
  • Order.Action.BUY_TO_COVER
  • Order.Action.SELL
  • Order.Action.SELL_SHORT
getId()

Returns the order id.

getType()

Returns the order type. Valid order types are:

  • Order.Type.MARKET
  • Order.Type.LIMIT
  • Order.Type.STOP
  • Order.Type.STOP_LIMIT
getAction()

Returns the order action. Valid order actions are:

  • Order.Action.BUY
  • Order.Action.BUY_TO_COVER
  • Order.Action.SELL
  • Order.Action.SELL_SHORT
getState()

Returns the order state. Valid order states are:

  • Order.State.INITIAL (the initial state).
  • Order.State.SUBMITTED
  • Order.State.ACCEPTED
  • Order.State.CANCELED
  • Order.State.PARTIALLY_FILLED
  • Order.State.FILLED
isActive()

Returns True if the order is active.

isInitial()

Returns True if the order state is Order.State.INITIAL.

isSubmitted()

Returns True if the order state is Order.State.SUBMITTED.

isAccepted()

Returns True if the order state is Order.State.ACCEPTED.

isCanceled()

Returns True if the order state is Order.State.CANCELED.

isPartiallyFilled()

Returns True if the order state is Order.State.PARTIALLY_FILLED.

isFilled()

Returns True if the order state is Order.State.FILLED.

getInstrument()

Returns the instrument identifier.

getQuantity()

Returns the quantity.

getFilled()

Returns the number of shares that have been executed.

getRemaining()

Returns the number of shares still outstanding.

getAvgFillPrice()

Returns the average price of the shares that have been executed, or None if nothing has been filled.

getGoodTillCanceled()

Returns True if the order is good till canceled.

setGoodTillCanceled(goodTillCanceled)

Sets if the order should be good till canceled. Orders that are not filled by the time the session closes will be will be automatically canceled if they were not set as good till canceled

Parameters:goodTillCanceled (boolean.) – True if the order should be good till canceled.

Note

This can’t be changed once the order is submitted.

getAllOrNone()

Returns True if the order should be completely filled or else canceled.

setAllOrNone(allOrNone)

Sets the All-Or-None property for this order.

Parameters:allOrNone (boolean.) – True if the order should be completely filled.

Note

This can’t be changed once the order is submitted.

getExecutionInfo()

Returns the last execution information for this order, or None if nothing has been filled so far. This will be different every time an order, or part of it, gets filled.

Return type:OrderExecutionInfo.
class pyalgotrade.broker.MarketOrder(orderId, action, instrument, quantity, onClose)

Bases: pyalgotrade.broker.Order

Base class for market orders.

Note

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

getFillOnClose()

Returns True if the order should be filled as close to the closing price as possible (Market-On-Close order).

class pyalgotrade.broker.LimitOrder(orderId, action, instrument, limitPrice, quantity)

Bases: pyalgotrade.broker.Order

Base class for limit orders.

Note

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

getLimitPrice()

Returns the limit price.

class pyalgotrade.broker.StopOrder(orderId, action, instrument, stopPrice, quantity)

Bases: pyalgotrade.broker.Order

Base class for stop orders.

Note

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

getStopPrice()

Returns the stop price.

class pyalgotrade.broker.StopLimitOrder(orderId, action, instrument, stopPrice, limitPrice, quantity)

Bases: pyalgotrade.broker.Order

Base class for stop limit orders.

Note

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

getStopPrice()

Returns the stop price.

getLimitPrice()

Returns the limit price.

class pyalgotrade.broker.OrderExecutionInfo(price, quantity, commission, dateTime)

Bases: object

Execution information for an order.

getPrice()

Returns the fill price.

getQuantity()

Returns the quantity.

getCommission()

Returns the commission applied.

getDateTime()

Returns the datatime.datetime when the order was executed.

class pyalgotrade.broker.Broker

Bases: pyalgotrade.observer.Subject

Base class for brokers.

Note

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

getShares(instrument)

Returns the number of shares for an instrument.

getPositions()

Returns a dictionary that maps instruments to shares.

getActiveOrders(instrument=None)

Returns a sequence with the orders that are still active.

Parameters:instrument (string.) – An optional instrument identifier to return only the active orders for the given instrument.
placeOrder(order)

Submits an order.

Parameters:order (Order.) – The order to submit.

Note

  • After this call the order is in SUBMITTED state and an event is not triggered for this transition.
  • Calling this twice on the same order will raise an exception.
createMarketOrder(action, instrument, quantity, onClose=False)

Creates a Market order. A market order is an order to buy or sell a stock at the best available price. Generally, this type of order will be executed immediately. However, the price at which a market order will be executed is not guaranteed.

Parameters:
  • action (Order.Action.BUY, or Order.Action.BUY_TO_COVER, or Order.Action.SELL or Order.Action.SELL_SHORT.) – The order action.
  • instrument (string.) – Instrument identifier.
  • quantity (int/float.) – Order quantity.
  • onClose (boolean.) – True if the order should be filled as close to the closing price as possible (Market-On-Close order). Default is False.
Return type:

A MarketOrder subclass.

createLimitOrder(action, instrument, limitPrice, quantity)

Creates a Limit order. A limit order is an order to buy or sell a stock at a specific price or better. A buy limit order can only be executed at the limit price or lower, and a sell limit order can only be executed at the limit price or higher.

Parameters:
  • action (Order.Action.BUY, or Order.Action.BUY_TO_COVER, or Order.Action.SELL or Order.Action.SELL_SHORT.) – The order action.
  • instrument (string.) – Instrument identifier.
  • limitPrice (float) – The order price.
  • quantity (int/float.) – Order quantity.
Return type:

A LimitOrder subclass.

createStopOrder(action, instrument, stopPrice, quantity)

Creates a Stop order. A stop order, also referred to as a stop-loss order, is an order to buy or sell a stock once the price of the stock reaches a specified price, known as the stop price. When the stop price is reached, a stop order becomes a market order. A buy stop order is entered at a stop price above the current market price. Investors generally use a buy stop order to limit a loss or to protect a profit on a stock that they have sold short. A sell stop order is entered at a stop price below the current market price. Investors generally use a sell stop order to limit a loss or to protect a profit on a stock that they own.

Parameters:
  • action (Order.Action.BUY, or Order.Action.BUY_TO_COVER, or Order.Action.SELL or Order.Action.SELL_SHORT.) – The order action.
  • instrument (string.) – Instrument identifier.
  • stopPrice (float) – The trigger price.
  • quantity (int/float.) – Order quantity.
Return type:

A StopOrder subclass.

createStopLimitOrder(action, instrument, stopPrice, limitPrice, quantity)

Creates a Stop-Limit order. A stop-limit order is an order to buy or sell a stock that combines the features of a stop order and a limit order. Once the stop price is reached, a stop-limit order becomes a limit order that will be executed at a specified price (or better). The benefit of a stop-limit order is that the investor can control the price at which the order can be executed.

Parameters:
  • action (Order.Action.BUY, or Order.Action.BUY_TO_COVER, or Order.Action.SELL or Order.Action.SELL_SHORT.) – The order action.
  • instrument (string.) – Instrument identifier.
  • stopPrice (float) – The trigger price.
  • limitPrice (float) – The price for the limit order.
  • quantity (int/float.) – Order quantity.
Return type:

A StopLimitOrder subclass.

cancelOrder(order)

Requests an order to be canceled. If the order is filled an Exception is raised.

Parameters:order (Order.) – The order to cancel.

Backtesting module and classes

class pyalgotrade.broker.backtesting.Commission

Bases: object

Base class for implementing different commission schemes.

Note

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

calculate(order, price, quantity)

Calculates the commission for an order execution.

Parameters:
  • order (pyalgotrade.broker.Order.) – The order being executed.
  • price (float.) – The price for each share.
  • quantity (float.) – The order size.
Return type:

float.

class pyalgotrade.broker.backtesting.NoCommission

Bases: pyalgotrade.broker.backtesting.Commission

A Commission class that always returns 0.

class pyalgotrade.broker.backtesting.FixedPerTrade(amount)

Bases: pyalgotrade.broker.backtesting.Commission

A Commission class that charges a fixed amount for the whole trade.

Parameters:amount (float.) – The commission for an order.
class pyalgotrade.broker.backtesting.TradePercentage(percentage)

Bases: pyalgotrade.broker.backtesting.Commission

A Commission class that charges a percentage of the whole trade.

Parameters:percentage (float.) – The percentage to charge. 0.01 means 1%, and so on. It must be smaller than 1.
class pyalgotrade.broker.backtesting.Broker(cash, barFeed, commission=None)

Bases: pyalgotrade.broker.Broker

Backtesting broker.

Parameters:
  • cash (int/float.) – The initial amount of cash.
  • barFeed (pyalgotrade.barfeed.BarFeed) – The bar feed that will provide the bars.
  • commission (Commission) – An object responsible for calculating order commissions.
getCash(includeShort=True)

Returns the available cash.

Parameters:includeShort (boolean.) – Include cash from short positions.
getCommission()

Returns the strategy used to calculate order commissions.

Return type:Commission.
getEquity()

Returns the portfolio value (cash + shares).

getFillStrategy()

Returns the FillStrategy currently set.

setCommission(commission)

Sets the strategy to use to calculate order commissions.

Parameters:commission (Commission.) – An object responsible for calculating order commissions.
setFillStrategy(strategy)

Sets the FillStrategy to use.

class pyalgotrade.broker.backtesting.FillStrategy

Bases: object

Base class for order filling strategies.

fillLimitOrder(order, broker_, bar)

Override to return the fill price and quantity for a limit order or None if the order can’t be filled at the given time.

Parameters:
Return type:

A FillInfo or None if the order should not be filled.

fillMarketOrder(order, broker_, bar)

Override to return the fill price and quantity for a market order or None if the order can’t be filled at the given time.

Parameters:
Return type:

A FillInfo or None if the order should not be filled.

fillStopLimitOrder(order, broker_, bar)

Override to return the fill price and quantity for a stop limit order or None if the order can’t be filled at the given time.

Parameters:
Return type:

A FillInfo or None if the order should not be filled.

fillStopOrder(order, broker_, bar)

Override to return the fill price and quantity for a stop order or None if the order can’t be filled at the given time.

Parameters:
Return type:

A FillInfo or None if the order should not be filled.

onBars(dateTime, bars)

Override (optional) to get notified when the broker is about to process new bars.

onOrderFilled(order)

Override (optional) to get notified when an order was filled, or partially filled.

class pyalgotrade.broker.backtesting.DefaultStrategy(volumeLimit=0.25)

Bases: pyalgotrade.broker.backtesting.FillStrategy

Default fill strategy.

Parameters:volumeLimit (float.) – The proportion of the volume that orders can take up in a bar. Must be > 0 and <= 1.

This strategy works as follows:

  • A pyalgotrade.broker.MarketOrder is always filled using the open/close price.

  • A pyalgotrade.broker.LimitOrder will be filled like this:
    • If the limit price was penetrated with the open price, then the open price is used.
    • If the bar includes the limit price, then the limit price is used.
    • Note that when buying the price is penetrated if it gets <= the limit price, and when selling the price is penetrated if it gets >= the limit price
  • A pyalgotrade.broker.StopOrder will be filled like this:
    • If the stop price was penetrated with the open price, then the open price is used.
    • If the bar includes the stop price, then the stop price is used.
    • Note that when buying the price is penetrated if it gets >= the stop price, and when selling the price is penetrated if it gets <= the stop price
  • A pyalgotrade.broker.StopLimitOrder will be filled like this:
    • If the stop price was penetrated with the open price, or if the bar includes the stop price, then the limit order becomes active.

    • If the limit order is active:
      • If the limit order was activated in this same bar and the limit price is penetrated as well, then the best between the stop price and the limit fill price (as described earlier) is used.
      • If the limit order was activated at a previous bar then the limit fill price (as described earlier) is used.

Note

  • This is the default strategy used by the Broker.
  • If volumeLimit is 0.25, and a certain bar’s volume is 100, then no more than 25 shares can be used by all orders that get processed at that bar.
  • If using trade bars, then all the volume from that bar can be used.

Table Of Contents

Previous topic

technical – Technical indicators

Next topic

strategy – Basic strategy classes

This Page