Options, Futures, FOPs

The following functions can be used for trading and analyzing binary, american, or european options, futures, and options on futures (FOPs). For an introduction in options trading, see Workshop8 or Financial Hacker.

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

Deletes all previously loaded contracts, and loads a new contract chain for the currently selected underlying and the current time. In [Test] or [Train] mode the chain is either read out of a Name.t8 / Name_YYYY.t8 file containing historical contract chains, or filled from matching dates of a previously loaded dataset with the given Handle. In [Trade] mode the chain for the symbol given with Name is either downloaded from the broker API, or filled from a dataset with the given Handle with no date filtering. If Now is nonzero in [Test] or [Train] mode, it is used instead of the current time. The function sets ContractRow to the row of the first found contract in the dataset, and NumContracts to the number of contracts in the chain, which is also returned. If no contract chain for the given time is found, 0 is returned.
  Loading a chain from the broker API can take several seconds, during which no trades can be entered or closed. So don't call this function too often. It needs normally only be called once per day, and must not be called in a TMF or trade enumeration loop. The ask/bid prices are normally only loaded for the contracts of open trades; use contractPrice to get prices of other contracts. The contract chain is stored per asset, so the underlying asset must be selected with asset() before calling contractUpdate().

contractRecord (string Name, var MinStrike, var MaxStrike, int MinDays, int MaxDays)

Appends the current contract chain to the begin of the .t8 contract history in [Trade] mode. This allows recording live contract chains for re-training or other purposes. The prices of all recorded contracts are loaded from the broker API. Because loading contract prices can take a long time (up to 5 seconds per option contract with the IB API), the strike range and life time can be limited with the MinStrike, MaxStrike, MinDays, MaxDays parameters. Only contracts that fall into the limits and have a nonzero price are recorded. If the limits are 0, prices for the whole chain are loaded.

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. The function sets up ContractStrike, ContractExpiry and other contract variables, and sets ContractRow to the row of the selected contract in the historical dataset or in the options chain. 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 strike closest to the given Strike value or distance to the underlying. 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, and does not alter ContractRow.

contract (TRADE*): CONTRACT*

As above, but selects the trade and its contract 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. Otherwise trade variables and contract variables are available for the trade and contract. 

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

As above, but selects and returns the option or future contract with the Type and Expiry, but the next-higher strike than the given Strike value. If Strike is negative, selects and returns the contract with the next-lower strike value. 

contractFind (int Type, int Days, var Find, int N): CONTRACT*

As above, but selects the option or future contract with the given Type closest to the given minimum life time in Days, and a parameter closest to the given Find value. The parameter can be selected with N: 1 = ask, 2 = bid, 3 = fVal, 4 = fVol, 5 = fUnl, 6 = strike. Returns a CONTRACT pointer, or 0 when no contract was found. If a parameter is selected that is not yet available for the contract, such as ask, bid, or underlying price in live trading, it is automatically retrieved from the broker API. This can take a long time on the first call of this function after loading a new contract chain.

contractDays (CONTRACT*): var

contractDays (TRADE*): var

Returns the fractional number of calendar days until contract or trade expiration time. Returns a negative number when the expiration time is in the past. Because the exact time to expiration depends on the time zone and market close time of the exchange where the contract is traded, the returned calendar days number can deviate from the exact value by a fraction of a day.

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 per underlying unit. Updating contract prices can be slow, depending on broker. If the contract is not traded or the market data not subscribed, the function returns 0. Contract prices of open positions are automatically updated at any bar.

contractPosition (TRADE*): int

Returns the current number of open lots or 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. In live trading 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 Mode): int

Checks the option position on the broker account in live [Trade] mode. If it is still open, returns the total number of open contracts (negative for a short position). Otherwise it checks for an open position of the underlying, and returns the position size. If Mode is at 1 and no open contract was found, the trade is automatically closed with a "Lapsed" message. If Mode is at 3 and an underlying position was found, it is sold at market. Mode = 3 thus replicates the backtest behavior of expired options. The 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 (see remarks). 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.

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

Returns the implied volatility (IV) of the given option contract with the given Value. For the 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). If the contract has no value or if the strike price is too far or on the wrong side of the asset price, the function returns 0. Source code in contract.c

contractStrike (int Type, int Days, var Price, var HistVol, var RiskFree, var Delta): var

Returns the theoretical strike value of a contract of given Type with the given Days until expiration, underlying Price, volatility HistVol, RiskFree yield rate, and Delta. Uses the formula Strike = Price * exp(-qnorm(Delta) * sigma * sqrt(T) + (r + (sigma^2)/2) * T). Source code in contract.c.

contractDelta (int Type, int Days, var Price, var HistVol, var RiskFree, var Strike): var

Returns the theoretical delta of a contract of given Type with the given Days until expiration, underlying Price, volatility HistVol, RiskFree yield rate, and Strike. Uses the formula Delta =  cdf((ln(Price/Strike) + (r + (sigma^2)/2) * T) /(sigma * sqrt(T))). Source code in contract.c.

contractIntrinsic (CONTRACT*, var Price): var

contractIntrinsic (TRADE*, var Price): var

Returns the intrinsic value of the option contract per underlying unit 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.

contractProfit (CONTRACT*, var Price, var Premium): var

Returns the profit per underlying unit of a contract sold or purchased at the given Premium when expiring at the given underlying Price. Premium must be positive for sold, negative for bought contracts. Type and fStrike of the contract must be set; the other parameters don't matter. Trading costs are not included. Source code in contract.c.

contractRisk (COMBO* Combo): var

Returns the maximum risk per underlying unit of the given option combo, which can consist of up to 4 contracts with arbitrary lot sizes (positive for bought and negative for sold contracts; COMBO struct defined in trading.h). The maximum risk is the worst loss when the combo expires far in the money, far out of the money, or at the average strike price. Type, fAsk, fBid, and fStrike of the contract must be set; the other parameters don't matter. Trading costs are not included. 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 content from a historical file or from the broker API.
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, plus the following optional flags:
+ONLYW3 - select only contracts that expire between the 16th and the 21th of the month.
+ONLYMATCH - select only contracts that exactly match the expiration date.'
+ASDISTANCE - Strike parameter as difference to the underlying price, which must be set in the CONTRACT structs (fUnl).
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 annualized volatility of the underlying asset, as a fraction, f.i. 0.2 for 20%. Normally calculated with the Volatility or VolatilityOV indicators 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:

Examples:

// 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(); }s // 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); } }
// Example script for converting EOD options data to .t8:
// Format: underlying symbol, exchange, date MMDDYYYY, adj close, option symbol, expiry MMDDYYYY, strike, Call/Put, American/European, ask, bid, volume, open interest, close
// Sample: "TLT,NYSEArca,04/10/2015,129.62,TLT   150410C00112500,04/10/2015,112.5,C,A,17.3,16.2,0,0,129.62"
string Format = ",,%m/%d/%Y,,,i,f,s,s,f,f,f,f,f";

void main() 
{
// first step: parse the CSV file into a dataset
  int Records = dataParse(1,Format,FILENAME);
  printf("\n%d Records parsed",Records);
// second step: convert the raw data to the final CONTRACT format
  for(i=0; i<Records; i++,c++) 
  {
    CONTRACT* C = dataAppendRow(2,9);
    C->time = dataVar(1,i,0);
    string PC = dataStr(1,i,3);
    string EA = dataStr(1,i,4);
    C->Type = ifelse(*PC == 'P',PUT,CALL) + ifelse(*EA == 'E',EUROPEAN,0);
    int Expiry = dataInt(1,i,1); 
    C->Expiry = 10000*(Expiry%10000) + Expiry/10000; // MMDDYYYY -> YYYYMMDD
    C->fStrike = dataVar(1,i,2);
    C->fAsk = dataVar(1,i,5);
    C->fBid = dataVar(1,i,6);
    C->fVol = dataVar(1,i,7);
    C->fVal = dataVar(1,i,8); // open interest
    C->fUnl = dataVar(1,i,9);
    if(!progress(100*i/Records,0)) break; // show a progress bar
  }
  dataSort(2);
  dataSave(2,"History\\MyOptions.t8");
}

See also:

enterLong/Short, exitLong/Short, asset, Quandl bridge, date functions, contract variables, contractCPD, workshop 8

 

► latest version online