To pass the time until jcl posts the new 'Algorithmic Options Trading' article on the Financial Hacker, I've so far come up with this:

Code:
#include <r.h>
#include <contract.c>

void run() 
{
	BarPeriod = 1440;
	LookBack = 255; // Look back 52 weeks - a year lookback	
	//StartDate = 2013;
	//EndDate = 2016; 	// fixed simulation period	
	
	assetList("assetsIB");
	assetHistory("SPY",FROM_YAHOO|UNADJUSTED);
	asset("SPY");
	if(is(INITRUN)){
		initRQL();
		dataLoad(1,"SPY_Options.t8",9);
	}

	Multiplier = 100;
	contractUpdate("SPY",1,CALL|PUT);	
	int Type = ifelse(random() > 0,CALL,PUT);// ****
	var delta_check = 0;
	var strike_price = 0; 
	int i = 0;
	bool test;
	int maximum = 1000;
	var con_value;
	var current_IV;
	var Dividend = 0.02;
	var HistVolOV = VolatilityOV(20);
	var Interest = 0.01*yield();

	// Here, based on whether the contract we want is CALL or PUT. Aim is to find the first contract that is just under (or above) 0.3 delta
	if(Type == CALL){ // If type equals CALL - When you increase Call strike price, you reduce delta
		for(i=0; i<maximum; i++){ 
			strike_price = priceClose() + (0.1*i);
			CONTRACT* dtest = contract(CALL,30,strike_price); // Find the option from the option chain based on current strike price
			con_value = contractVal(dtest,priceClose(),HistVolOV,Dividend,Interest,&delta_check);// Find the contract value and delta of contract at strike price
			current_IV = contractVol(dtest,priceClose(),HistVolOV,con_value,Dividend,Interest);
			
			if(con_value < 0) break;	// Validaiton test - You can not have a negative contract value so breaks when fails
			else test = true; // Passes validation test - used for display purposes
			if(delta_check < 0.3) break;}} // Will show the first value that is just under 0.3 - therefore the closest possible & under!			
	
	else{ // If type equals PUT - When you increase Call strike price, you increase delta (magnitude as this has minus sign)
		for(i=0; i<maximum; i++){ 
			strike_price = priceClose() - (0.1*i);
			CONTRACT* dtest = contract(PUT,30,strike_price); // Find the option from the option chain based on current strike price
			con_value = contractVal(dtest,priceClose(),HistVolOV,Dividend,Interest,&delta_check);// Find the contract value and delta of contract at strike price
			current_IV = contractVol(dtest,priceClose(),HistVolOV,con_value,Dividend,Interest);
			
			if(con_value < 0) break;	// Validaiton test - You can not have a negative contract value
			else test = true; // Passes validation test - used for display purposes
			if(delta_check > -0.3) break;}} // Will show the first value that is just under 0.3 - therefore the closest possible & under!


	// Outside of for loop, we then use the retrieved contract to therefore calculate the Implied volatility, and then the IV Rank!
	vars IV = series(current_IV); // Store calculated IV form for loop into series Will need a lookback of a year
	
	// IV percentile calculation - adapt HH function 
	var vHH = 0.; // Set to a low value as that its sensitive at the start
	var vLL = 1; // Set to a high value as its sensitive at the start
	var IV_rank; // also known as the IV percentile 
	var count;
	var yer = 255; // 52 weeks based on Zorro reports
	
	// Here, the two for loops will look back in the past year to find the maximum and minimum IV values for the asset	
	for(count = 0; count < yer; count++) // For loop to find the highest IV calculated in the past year
	vHH = max(vHH,IV[count]);
	for(count = 0; count < yer; count++) // For loop to find the Lowest IV calculated in the past year
	vLL = min(vLL,IV[count]); // to ensure that IV is never set to 0
	
	// We do not want to calculate the IV rank (or percentile) during the lookback period!!!
	if(!is(LOOKBACK)) IV_rank =  (100 * (current_IV - vLL))/(vHH - vLL);  // Equation from http://tastytradenetwork.squarespace.com/tt/blog/implied-volatility-rank

	// Plot IV and IV rank graph
	plot("IV curve",IV[0],NEW,BLUE);
	plot("IV Rank",IV_rank,NEW,BLACK);
	PlotWidth = 600;
	PlotHeight1 = 300;
	
	// Only to enter trades that are just under 0.30 delta and equal or above 50% IV percentile
	if((between(abs(delta_check),0.25,0.3))&&(IV_rank >= 50)){ // Can do optimizing here YAY!
		static int LastExpiry = 0;
		if(ContractType && LastExpiry != ContractExpiry) {
			enterShort();
			LastExpiry = ContractExpiry;
	}}

}



The last result produced (when the lookback bug wasn't messing things up - explained below) is as shown:

Code:
option_delta_check compiling................
Error 056: No Quandl Key in Zorro.ini!
Parse HistoryFRED-DTB3.csv...
Test: option_delta_check SPY 2012..2017
Assets assetsIB 
Monte Carlo Analysis... Median AR 4%
Profit 3096$  MI 61$  DD 511$  Capital 18909$
Trades 18  Win 88.9%  Avg +172.0p  Bars 23
AR 4%  PF 9.12  SR 1.24  UI 4%  R2 0.89
Time 00:13:45



Several things to note:
- This is so far a very basic option trading system, which will enter trades that have an absolute magnitude between 0.25 and 0.3 delta. As well as this, I have also implemented an IV percentile calculator, which compares the current IV of the asset with the maximum and minimum IV of the asset in the past 365 days (or 52 weeks). Here, trades need to be in the 50% or above to also be entered (without this filter, there would be over 200 trades)

A random function decides whether the contract to SELL is a CALL or PUT, exactly the same way done in the random sell strategy in 'Algorithmic Options Trading Part 1'

Hopefully this can help some of those who are getting to grips with options trading programming, as I myself have learned a ridiculous amount, and I am very keen on learning a lot more! However for those more experienced, please feel free to suggest improvements!

- There is definitely a bug when it comes to the lookback, as shown below. A couple (or maybe all?) of you will probably notice it as well. It is on and off, on one occasion that I press [test], the script will not run, but then the next time I press [test], the script will run fine...

Code:
Different messages appear on the Zorro window, even though I did not make a single change between the two tests. 

Error 056: No Quandl Key in Zorro.ini!
Parse HistoryFRED-DTB3.csv...
Test: option_delta_check SPY 2012..2017
Assets assetsIB 
Error 037: Invalid value in plot "IV Rank" bar 255

option_delta_check compiling................
Error 056: No Quandl Key in Zorro.ini!
Parse HistoryFRED-DTB3.csv...
Test: option_delta_check SPY 2012..2017
Assets assetsIB 
Copied to Clipboard!



I did not make a single change to the code on the two occasions, however when I run the test on the first occasion, the problem occurs where the TS does not go into any trades, and the enter backtest finishes within seconds. I am certain it is to do with the Lookback, simply because I never had this problem until I included lookback in the code. The lookback is vital as it is used for the IV percentile calculator. As stated before, the second time I run the code, the backtest runs fine.

Again, I would really appreciate feedback as to what may be causing this problem.

- You will notice, I used breaks in the for loops. The reason being was that I was spending too much time playing around with while and do while loops, and neither got me anywhere. If anyone can perfect/ improve the process carried out in the CALL/PUT FOR loops, again feel free to put it forward!

- I left the bool test variable as I initially used it for validation and verification purposes, but when I remove the 3 lines of relevant code, the lookback bug seems to go crazy...

- Those are the main thing folks, so please let me know of your thoughts