Futures and options

The following functions can be used for trading and analyzing futures, binary, american, or european options, and futures options (contract.c must be included):

contractUpdate (string Name, int Handle, int Mode): int

Deletes all options or futures, and loads a new contract chain for the current day and the underlying with given Name. Returns the number of contracts in the chain. In [Test] or [Train] mode the chain is copied from a historical dataset of CONTRACT records with the given Handle that was previously loaded with dataLoad or dataParse. In [Trade] mode the chain is downloaded from the broker API, which can take several minutes dependent on Internet speed and number of contracts. Contract chains have no history and can only be loaded after the Lookback period. While the chain is loading, no trades can be entered or closed, so don't call this function too often. The ask/bid prices are only loaded for the contracts of open trades; use contractPrice to get prices of other contracts. This function needs only be called once per day; it must not be called in a TMF or trade enumeration loop.

contract (int Type, int Expiry, var Strike): CONTRACT*

Selects the option or future contract from the option chain that matches exactly the given Type, Expiry date, and Strike value. Returns a CONTRACT pointer to the found contract, or 0 when no such contract was found. If a contract is selected, enterLong and enterShort will buy or write (sell short) the contract instead of the underlying asset. Calling asset, contractUpdate, or contract(0) deselects the contract and allows again trading with the underlying.

contract (int Type, int Days, var Strike): CONTRACT*

As above, but selects the option or future contract with the given Type closest to the given minimum life time in Days and the given Strike value. Returns a CONTRACT pointer, or 0 when no contract was found.


As above, but selects directly the given option or future contract.

contract (TRADE*): CONTRACT*

As above, but selects the contract of the given trade from the current contract chain. Returns 0 if no contract for this trade was found.

contractDays (CONTRACT*): var

contractDays (TRADE*): var

Returns the fractional number of calendar days until contract resp. trade expiration date, assuming an expiration time of 20:00 UTC. Returns a negative number when the expiration date is in the past.

contractPrice (CONTRACT*): var

contractPrice (TRADE*): var

Updates the current ask and bid price of the selected contract or trade from the broker or from the historical data, and returns the bid/ask average. If the contract is not traded, the prices are 0. For a fast reaction on changed prices, call this function once per bar (or even more often) for all open contract trades.

contractPosition (TRADE*): int

Returns the current number of open contracts of the given trade (negative values for a short position). Can be used for determining if a certain contract was expired or exercised by the broker. The GET_POSITION command must be supported by the broker API, and no other trades with the same contract type, strike, and expiry must be opened.

contractCheck (TRADE*): int

Checks if the option trade is still open. If not, it is assumed that it was expired or exercised. Open positions of the underlying are then also checked and automatically sold at market. This function can be called regularly in a for(open_trades) loop for keeping the positions between broker and strategy in sync. The GET_POSITION command must be supported by the broker API, and no other trades with the same contract type, strike, expiry, and underlying must be opened.

contractRoll (TRADE*, int Days, var Strike, function TMF): TRADE*

Rolls a closed option or future contract by opening a duplicate with the same type, volume, stop loss and profit distances, the given number of Days until expiration, the given Strike (0 for using the previous strike) and an optional trade management function. Returns a pointer to the new trade, or 0 if the contract could not be rolled. Source code in contract.c.

contractExercise (TRADE*)

Exercises an option. In the backtest, the option is closed at its intrinsic price. In live trading, an order to exercise the option is sent to the broker. It is normally not immediately executed, but pending. Use contractCheck() for closing the trade and selling the underlying as soon as the order was executed. Don't call this function for European options before expiration, or for options that are not in the money.

contractVal (CONTRACT*, var Price, var HistVol, var Dividend, var RiskFree, var* Delta, var* Gamma, var* Vega, var* Theta, var* Rho): var

Returns the theoretical value and optionally the greeks of the given option contract at the given Price of the underlying. Uses the RQuantLib package; R must be installed and initRQL() must be called in the initial run. Source code in contract.c.

contractIntrinsic (CONTRACT*, var Price): var

contractIntrinsic (TRADE*, var Price): var

Returns the intrinsic value of the option contract at the given Price of the underlying. The intrinsic value of a call option is the difference between price and strike; for put options it's the difference between strike and price. A positive difference means that the option is in the money. Source code in contract.c.

contractVol (CONTRACT*, var Price, var HistVol, var Value, var Dividend, var RiskFree): var

Returns the implied volatility of the of the given option contract based on the given Value. Uses the RQuantLib package; R must be installed and initRQL() must be called in the initial run. Source code in contract.c.

yield(): var

Helper function, returns the current yield rate of 3-months US treasury bills in percent. Can be used as a proxy of the risk-free interest for calculating the values of option contracts. Works in backtest as well as live trading. Quandl Bridge or Zorro S required. Source code in contract.c.

dmy(int Expiry): var

ymd(var Date): int

Helper functions, convert an expiration date in the YYYYMMDD format to the Windows DATE format and vice versa. Source code in contract.c.

nthDay(int Year, int Month, int Dow, int N): var

Helper function, returns the Windows DATE format of the Nth given weekday of the given month. For instance, nthDay(2016,11,FRIDAY,3) returns the date of the third friday in November 2016. Source code in contract.c.


Name The name of the underlying, f.i. "ES" or "SPY", or Asset for the current asset.
Handle A number from 1...1000 that identifies the dataset containing a CONTRACT list with historical options data. See remarks and dataset handling.
Mode PUT|CALL for options, FUTURE for futures, PUT|CALL|FUTURE for options on futures.
Type The contract type, any meaningful combination of FUTURE, PUT, CALL, EUROPEAN, BINARY. Add ONLYW3 for selecting only contracts that expire between the 16th and the 21th of the month.
Days The number of calendar days until expiration, with one week tolerance.
Expiry The expiration date in the YYYYMMDD format.
Strike Option strike price rounded to 1 dollar, or 0 for futures.
HistVol The historical volatility of the underlying asset, f.i. from the Volatility indicator. Normally taken from the last 20 days.
Dividend The annual dividend yield of the underlying, as a fraction, f.i. 0.02 for 2% dividend yield.
RiskFree The risk-free interest rate, as a fraction, f.i. yield()/100.
Value The value of the option for determining the implied volatility.
TRADE* The pointer of an option or future trade. Use ThisTrade for the trade pointer in a TMF or trade enumeration loop.



// Sell call and put options at 1 stddev of the underlying
// Buy them back 2 days before expiration #include <contract.c> void run() { BarPeriod = 1440; BarZone = ET; BarOffset = 15*60; // trade at 3 pm Eastern time if(is(FIRSTINITRUN)) { assetList("AssetsIB"); assetHistory("SPY",FROM_YAHOO|UNADJUSTED); asset("SPY"); dataLoad(1,"SPY_Options.t8",9); // historical options data } contractUpdate(Asset,1,PUT|CALL); vars Close = series(priceClose()); int DTE = 6*7; // look for 6-week contracts var Strangle = StdDev(Close,20); CONTRACT* Call = contract(CALL,DTE,Close[0] + Strangle); CONTRACT* Put = contract(PUT,DTE,Close[0] - Strangle); if(!NumOpenTotal && Call && Put && !is(LOOKBACK)) { contract(Call); enterShort(); contract(Put); enterShort(); } // Check expiration and buy them back when in the money for(open_trades) { if(contractDays(ThisTrade) <= 2 and contractIntrinsic(ThisTrade,Close[0]) > 0)) exitTrade(ThisTrade); } }

See also:

enterLong/Short, exitLong/Short, asset, Quandl bridge, contract variables


► latest version online