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 previously loaded contracts, and loads a new contract chain for the current time and the currently selected underlying asset. Sets NumContracts to the number of contracts in the chain, which is also returned. In [Test] or [Train] mode the chain is copied from a dataset containing CONTRACT records, which is either automatically obtained from a Name.t8 file, or copied from a previously loaded dataset with the given Handle. In [Trade] mode the chain for the symbol given with Name is downloaded from the broker API (which can take several minutes with large chains). 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 normally 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. The contract chain is stored per asset, so the underlying asset must be selected with asset() before calling contractUpdate().

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

Selects the option or future contract from the current 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,0,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.

contract (int N): CONTRACT*

As above, but selects the Nth contract from the current contract chain, where N = 1..NumContracts. If N = 0, the currently selected contract is deselected in order to allow trading with the underlying.

contract (CONTRACT*): CONTRACT*

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, which can happen at the expiration day or when the chain was not updated.

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.

contractPrint ()

Exports the current contract chain to a CSV file, for diagnostics purposes,

contractPrint (CONTRACT*)

Prints the given contract parameters to the log file for diagnostics purposes, in the order Date, Type, Expiry, Strike, Underlying, Ask, Bid, fVal.
 

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. Type, fStrike, and Expiry of the contract must be set; the other parameters don't matter. Expiry can be either an expiration date in the YYYYMMDD format, or alternatively the number of calendar days until expiration. HistVol is the underlying annual volatility of the log returns, f.i. by Volatility or VolatilityOV (usually over 20 days). Dividend is the continuous annual dividend yield per year of the underlying, as a fraction in the 0..1 range. RiskFree is the annual risk-free yield as a fraction in the 0..1 range, f.i. by yield()/100.
Delta is the impact of an underlying price change on the option value, in the 0..1 range for calls and 0..-1 for puts. Gamma is the impact on Delta. Vega is the impact of a change of the underlying volatility, Theta is the impact of a change of the expiration time, and Rho is the impact of a change of the risk-free yield. The function uses R and the RQuantLib package; both must be installed on the trading PC (see remarks below). 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. Type and fStrike of the contract or trade must be set; the other parameters don't matter. Source code in contract.c.

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

Returns the implied volatility of the given option contract with the given Value. For the other parameters, see contractVal. The implied volatility is an estimate of the future volatility of the underlying, based on the current option parameters. The function uses R and the RQuantLib package; both must be installed on the trading PC (see remarks below). 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 (divide it by 100 for using it in contractVal or contractVol). Works in backtest as well as live trading. Zorro S required for Quandl data access; enter your Quandl key in the QuandlKey field in Zorro.ini. 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. The expression dmy(Expiry) - wdate() converts an expiration date to a number of calendar days.

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.


Parameters:

Name The name of the underlying, f.i. "ES" or "SPY", or Asset for the current asset.
Handle A number from 1...800 that identifies a previously loaded dataset containing a CONTRACT list with historical options data; or 0 for automatically loading a dataset from a file Name.t8 in the History folder.
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, and BINARY. Add +ONLYW3 for selecting only contracts that expire between the 16th and the 21th of the month. Add +ONLYMATCH for selecting only contracts that exactly match the expiration date and strike price.
Days The minimum number of calendar days until expiration. The closest expiration date will be selected.
Expiry The expiration date in the YYYYMMDD format.
Strike Option strike price, or 0 for futures.
HistVol The historical volatility of the underlying asset, f.i. from the Volatility or VolatilityOV indicators. 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.

Remarks:

Example:

// 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 assetList("AssetsIB"); assetHistory("SPY",FROM_AV|UNADJUSTED); asset("SPY"); contractUpdate(Asset,0,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