com.optstack.api

StrategyRunnerT

abstract class StrategyRunnerT extends Logging2

All backtest strategies should extend / inherit the StrategyRunnerT class. This class sets up the test environment in which a backtest will be run. This class provides several helper functions that will allow you to define your desired trading strategies.

You will need to implement the handleData() function. The handleData() function is the function where you define your trading logic. This function will be called repeatedly, once with each timestep / tick of the data.

The initialize() function is optional and can be used to initialize any class variables. This function is invoked only once, before the handleData() function is invoked.

For example:

import com.optstack.api._
import com.optstack.api.strategies._
import com.optstack.math._
import com.optstack.api.Implicits._

class PutVertical (config:BacktestConfig) extends StrategyRunnerT (config) {

	// Nasdaq 100 Index (NDX)
	var ndx = this.getInstrument ("^NDX");

	// NDX 10 period / 50 period Moving Averages
	var movingAvg10 = ndx.studies.MovingAverage(timePeriod=10)
	var movingAvg50 = ndx.studies.MovingAverage(timePeriod=50)

	def handleData () = {

		//Plot the 10 period and 50 period Moving Averages
		this.plot(plotItem=movingAvg10,plotName="10 period")
		this.plot(plotItem=movingAvg50,plotName="50 period")

	    // if 10 period moving average crosses above 50 period moving average,
	    // sell a put vertical
	    if (movingAvg10.crossesAbove(movingAvg50)) {
	    	var vertical = ndx.strategies.verticals.PutVertical

	    	// select put vertical which meet the following criterias:
	    	//    5 - 30 days to expiration,
	    	//    distance between strikes of 50 - 150,
	    	//      delta of 10 - 30
			vertical.selectBy(false).
				 daysToExpiration(minDays=5,maxDays=30).
				 distanceBetweenStrikes(minWidth=50,maxWidth=150).
				 delta(minDelta=10,maxDelta=30)

			// size the position by quantity
			vertical.sizeBy.quantity(quantity=1)

			// sell put vertical spread with orderID = "MyVerticalSpreadID"
			// this orderID can be used to lookup the vertical spread for future adjustments
			vertical.sell("MyVerticalSpreadID", "Selling Vertical Spread")
	    }

	    // lookup any existing vertical spread by its orderID
	    // close existing vertical spreads if the profit is $3000 or greater
	    val existingVerticalSpreads = this.selectPosition(orderID="MyVerticalSpreadID");
		existingVerticalSpreads.foreach ({   curVerticalSpread =>
			if (curVerticalSpread.gainLoss > 3000) {
				curVerticalSpread.close("ClosingSpread: Profit > 3000, Profit=" + curVerticalSpread.gainLoss)
			}

		})

	  }

		def initialize () = { }
  }
Linear Supertypes
Logging2, AnyRef, Any
Ordering
  1. Alphabetic
  2. By inheritance
Inherited
  1. StrategyRunnerT
  2. Logging2
  3. AnyRef
  4. Any
  1. Hide All
  2. Show all
Learn more about member selection
Visibility
  1. Public
  2. All

Instance Constructors

  1. new StrategyRunnerT(config: BacktestConfig)

Abstract Value Members

  1. abstract def handleData(): Unit

    Define your trading logic within the handleData() function.

    Define your trading logic within the handleData() function. This function is called by the backtest engine repeatedly, once at each time step / tick.

    Variables that are declared in this function are reset with each time step loop. Therefore, if you need a variable that maintains state across time steps, declare such variable outside this function.

    Annotations
    @FunctionInfo()
  2. abstract def initialize(): Unit

    Define any initialization logic within the initialize() function.

    Define any initialization logic within the initialize() function. This function is called by the backtest engine once, before handleData() is invoked.

    Annotations
    @FunctionInfo()

Concrete Value Members

  1. final def !=(arg0: AnyRef): Boolean

    Definition Classes
    AnyRef
  2. final def !=(arg0: Any): Boolean

    Definition Classes
    Any
  3. final def ##(): Int

    Definition Classes
    AnyRef → Any
  4. final def ==(arg0: AnyRef): Boolean

    Definition Classes
    AnyRef
  5. final def ==(arg0: Any): Boolean

    Definition Classes
    Any
  6. final def asInstanceOf[T0]: T0

    Definition Classes
    Any
  7. def clone(): AnyRef

    Attributes
    protected[java.lang]
    Definition Classes
    AnyRef
    Annotations
    @throws( ... )
  8. final def eq(arg0: AnyRef): Boolean

    Definition Classes
    AnyRef
  9. def equals(arg0: Any): Boolean

    Definition Classes
    AnyRef → Any
  10. def finalize(): Unit

    Attributes
    protected[java.lang]
    Definition Classes
    AnyRef
    Annotations
    @throws( classOf[java.lang.Throwable] )
  11. final def getClass(): Class[_]

    Definition Classes
    AnyRef → Any
  12. final def getContext: RunContextT

    View / update the backtest settings, such as initial cash balance, margining type, slippage parameters, etc.

    View / update the backtest settings, such as initial cash balance, margining type, slippage parameters, etc..

    Annotations
    @FunctionInfo()
  13. final def getInstrument(symbol: String): SecurityT

    Get security / instrument by its symbol

    Get security / instrument by its symbol

    Annotations
    @FunctionInfo()
  14. final def getNumOpenPositions(orderID: String): Int

    Annotations
    @FunctionInfo()
  15. final def getOption(underlyingSymbol: String, callOrPut: String, expirationDate: Date, strike: Double): SecurityT

    Get call / put option associated with underlying symbol

    Get call / put option associated with underlying symbol

    Annotations
    @FunctionInfo()
  16. final def getPortfolio: PortfolioStatsT

    Get portfolio statistics, such as cost basis, market value, etc.

    Get portfolio statistics, such as cost basis, market value, etc..

    Annotations
    @FunctionInfo()
  17. def hashCode(): Int

    Definition Classes
    AnyRef → Any
  18. final def isInstanceOf[T0]: Boolean

    Definition Classes
    Any
  19. final def log(s: Any): Unit

    Print the argument.

    Print the argument. Logs will appear in the Logs Tab Panel. Useful for debugging your strategy

    Annotations
    @FunctionInfo()
  20. def logError(message: ⇒ Any): Unit

    Definition Classes
    Logging2
  21. final def ne(arg0: AnyRef): Boolean

    Definition Classes
    AnyRef
  22. final def notify(): Unit

    Definition Classes
    AnyRef
  23. final def notifyAll(): Unit

    Definition Classes
    AnyRef
  24. final def pause(millis: Int): Unit

    Pause execution of backtest for X milliseconds.

    Pause execution of backtest for X milliseconds. (Limit 5000 milliseconds)

    Annotations
    @FunctionInfo()
  25. final def plot(plotItem: Any, plotName: String, plotType: PlotTypeT = PlotTypeT.LINE, panel: PlotPanelT = PlotPanelT.LOWER_PANEL): Unit

    Plot various time series data, such as technical studies (Moving Averages, Bollinger Bands, Portfolio Profit / Loss, etc.

    Plot various time series data, such as technical studies (Moving Averages, Bollinger Bands, Portfolio Profit / Loss, etc...) Specify different types of plots (Line, Area, Candlestick, etc..) and whether to plot on Upper Panel or Lower Panels

    For example:

    //lookup Nasdaq 100 Index (NDX)
    val ndx = this.getInstrument ("^NDX");
    
    // NDX 50 period Moving Average
    val movingAvg50 = ndx.studies.MovingAverage(numPeriods=50)
    
    // plot 50 day moving average using Line chart on lower panel
    this.plot(plotItem=movingAvg50,plotName="50 day",plotType=PlotTypeT.LINE, PlotPanelT.LOWER_PANEL)
    Annotations
    @FunctionInfo()
  26. final def plot(plotItem: Any, plotName: String): Unit

    Plot various time series data, such as technical studies (Moving Averages, Bollinger Bands, Portfolio Profit / Loss, etc.

    Plot various time series data, such as technical studies (Moving Averages, Bollinger Bands, Portfolio Profit / Loss, etc...)

    For example:

    //lookup Nasdaq 100 Index (NDX)
    		val ndx = this.getInstrument ("^NDX");
    
    		// NDX 50 period Moving Average
    		val movingAvg50 = ndx.studies.MovingAverage(numPeriods=50)
    
    		// plot 50 day moving average
    		this.plot(plotItem=movingAvg50,plotName="50 period moving average")
    Annotations
    @FunctionInfo()
  27. final def plotPositions(positions: PositionsSequenceT[PositionT], plotName: String, methodToInvokeOnPositionT: String = "gainLoss"): Unit

    Plot attributes of a sequence of positions, such as gainLoss, delta, etc.

    Plot attributes of a sequence of positions, such as gainLoss, delta, etc. Useful when you have selected a list of positions, using "selectPosition" API

    For example:

    var positions= this.selectPosition(orderID="CoveredCall")
    this.plotPositions(positions, "MyCoveredCalls", "gainLoss")
    Annotations
    @FunctionInfo()
  28. def println(logLevel: Int, message: ⇒ Any): Unit

    Definition Classes
    Logging2
  29. def println(message: ⇒ Any): Unit

    Definition Classes
    Logging2
  30. final def selectPortfolio(): PositionT

    Select the portfolio

    Select the portfolio

    Annotations
    @FunctionInfo()
  31. final def selectPosition(orderID: String, removeClosedPositions: Boolean = true): PositionsSequenceT[PositionT]

    Select a position by its Order ID.

    Select a position by its Order ID. Returns a sequence of zero or more matching positions.

    To select by Order ID, be sure to specify the order ID when you buy / sell an order.

    val cc = ndx.strategies.withStock.CoveredCall
    cc.buy(quantity=10,orderID="vertical1001",comments="Enter CoveredCall When 50 Day MVG crosses above 200 Day MVG")
    
    .....
    .....
    
    // select the covered call order using the orderID
    val coveredCall = this.selectPosition(orderID="vertical1001")
    Annotations
    @FunctionInfo()
    See also

    com.optstack.api.strategies.OrderFiltersT

  32. final def synchronized[T0](arg0: ⇒ T0): T0

    Definition Classes
    AnyRef
  33. def toString(): String

    Definition Classes
    AnyRef → Any
  34. final def wait(): Unit

    Definition Classes
    AnyRef
    Annotations
    @throws( ... )
  35. final def wait(arg0: Long, arg1: Int): Unit

    Definition Classes
    AnyRef
    Annotations
    @throws( ... )
  36. final def wait(arg0: Long): Unit

    Definition Classes
    AnyRef
    Annotations
    @throws( ... )

Deprecated Value Members

  1. final def BarType: BarTypeHelperT.type

    Annotations
    @FunctionInfo() @deprecated
    Deprecated
  2. final def closePositions(position: PositionT, comments: String = ""): Unit

    Close the specified position

    Close the specified position

    Annotations
    @FunctionInfo() @deprecated
    Deprecated
  3. final def closePositions(positionID: String): Unit

    Close the position by its Position ID

    Close the position by its Position ID

    Annotations
    @FunctionInfo() @deprecated
    Deprecated
  4. final def orders: OrdersActionT.type

    Annotations
    @FunctionInfo() @deprecated
    Deprecated

Inherited from Logging2

Inherited from AnyRef

Inherited from Any

Ungrouped