| Overall Statistics |
|
Total Trades 12 Average Win 0.10% Average Loss -0.10% Compounding Annual Return 0.213% Drawdown 0.500% Expectancy -0.665 Net Profit 0.212% Sharpe Ratio 0.345 Probabilistic Sharpe Ratio 21.446% Loss Rate 83% Win Rate 17% Profit-Loss Ratio 1.01 Alpha 0.001 Beta 0.002 Annual Standard Deviation 0.004 Annual Variance 0 Information Ratio -0.597 Tracking Error 0.278 Treynor Ratio 0.689 Total Fees $73.50 Estimated Strategy Capacity $0 Lowest Capacity Asset ABBV VCY032R250MD |
namespace QuantConnect.Algorithm.CSharp
{
public partial class CollarAlgorithm : QCAlgorithm
{
public class LookupData {
// ********************** DividendRecord **************************************
// *** This structure contains the dividend information necessary to calculate trading
// *** decision. It is used to build a List<DividendRecord> that can be searched to
// *** produce the nextExDivDate and dividend amount0
// *** doTracing
// *** haltProcessing
// *** exDividendDates
// *** fedFundsRates
// *** ibkrHairCuts
// *** workingDays
// *** thisFFRate
// *** ibkrRateAdj
public struct DividendRecord {
public string ticker;
public DateTime exDate;
public decimal divAmt;
public string frequency;
}
public List<SSQRColumn> SSQRMatrix = new List<SSQRColumn>();
public Symbol uSymbol; // underlying symbol in current processing
public bool doTracing = false;
public bool haltProcessing = false;
public decimal workingDays = 365M;
public decimal thisFFRate = 0M;
public decimal ibkrRateAdj = .006M; // IBKR adds 60bps to FFR (blended over $3,000,000)
public decimal maxPutOTM = 0M; // maximum Put OTM depth
public List<DividendRecord> exDividendDates = new List<DividendRecord>();
public Dictionary<DateTime, decimal> fedFundsRates = new Dictionary<DateTime, decimal>();
public Dictionary<decimal, decimal> ibkrHairCuts = new Dictionary<decimal, decimal>();
public Dictionary<int, string> tickers = new Dictionary<int, string> ();
public decimal divdndAmt = 0;
public string divdnFrequency = "";
public DateTime exDivdnDate;
public DateTime dtTst; // used for current date time in methods
public int daysRemainingC; // use vars for checking days before expiration
public int daysRemainingP;
public int daysRemaining2P;
public int daysRemainingWC;
public void InitializeData(QCAlgorithm algo)
{
this.exDividendDates = this.GetDividendDates(algo);
if (exDividendDates == null) algo.Debug("|||||||||||||||||| MISSING DIV DATES |||||||||||||||");
this.fedFundsRates = this.GetFedFundsRates(algo);
if (fedFundsRates == null) algo.Debug("|||||||||||||||||| MISSING FED FUNDS |||||||||||||||");
this.ibkrHairCuts = this.InitializeHaircuts(algo);
//this.tickers = this.GetTickers(algo); //// //// //// REMOVED CODE FROM THIS VERSION OF THE CODE
}
public void GetSliceData(QCAlgorithm algo)
{
}
// ********************** getNextExDate **************************************
// *** Use this to find and return the next ex-dividend date from
// *** the list exDividendDates given a Slice.DateTime
// ***********************************************************************************
public DateTime getNxtExDt(string tickStr, DateTime sliceTime, List<DividendRecord> exDivRecs)
{
// // /// /// NOTE: Adjusted this to .Compare(sliceTime, d.exDate <=0) to accommondate BND ex-dates on 1st of month
// // /// /// NOTE: This should work because most stocks will be traded before progressing through the month to their ex-div dates
DividendRecord nextExDateRec = exDivRecs.Where(d => DateTime.Compare(sliceTime.Date, d.exDate.Date)<=0 &&
d.ticker == tickStr)
.OrderBy(d => d.exDate)
.FirstOrDefault();
DateTime nextExDate = nextExDateRec.exDate;
return nextExDate;
}
// ********************** GetFedFundsRates() **************************************
// *** This function downloads the DFF.csv file from Dropbox and loads it into
// *** a Dictionary<DateTime, interest rate> for each day
// *** this dictionary is used when making a trading decision to calculate the interest
private Dictionary<DateTime, decimal> GetFedFundsRates(QCAlgorithm algo)
{
var ffFile = algo.Download("https://www.dropbox.com/s/s25jzi5ng47wv4k/DFF.csv?dl=1");
if (ffFile == null) return null;
Dictionary<DateTime, decimal> ffDict = new Dictionary<DateTime, decimal>();
string[] ffLines = ffFile.Split(new[] {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries);
int h = 0;
foreach (string ffLine in ffLines)
{
if(h==0) // discard header row
{
h++;
continue;
}
var vals = ffLine.Split(',');
ffDict.Add(DateTime.Parse(vals[0]), Convert.ToDecimal(vals[1])/100M); // convert percentage to decimal
h++;
}
// these next 2 lines are for debugging only --
//DateTime testFind = DateTime.Parse("02/02/2015 16:30:00");
//var justDate = testFind.Date;
return ffDict;
}
// ********************** GetDividendDates() **************************************
// *** This function downloads the DividendDates.csv file from Dropbox and loads it into
// *** a List<DividendRecord>. The List is used to lookup the next ex-dividend date
// *** this list is used when making a trading decision to calculate the dividend payout
private List<DividendRecord> GetDividendDates(QCAlgorithm algo)
{
// 2020-9-25 9:24 https://www.dropbox.com/s/ap8s120gksb858h/DividendData.csv?dl=1
// 2020-09-25 8:11 https://www.dropbox.com/s/ap8s120gksb858h/DividendData.csv?dl=1
// 2020-09-25 8:09 https://www.dropbox.com/sh/05qjk3o3y53fp4i/AAA6fEJg8J50xMQWm5nlg7M4a?dl=1 -- zip file
// 2021-01-14 8:33 var csvFile = Download("https://www.dropbox.com/s/ap8s120gksb858h/DividendData.csv?dl=1");
var csvFile = algo.Download("https://www.dropbox.com/s/jv0aaajwsw8auwo/FiveYearDividends.csv?dl=1");
if (csvFile == null) return null;
decimal lastDiv = 0;
List<DividendRecord> dividendDates = new List<DividendRecord>();
// want to use Microsoft.VisualBasic.FileIO csv parser but is not available
// use the system's /cr /lf to parse the file string into lines
string[] csvLines = csvFile.Split(new[] {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries);
int i = 0;
foreach (string csvLine in csvLines)
{
if (i == 0)
{
i++;
continue; //discard the header row
}
var values = csvLine.Split(','); // this file is comma delimited
if (!values[3].Equals("annual") ) {
DividendRecord divRec = new DividendRecord();
divRec.ticker = values[0];
if (values[1] == "") {
divRec.divAmt = 0;
} else {
divRec.divAmt = Convert.ToDecimal(values[1]);
}
divRec.exDate = DateTime.Parse(values[2]);
divRec.frequency = values[3];
dividendDates.Add(divRec);
}
}
i++;
return dividendDates;
}
private Dictionary<decimal, decimal> InitializeHaircuts(QCAlgorithm algo)
{
Dictionary<decimal, decimal> ibkrHC = new Dictionary<decimal, decimal>();
ibkrHC.Add(0M, .75M);
ibkrHC.Add(0.5M, .75M);
ibkrHC.Add(1M, .75M);
ibkrHC.Add(1.5M, .75M);
ibkrHC.Add(2M, .75M);
ibkrHC.Add(2.5M, .85M);
ibkrHC.Add(3M, 1M);
ibkrHC.Add(3.5M, 1.15M);
ibkrHC.Add(4M, 1.3M);
ibkrHC.Add(4.5M, 1.65M);
ibkrHC.Add(5M, 2M);
ibkrHC.Add(5.5M, 2.2M);
ibkrHC.Add(6M, 2.4M);
ibkrHC.Add(6.5M, 2.6M);
ibkrHC.Add(7M, 2.8M);
ibkrHC.Add(7.5M, 3M);
ibkrHC.Add(8M, 3.5M);
ibkrHC.Add(8.5M, 3.8M);
ibkrHC.Add(9M, 4M);
ibkrHC.Add(9.5M, 4.3M);
ibkrHC.Add(10M, 4.5M);
ibkrHC.Add(10.5M, 4.8M);
ibkrHC.Add(11M, 5M);
ibkrHC.Add(11.5M, 5.3M);
ibkrHC.Add(12M, 5.5M);
ibkrHC.Add(12.5M, 5.7M);
ibkrHC.Add(13M, 6M);
ibkrHC.Add(13.5M, 6.2M);
ibkrHC.Add(14M, 6.6M);
ibkrHC.Add(14.5M, 6.8M);
ibkrHC.Add(15M, 7M);
ibkrHC.Add(15.5M, 7.2M);
ibkrHC.Add(16M, 7.4M);
ibkrHC.Add(16.5M, 7.6M);
ibkrHC.Add(17M, 7.8M);
ibkrHC.Add(17.5M, 8.1M);
ibkrHC.Add(18M, 8.2M);
ibkrHC.Add(18.5M, 8.4M);
ibkrHC.Add(19M, 8.6M);
ibkrHC.Add(19.5M, 8.8M);
ibkrHC.Add(20M, 9M);
ibkrHC.Add(20.5M, 9.2M);
ibkrHC.Add(21M, 9.4M);
ibkrHC.Add(21.5M, 9.6M);
ibkrHC.Add(22M, 9.8M);
ibkrHC.Add(22.5M, 10.1M);
ibkrHC.Add(23M, 10.4M);
ibkrHC.Add(23.5M, 10.7M);
ibkrHC.Add(24M, 11M);
ibkrHC.Add(24.5M, 11.4M);
ibkrHC.Add(25M, 11.8M);
ibkrHC.Add(25.5M, 12.3M);
ibkrHC.Add(26M, 12.8M);
ibkrHC.Add(26.5M, 13.2M);
ibkrHC.Add(27M, 13.7M);
ibkrHC.Add(27.5M, 14.2M);
ibkrHC.Add(28M, 14.7M);
ibkrHC.Add(28.5M, 15.2M);
ibkrHC.Add(29M, 15.6M);
ibkrHC.Add(29.5M, 16.1M);
ibkrHC.Add(30M, 16.6M);
ibkrHC.Add(30.5M, 17M);
ibkrHC.Add(31M, 17.4M);
ibkrHC.Add(31.5M, 17.8M);
ibkrHC.Add(32M, 13.4M);
ibkrHC.Add(32.5M, 18.2M);
ibkrHC.Add(33M, 18.6M);
ibkrHC.Add(33.5M, 19M);
ibkrHC.Add(34M, 19.4M);
ibkrHC.Add(34.5M, 19.8M);
ibkrHC.Add(35M, 20.2M);
return ibkrHC;
} // end initializeIBKR
// ********************** getNextExDate **************************************
// *** Use this to find and return the next ex-dividend date from
// *** the list exDividendDates given a Slice.DateTime
// ***********************************************************************************
public void GetNextExDate(QCAlgorithm algo)
{
// // /// /// NOTE: Adjusted this to .Compare(sliceTime, d.exDate <=0) to accommondate BND ex-dates on 1st of month
// // /// /// NOTE: This should work because most stocks will be traded before progressing through the month to their ex-div dates
if (haltProcessing) {
algo.Debug(" HALTED IN getNextExDate");
}
DateTime sliceTime = algo.CurrentSlice.Time;
string tickStr = this.uSymbol.Value;
DividendRecord nextExDateRec = exDividendDates.Where(d => DateTime.Compare(sliceTime.Date, d.exDate.Date)<=0 &&
d.ticker == tickStr)
.OrderBy(d => d.exDate)
.FirstOrDefault();
///
if (nextExDateRec.ticker == "" ) {algo.Debug(" ------------- MISSING DIVIDEND TICKER: " + tickStr);}
this.exDivdnDate = nextExDateRec.exDate;
this.divdndAmt = nextExDateRec.divAmt;
this.divdnFrequency = nextExDateRec.frequency;
return;
}
public void GetNextExDate(string tickStr, QCAlgorithm algo)
{
// // /// /// NOTE: Adjusted this to .Compare(sliceTime, d.exDate <=0) to accommondate BND ex-dates on 1st of month
// // /// /// NOTE: This should work because most stocks will be traded before progressing through the month to their ex-div dates
if (haltProcessing) {
algo.Debug(" HALTED IN getNextExDate");
}
DateTime sliceTime = algo.CurrentSlice.Time;
DividendRecord nextExDateRec = exDividendDates.Where(d => DateTime.Compare(sliceTime.Date, d.exDate.Date)<=0 &&
d.ticker == tickStr)
.OrderBy(d => d.exDate)
.FirstOrDefault();
if (nextExDateRec.ticker == "" ) {algo.Debug(" ------------- MISSING DIVIDEND TICKER: " + tickStr);}
this.exDivdnDate = nextExDateRec.exDate;
this.divdndAmt = nextExDateRec.divAmt;
this.divdnFrequency = nextExDateRec.frequency;
return;
}
} /// end class lookupData
}
}using QuantConnect.Securities.Option;
using static QuantConnect.StringExtensions;
using System.Collections.Generic;
using System.Drawing;
using Newtonsoft.Json;
namespace QuantConnect.Algorithm.CSharp
{
public partial class CollarAlgorithm : QCAlgorithm
{
// Initialize trade control variables used to intercept automated options exercise.
//public var uniThis;
public bool badDtParameter; // get this from the parameters for debugging
public bool haltProcessing = false; // use this to trap ERROR
public bool doTracing = false; // turn Debug() process tracing on/off
public Symbol symbFilter = null;
//bool didTheTrade = false; // Flag that permits InterateOrderedSSQRMatrix only if a trade was done
OrderTicket closeCallTicket; // use this to track and manage collar rolling and killing trades
OrderTicket closePutTicket; // use this to track and manage collar rolling and killing trades
OrderTicket closeWCallTicket; // use this to track and manage collar rolling and killing trades
List<OpenLimitOrder> oLOs = new List<OpenLimitOrder>(); // maintain a list of open limit orders to manage
bool iteratePortfolio = false; // Switch to toggle Iterating and Logging portfolio
decimal stockDollarValue; // get the dollar value for the position
decimal sharesToBuy; // Get the number shares to achieve the value
bool hasDividends = true; // Bool set (unset=false) to determine whether to add security to portfolio
decimal optionsToTrade; // Get the initial Options to trade (1/10th the sharesToBuy)
decimal callsToTrade; // Get the initial call options to trade in a variable call coverage strategy
//decimal maxPutOTM = 0.5M; // Instantiate and set maximum depth of PUT OTM -- percentage
int MinNmbrDivs = 1; // Instantiate and set minimum number of dividends acceptable in BestSSQRMatrix
decimal wingFactor = 0; // wing factor to multiply optionsToTrade to trade the wings
decimal vix; // used to track and log vix values
bool doTheTrade = false; // Used to allow trades the algorithm initiates
bool didTheTrade = false; // used to toggle iterating SSQRMatrix
bool useDeltas = false; // used to turn use of deltas in trade determination on or off
public decimal ROCThresh; // return on (risk/margin-committed) capital
public decimal RORThresh; // return on risk (= net collar cost - put strike)
public decimal CCORThresh; // call coverage ratio / risk for 0 cost collar (risk = stockPrice - putStrike)
bool goodThresh = false; // used to determine go/no-go on trade
public bool switchROC = true;
LookupData LUD = new LookupData(); // repository of system-wide and common data
List<TradePerfRec> tradeRecs = new List<TradePerfRec>(); // used to track P&L of trades
List<TradePerfRec> tprsToClose = new List<TradePerfRec>(); // List of TPRs to Close. // use this in OnData TPR-driven position updating
List<TradePerfRec> tprsToOpen = new List<TradePerfRec>(); // List of TPRs to Open. // use this in OnData TPR-driven position updating
List<TradePerfRec> secTPRs = new List<TradePerfRec>();
List<TradePerfRec> thetaTPRs = new List<TradePerfRec>();
int tradeRecCount = 0; // track the trade count
int secndRecCount = 0; // loop counter for processing 2nd Recs
int collarIndex = 0;
bool hasPrimaryRec = false;
bool hasSecondaryRec = false;
bool hasThetaRec = false;
int curr2ndTPR = 0; // Used to store index
int curr1stTPR = 0; // used to store index of 1st TPR
// Use this to filter FineFilterSelection to 1 stock as specified by Algorithm Parameter.
string strFilterTkr = "";
Symbol thisSymbol; // Initialize Symbol as class variable
decimal incrPrice = 0; // check for underlying price appreciation
decimal currSellPnL = 0; // for calculating potential roll P&L
decimal currExrcsPutPnL = 0; // for calculating potential roll P&L
decimal currExrcsCallPnL = 0; // for calculating potential roll P&L
decimal callStrike;
decimal putStrike;
decimal sTPRPutStrike; // strike of 2nd TPR Put Strike
decimal wcStrike; // strike of wing call for evaluating sale
Symbol debugSymbol; // general purpose debugging variable
OptionChain debugChain; // special purpose debugging variable
decimal stockPrice = 0;
decimal fTPRPutPrice = 0; // used when rolling up stop losses or deciding to exercise ITM positions
decimal sTPRPutPrice = 0; // used when evaluating sTPRs for rolling or extinguishing
decimal thisROC = 0;
decimal thisROR = 0;
decimal thisCCOR = 0;
decimal heldValue = 0; // value of thisSymbol held
bool buyMoreShares = false; // decision to buy more shares of thisSymbol or keep managing inventory
SSQRColumn bestSSQRColumn = new SSQRColumn();
decimal stockDividendAmount = 0M;
string divFrequency = "Quarterly";
decimal divPlotValue = 0M;
DateTime fmrNextExDate;
bool sellThePut = false; // ORDER MANAGEMENT CONTROL -- SET sellThePut whenever calls are exercised by LEAN
bool buyTheCall = false; // ORDER MANAGEMENT CONTROL -- SET buyThePut whenever puts are exercised by LEAN
// Added foundOption dictionary to store if we have pulled greek data for our securities
Dictionary<Symbol, bool> foundOption = new Dictionary<Symbol, bool>();
// Holds multi ticker data
Dictionary<Symbol, SymbolData> symbolDataBySymbol = new Dictionary<Symbol, SymbolData>();
int lastMonth = -1;
// *** *** *** *** *** *** *** *** *** *** ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ *** *** *** *** *** *** *** *** *** *** *** *** *** ***
// *** *** *** *** *** *** *** *** *** *** | PRICE AND DIVIDEND AND TRANSACTION PLOT |** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
// *** *** *** *** *** *** *** *** *** *** ‾‾‾ ‾‾‾ ‾‾‾ ‾‾‾ ‾‾‾ ‾‾‾ ‾‾‾ ‾‾‾ ‾‾‾ ‾‾‾ ‾‾‾ ‾‾‾ *** *** *** *** *** *** *** *** *** *** *** *** *** ***
// Instantiate and set plotting information
//Stochastic sto; // Stochastic
AccumulationDistribution ad; // Accumulation / Distribution
AccumulationDistributionOscillator adOsc; // Accumulation / Distribution Oscillator
AverageDirectionalIndex adx; // Average Directional Index
AverageDirectionalMovementIndexRating adxr; // Average Directional Index Rating
OnBalanceVolume obv; // On Balance Volumne indicator
Variance variance; // Variance of this stock
//decimal lastSto; // store values from night before
decimal lastAd;
decimal lastAdOsc;
decimal lastAdx;
decimal lastAdxr;
decimal lastObv;
decimal lastVariance;
Chart stockPlot; // initialize Series Variables to reference during order processing and endofday plotting
Series buyOrders;
Series sellOrders;
Series rollOrders;
Series ptsOrders;
Series assetPrice;
Series varianceS;
//Series stochastics;
Series dividendsS;
Series vixVals;
// *** *** *** *** *** *** *** *** *** *** ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ *** *** *** *** *** *** *** *** *** *** *** *** *** ***
// *** *** *** *** *** *** *** *** *** *** | END OF VARIABLE DECLARATION AND INSTANTIATION |** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
// *** *** *** *** *** *** *** *** *** *** ‾‾‾ ‾‾‾ ‾‾‾ ‾‾‾ ‾‾‾ ‾‾‾ ‾‾‾ ‾‾‾ ‾‾‾ ‾‾‾ ‾‾‾ ‾‾‾ *** *** *** *** *** *** *** *** *** *** *** *** *** ***
public override void Initialize()
{
DateTime startDate = DateTime.Parse(GetParameter("StartDate"));
DateTime endDate = DateTime.Parse(GetParameter("EndDate"));
SetStartDate(startDate.Year, startDate.Month, startDate.Day); //Set Start Date
SetEndDate(endDate.Year, endDate.Month, endDate.Day); // Set End Date
SetCash(10000000); //Set Strategy Cash
SetWarmup(TimeSpan.FromDays(31), Resolution.Daily);
//ABBV ADM BA BBY BMY CVS DOW GIS GM IBM IRM KO LVS M OHI OXY PM PG PSX QCOM SO T VZ WFC XOM
// Get RunTime control parameters for Minimum # of Dividends and Maximum OTM Put Depth
strFilterTkr = GetParameter("stockTicker");
if (!strFilterTkr.IsNullOrEmpty()) {
symbFilter = QuantConnect.Symbol.Create(strFilterTkr, SecurityType.Equity, Market.USA); /// create a symbol to filter the Universe if one is in the parameters
}
badDtParameter = GetParameter("CheckBadDate") == "true" ? true : false; // get this from parameters
stockDollarValue = Convert.ToDecimal(GetParameter("StockDollarValue"));
MinNmbrDivs = Convert.ToInt16(GetParameter("MinNmbrDivs")); // get and set minimum number of dividends acceptable in BestSSQRMatrix
useDeltas = GetParameter("UseDeltas") == "true" ? true : false; // get this from parameters
wingFactor = Convert.ToDecimal(GetParameter("wingFactor")); // get wing factor for multiplying optionsToTrade when putting on wing
LUD.InitializeData(this);
LUD.maxPutOTM = Convert.ToDecimal(GetParameter("MaxOTMPutDepth")); // get and set the Maximum OTM Put Depth
LUD.doTracing = GetParameter("LogTrace") == "true" ? true : false; // get this from paramters to turn Debug() tracing on/off
// Chart - Master Container for the Chart:
if (symbFilter !=null) {
stockPlot = new Chart("Stock Chart");
// On the Trade Plotter Chart we want 3 series: trades and price:
buyOrders = new Series("Buys", SeriesType.Scatter, "$", Color.Green, ScatterMarkerSymbol.Triangle);
rollOrders = new Series("Rolls", SeriesType.Scatter, "$", Color.Blue, ScatterMarkerSymbol.Square);
ptsOrders = new Series("PTSs", SeriesType.Scatter, "$", Color.Crimson, ScatterMarkerSymbol.Square);
sellOrders = new Series("Sells", SeriesType.Scatter, "$", Color.Red, ScatterMarkerSymbol.TriangleDown);
dividendsS = new Series("Divs", SeriesType.Scatter, "$", Color.Pink, ScatterMarkerSymbol.Diamond);
assetPrice = new Series("EOD Price", SeriesType.Line, "$", Color.Purple);
varianceS = new Series("Variance", SeriesType.Line, "$", Color.Magenta);
assetPrice.Index = 0;
buyOrders.Index = 0;
rollOrders.Index = 0;
ptsOrders.Index = 0;
sellOrders.Index = 0;
dividendsS.Index = 0;
stockPlot.AddSeries(buyOrders);
stockPlot.AddSeries(rollOrders);
stockPlot.AddSeries(ptsOrders);
stockPlot.AddSeries(sellOrders);
stockPlot.AddSeries(dividendsS);
stockPlot.AddSeries(assetPrice);
AddChart(stockPlot);
}
//SetSecurityInitializer(HistoricalSecurityInitializer);
var uniThis = AddUniverse(CoarseSelectionFilter, FineSelectionFunction);
} // // // /// /// /// /// /// Initialize()
public void OnData(TradeBars tbData)
{
// Does this update the indicators?
}
public void OnData(Dividends dData) ///// //////// check this for completeness and cohesion with previous versions
{
try{
if (Portfolio.Invested)
{
foreach(var pair in symbolDataBySymbol) { //// wonder if this will miss some .Distribution values?
Symbol thisSymbol = pair.Key;
SymbolData symbolData = pair.Value;
if(dData.ContainsKey(thisSymbol))
{
int k = 0; // counter for updates
var paymentAmount = dData[thisSymbol].Distribution;
if (doTracing) Debug(" DDDDDDDDDD DDDDDDDDDDD DIVIDENDS FOR " + thisSymbol + " ARE " + paymentAmount);
if (tradeRecs.Any(tpr=> tpr!=null && tpr.isOpen && tpr.uSymbol.Equals(thisSymbol))) {
foreach(var tprec in tradeRecs.Where(tpr=> tpr.isOpen && tpr.uSymbol.Equals(thisSymbol))) {
tprec.numDividends = tprec.numDividends + 1;
tprec.divIncome = tprec.divIncome + paymentAmount;
k = k + 1;
}
}
if (doTracing) Debug(" DDDDDDDDDD DDDDDDDDDDD UPDATED " + k.ToString() + " TRADE PERF RECORDS. ");
if (doTracing) Debug("-");
if (symbFilter != null) Plot("Stock Chart", "Divs", divPlotValue);
}
}
}
} catch (Exception errMsg)
{
if (doTracing) Debug(" DIV ERROR DIV ERROR DIV ERROR " + errMsg);
return;
}
}
public override void OnData(Slice data)
{
if (data.Time.Hour != 10) return;
if (data.Time.Minute % 15 != 0) return; // evaluate everything every 15 minutes
if ((int)data.Time.DayOfWeek == 3 && data.Time.Minute == 0) {
Debug(" ++++++++++++++++++ SLICE DATA +++++++++++++++++++++++++++");
}
List<Symbol> removeSymbols = new List<Symbol>();
foreach(var symbol_r in removeSymbols) {
RemoveOptions(symbol_r);
Liquidate(symbol_r);
RemoveSecurity(symbol_r);
symbolDataBySymbol.Remove(symbol_r);
Debug("Removing " + symbol_r.Value + " due to openInterest");
}
foreach(var pair in symbolDataBySymbol) {
Symbol thisSymbol = pair.Key;
LUD.uSymbol = thisSymbol;
SymbolData symbolData = pair.Value;
OptionChain chain;
if ((symbolData.openInterestCheck == false) & (data.OptionChains.TryGetValue(symbolData.optSymbol, out chain))) {
var atmPutContract_r = chain.OrderBy(x => x.Expiry)
.ThenBy(x => Math.Abs(chain.Underlying.Price - x.Strike))
.ThenByDescending(x => x.Right)
.FirstOrDefault();
var atmCallContract_r = chain
.OrderBy(x => x.Expiry)
.ThenBy(x => Math.Abs(chain.Underlying.Price - x.Strike))
.ThenBy(x => x.Right)
.FirstOrDefault();
int cutOff = 10000;
if((atmPutContract_r.OpenInterest < cutOff) || (atmCallContract_r.OpenInterest < cutOff)) {
removeSymbols.Add(atmCallContract_r.UnderlyingSymbol);
Debug("Removing " + atmCallContract_r.UnderlyingSymbol + " from Universe due to low OpenInterest in front contracts");
}
symbolData.openInterestCheck = true;
}
if (!IsMarketOpen(thisSymbol)) return;
//CheckGreeks(ref foundOption, data); ///// **** **** Jovad Jovad Jovad : where is foundOption set to something to be checked?
if(!data.Bars.ContainsKey(thisSymbol)) ///// **** **** Jovad Jovad Jovad : Won't this exit the whole OnData() if solely 1 thisSymbol is not here
{ /// (int)data.Time.DayOfWeek == 1 &&
if ((int)data.Time.DayOfWeek == 3) {
Debug(" ***** ****** at " + data.Time.Minute + " Slice does not have " + thisSymbol);
}
//return; //// ////// JOVAD JOVAD JOVAD - RETURN EXITS THE ON DATA BEFORE PROCESSING YOUR WHOLE FOR LOOP
continue;
} else {
if ((int)data.Time.DayOfWeek == 3) {
Debug(" ***** ****** at " + data.Time.Minute + " Slice has " + thisSymbol);
}
}
goodThresh = false; // set the threshold switch to false;
hasPrimaryRec = hasSecondaryRec = false; // reset processing branch flags
if (CheckBadDate(data.Time))
{
LUD.haltProcessing = true;
Debug(" @@@@@@ BAD DATE @@@@@@@@@@ The price of " + thisSymbol + " is " + data[thisSymbol].Price);
foreach(var kvp in Securities)
{
var security = kvp.Value;
if (security.Invested)
{
Debug($" |-|-|-|- HOLDINGS: {security.Symbol} : {security.Holdings.Quantity} @ {security.BidPrice} by {security.AskPrice}");
}
}
} else LUD.haltProcessing = false;
if (LUD.haltProcessing) {
Debug(" Logging ONDATA()");
}
if (didTheTrade)
{
Debug($" |||| |||| |||| DID A TRADE ");
foreach(var kvp in Securities) /// make sure there's no leaking of abandoned stocks or options
{
var security = kvp.Value;
if (security.Invested)
{
Debug($" |||| HOLDINGS: {security.Symbol} : {security.Holdings.Quantity} @ {security.BidPrice} by {security.AskPrice}");
}
}
didTheTrade = false;
}
//if (newRollDate.GetHashCode() == 0) newRollDate = data.Time.Date;
//if (oldRollDate.GetHashCode() == 0) oldRollDate = data.Time.Date;
string tickerString = thisSymbol.Value;
LUD.GetNextExDate(tickerString, this);
if (LUD.exDivdnDate.Equals(DateTime.MinValue)) {
if (doTracing) Debug("----- NULL nextExDate ----- NULL nextExDate -----");
hasDividends = false;
return;
} else hasDividends = true;
stockPrice = data[thisSymbol].Price;
if (divPlotValue == 0) { divPlotValue = stockPrice - 5; }
thisROC = 0;
thisROR = 0;
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// IF NOT INVESTED AT ALL OR IF LESS THAN
// QUARTER'S ALLOCATION, CREATE AND TEST
// POTENTIAL OPTIONS COLLARS AND IF
// GOOD, ESTABLISH A POSITION
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
heldValue = Portfolio[thisSymbol].HoldingsValue; // get the dollar value of thisSecurity's positition
if (heldValue < stockDollarValue) {
sharesToBuy = Math.Round((stockDollarValue-heldValue)/stockPrice/100, 0) * 100;
if ( sharesToBuy >= 1000M && symbolDataBySymbol[thisSymbol].isRollable == true) {
buyMoreShares = true;
} else buyMoreShares = false;
}
if (haltProcessing) {
Debug(" --- ");
}
try {
hasPrimaryRec = tradeRecs.Any(t => t!=null && t.isOpen && !t.isSecondary && t.uSymbol.Equals(thisSymbol));
} catch (Exception errMsg)
{
Debug(" ERROR at 369 in main.cs " + errMsg );
if (errMsg.Data.Count > 0) {
Debug(" Extra details:");
foreach (DictionaryEntry de in errMsg.Data)
Debug(" Key: {0,-20} Value: {1}'" + de.Key.ToString() + "'" + de.Value);
}
return;
}
hasSecondaryRec = false;
secndRecCount = 0; // reset the 2ndTPR processing loop counter
//hasSecondaryRec = tradeRecs.Any(t => t!=null && t.isOpen && t.isSecondary && t.uSymbol.Equals(thisSymbol));
hasThetaRec = tradeRecs.Any(t => t!=null && t.isOpen && t.isTheta && t.uSymbol.Equals(thisSymbol));
try {
if (!hasPrimaryRec && buyMoreShares & hasDividends & symbolData.isRollable)
{
// get the underlying stock price in this Slice
if (LUD.exDivdnDate.Month == data.Time.Month)
{
///////////////////////////// ONLY TEST EVERY 15 QUARTER HOUR AND EACH SUBSEQUENT MINUTE
//if (data.Time.Minute != 0 & data.Time.Minute != 1 & data.Time.Minute != 15 & data.Time.Minute != 16 & data.Time.Minute != 30 & data.Time.Minute != 31 & data.Time.Minute != 45) return;
if (doTracing) Debug($" ----- PROCESSING COLLAR INITIAZATION: {thisSymbol}");
if (doTracing) Debug(" ----- ");
bestSSQRColumn = GetBestCollar(this, ref LUD);
if (bestSSQRColumn == null || bestSSQRColumn.IsEmpty()) // just in case somehow we got here with a null bestSSQRColumn
{
if (doTracing) Debug($" ************** null OR EMPTY bestSSQR in Trade Initializing {thisSymbol} *************");
return;
} else {
if (!bestSSQRColumn.IsEmpty()) {
Debug($" ******************* EXECUTING BESTSSQRCOLUMN -- {thisSymbol} --- ");
ExecuteTrade(data, bestSSQRColumn);
if (didTheTrade) {
//oldRollDate = data.Time.Date;
var orderedSSQRMatrix = LUD.SSQRMatrix.OrderByDescending(p => p.CCOR);
IterateOrderedSSQRMatrix(orderedSSQRMatrix);
//didTheTrade = false;
} else {
Debug($" ******************* DIDN'T TRADE - {thisSymbol} --- ");
}
}
return;
}
} // if data.Time.Month == nextExDividendDate.Month
} // if !hasPrimaryRec && buyMoreShares & hasDividends
} catch (Exception errMsg)
{
Debug(" ERROR " + errMsg );
if (errMsg.Data.Count > 0) {
Debug(" Extra details:");
foreach (DictionaryEntry de in errMsg.Data)
Debug(" Key: {0,-20} Value: {1}'" + de.Key.ToString() + "'" + de.Value);
}
return;
}
} // end ForEach(var pair in symbolDataBySymbol)
int k = 0;
if (tradeRecs.Any(tpr=> tpr!=null && tpr.isOpen && !tpr.isSecondary && !tpr.isTheta && data.Time.Subtract(tpr.startDate).Days >=10)) {
foreach(var tprec in tradeRecs.Where(tpr=> tpr.isOpen && !tpr.isSecondary && !tpr.isTheta && data.Time.Subtract(tpr.startDate).Days >= 10)) {
if (tprec.CheckRolling(this, ref LUD)) break; /// 2021-10-18 -- modified TradeDetermination.cs so never sets .isClose=true. & never add and new TPR there
k = k + 1;
}
}
if (tprsToClose.Any(tpr=> tpr!=null)) { /// 2021-10-18 -- close TPRs here
//tprsToClose.ForEach(tpr=>tpr.isOpen = false);
tprsToClose.ForEach(tpr=>tpr.CloseTPR());
}
tprsToClose.Clear();
if(tprsToOpen.Any(tpr=>tpr!=null)) { /// 2021-10-18 -- open TPRs here
foreach(var tprec in tprsToOpen) {
tprec.OpenTPR();
tradeRecs.Add(tprec);
}
}
tprsToOpen.Clear();
} // OnData()
public IEnumerable<Symbol> CoarseSelectionFilter(IEnumerable<CoarseFundamental> coarse)
{
if(Time.Month == lastMonth) {
return Universe.Unchanged;
}
lastMonth = Time.Month;
//2. Save coarse as _coarse and return an Unchanged Universe
var _coarse = coarse;
/*
List<Symbol> finalCoarse = new List<Symbol>();
foreach(var symbol in symbolDataBySymbol.Keys) {
foreach(var optionSymbol in symbolDataBySymbol[symbol].currentOptions) {
if(Portfolio[optionSymbol].Invested) {
finalCoarse.Add(symbol);
Debug("Adding Invested Option " + symbol.ToString() + " to Coarse Filter at " + Time.ToString() );
break;
}
}
}
var filteredByPrice = coarse.Where(x => x.HasFundamentalData & x.Market == Market.USA & x.Price > 5).Select(x => x.Symbol);
foreach(var finalSymbol in filteredByPrice) {
if(!finalCoarse.Contains(finalSymbol)) {
finalCoarse.Add(finalSymbol);
}
}
*/
var filteredByPrice = coarse.Where(x => x.HasFundamentalData & x.Market == Market.USA & x.Price > 5).Select(x => x.Symbol);
return filteredByPrice;
}
public IEnumerable<Symbol> FineSelectionFunction(IEnumerable<FineFundamental> fine)
{
var _fine = fine;
int cntr = 0;
// SELECT 2% Dividend Yield & $5B Market Cap
var CDC_Criteria = fine.Where(x => x.ValuationRatios.TrailingDividendYield >= 0.02m & x.MarketCap > 5e9).Select(x => x.Symbol);
if (strFilterTkr != "") /// If a stockTicker is not empty, then run the backtest for that tick only
{
CDC_Criteria = CDC_Criteria.Where(s=>s == QuantConnect.Symbol.Create(strFilterTkr, SecurityType.Equity, Market.USA ));
} else {
/// otherwise take the top 10 securities
CDC_Criteria = CDC_Criteria.Take(10);
}
Debug( " ------------------ UNIVERSE FINE SELECTION -------------------------");
foreach(var fineSymb in CDC_Criteria) {
cntr = cntr + 1;
Debug(" " + cntr.ToString() + ": " + fineSymb);
}
return CDC_Criteria;
}
/// Rahul said this is beta and possibly inactive
public void OnAssignmentOrderEvent(OrderEvent assignmentEvent)
{
//if (doTracing) Debug("ASSIGNMENT ==== " + assignmentEvent.Symbol.Value);
Debug("AAAAAAAAAAAAAAA ASSIGNMENT ==== " + assignmentEvent.Symbol.Value);
}
// ********************** OnOrderEvent ***********************************************
// *** Generalized function to iterate through and print members of an IEnumerable of Contracts
// *** This is used for debugging only tricky part is passing an IOrderedEnumerable into this
// ****************************************************************************************************
public override void OnOrderEvent(OrderEvent orderEvent) {
var order = Transactions.GetOrderById(orderEvent.OrderId);
var oeSymb = orderEvent.Symbol;
if (haltProcessing) {
Debug(" Logging ONORDER()");
}
Debug(" OO +++ " + order.Type + " order for " + oeSymb + ", Order Status: " + orderEvent.Status);
try {
if (orderEvent.Status == OrderStatus.Filled)
{
//var order = Transactions.GetOrderById(orderEvent.OrderId);
//var oeSymb = orderEvent.Symbol;
if (order.Type == OrderType.OptionExercise)
{
Debug(" OO OPTION EXERCISE ORDER EVENT AT:" + orderEvent.UtcTime + " OOOO");
if (orderEvent.IsAssignment) {
// .IsAssignment seems only to occur when LEAN creates the ASSIGNMENT. -- use this to troubleshoot
// Check for this now because DIVIDEND APPROACHMENT may
Debug(" OO " + orderEvent.UtcTime + " LEAN LEAN LEAN ASSIGNMENT ORDER EVENT LEAN LEAN LEAN OOOOOO");
Debug(" OO ASSIGNMENT SYMBOL: " + oeSymb );
if (oeSymb.HasUnderlying && oeSymb.ID.OptionRight == OptionRight.Call) {
sellThePut = true;
}
}
Debug(" OO Quantity: " + orderEvent.FillQuantity + ", price: " + orderEvent.FillPrice);
if (oeSymb.HasUnderlying) {
didTheTrade = true;
var thisOption = (Option)Securities[oeSymb];
var stkSymbol = thisOption.Underlying;
Debug(" OO OPTIONS ORDER FOR : " + oeSymb + " IS A " + (oeSymb.ID.OptionRight == OptionRight.Put ? "PUT. " : "CALL.") + "for underlying: " + stkSymbol);
// Get the open tradePerfRecord (if any still exists) ??? what is the order of exercise events ???
// tradePerfRec Call termination handled in code prior to PUT EXERCISE
// Execute TradePerfRec Underlying termination in OnOrder() upon Stock Assignment
if(oeSymb.ID.OptionRight == OptionRight.Put)
{
Debug(" oo oo oo oo oo oo oo oo oo oo oo oo oo oo oo oo ");
Debug(" oo PUT OPTION EXERCISE ORDER FOR : " + oeSymb);
Debug(" oo oo oo oo oo oo oo oo oo oo oo oo oo oo oo oo ");
if (tradeRecs.Any(t => t!=null && t.pSymbol.Equals(oeSymb) & t.pQty == -order.Quantity)) {
var pTPR = tradeRecs.Where(t => t!=null && t.pSymbol.Equals(oeSymb) & t.pQty == -order.Quantity).FirstOrDefault();
pTPR.pEndPrice = orderEvent.FillPrice;
Debug(" OO UPDATED PUT END PRICE TO : " + orderEvent.FillPrice);
if (pTPR.cSymbol != null) {
var shrtCall = (Option)Securities[pTPR.cSymbol];
TimeSpan daysToCallExpiry = shrtCall.Expiry.Subtract(orderEvent.UtcTime);
/*if (daysToCallExpiry.Days > 10 ) {
Debug(" OO CALL " + shrtCall + " EXPIRES IN " + daysToCallExpiry.Days + ". CREATING THETA TPR.");
// create a thetaTPR to move the call data and track it. Buy it back when theta decays.
tradeRecs.Add(newThTPR);
pTPR.cSymbol = null; // eliminate the call from the existint TPR
pTPR.cStartPrice = 0;
pTPR.cQty = 0;
} else { */
Debug(" OO SELLING THE CALL IF IT EXISTS");
Debug("IN MAIN INVESTING");
var closeCTkt = MarketOrder(pTPR.cSymbol, -pTPR.cQty);
if (closeCTkt.Status == OrderStatus.Filled) {
pTPR.cEndPrice = closeCTkt.AverageFillPrice;
}
//}
}
Debug(" OO SELLING THE WING CALL IF IT EXISTS");
if (pTPR.wcSymbol != null) {
//var wingCall = (Option)Securities[pTPR.wcSymbol];
var closeWingTkt = MarketOrder(pTPR.wcSymbol, -pTPR.wcQty);
if (closeWingTkt.Status == OrderStatus.Filled) {
pTPR.wcEndPrice = closeWingTkt.AverageFillPrice;
}
}
} else { // 1st TPR in PUT EXERCISE
Debug(" oo oo oo oo oo oo oo oo oo oo oo oo oo oo oo oo ");
Debug(" oo PUT OPTION ORDER FOR : " + oeSymb);
Debug(" oo NOT SURE HOW THIS WAS ACCESSED - NO 1st TPR FOUND ");
Debug(" oo oo oo oo oo oo oo oo oo oo oo oo oo oo oo oo ");
//string jsonString = ConvertTradePerfRec(tradeRecs);
/* if (tradeRecs.Any(t => t!=null && t.cSymbol.Equals(oeSymb) & t.cQty == -order.Quantity)) {
var cTPR = tradeRecs.Where(t => t!=null && t.cSymbol.Equals(oeSymb) & t.cQty == -order.Quantity).FirstOrDefault();
cTPR.cEndPrice = orderEvent.FillPrice;
Debug(" OO UPDATED CALL END PRICE TO : " + orderEvent.FillPrice);
Debug(" OO SELLING THE PUT IF IT EXISTS");
if (cTPR.cSymbol != null) {
var closePTkt = MarketOrder(cTPR.pSymbol, -cTPR.pQty);
if (closePTkt.Status == OrderStatus.Filled) {
cTPR.pEndPrice = closePTkt.AverageFillPrice;
}
}
} */
}
} else if (oeSymb.ID.OptionRight == OptionRight.Call){
Debug(" oo oo oo oo oo oo oo oo oo oo oo oo oo oo oo oo ");
Debug(" oo CALL OPTION EXERCISE ORDER FOR : " + oeSymb);
Debug(" oo oo oo oo oo oo oo oo oo oo oo oo oo oo oo oo ");
if (tradeRecs.Any(t => t!=null && t.cSymbol.Equals(oeSymb) & t.cQty == -order.Quantity)) {
Debug(" oo oo FOUND SHORT CALL 1ST TPR oo ");
var cTPR = tradeRecs.Where(t => t!=null && t.cSymbol.Equals(oeSymb) & t.cQty == -order.Quantity).FirstOrDefault();
cTPR.cEndPrice = orderEvent.FillPrice;
Debug(" oo oo UPDATED 1ST TPR SHORT CALL END PRICE TO : " + orderEvent.FillPrice);
if (cTPR.pSymbol != null) {
var longPut = (Option)Securities[cTPR.pSymbol];
Debug(" oo SELLING THE PUT IF IT EXISTS");
var closePTkt = MarketOrder(cTPR.pSymbol, -cTPR.pQty);
if (closePTkt.Status == OrderStatus.Filled) {
cTPR.pEndPrice = closePTkt.AverageFillPrice;
}
}
if (cTPR.wcSymbol != null) {
var wCallSymbol = (Option)Securities[cTPR.wcSymbol];
Debug(" oo oo oo SELLING THE WING CALL IF IT EXISTS OR HASN'T BEEN BOUGHT");
if (cTPR.wcEndPrice != 0) {
Debug(" oo oo oo oo SELLING THE WING CALL");
var closeWCTkt = MarketOrder(cTPR.wcSymbol, -cTPR.wcQty);
if (closeWCTkt.Status == OrderStatus.Filled) {
cTPR.wcEndPrice = closeWCTkt.AverageFillPrice;
}
} else Debug(" oo oo oo oo THE WING CALL WAS ALREADY SOLD");
} //// THE FOLLOWING WOULD EXECUTE IF ALGO EXERCISED THE WING CALL -- NOT CONTEMPLATED
} else if (tradeRecs.Any(t => t!=null && t.wcSymbol.Equals(oeSymb) & t.wcQty == order.Quantity)) {
var wcTPR = tradeRecs.Where(t => t!=null && t.wcSymbol.Equals(oeSymb) & t.wcQty == order.Quantity).FirstOrDefault();
Debug(" oo FOUND SHORT CALL 1ST TPR oo ");
Debug(" oo UPDATED WING CALL END PRICE TO : " + orderEvent.FillPrice);
wcTPR.wcEndPrice = orderEvent.FillPrice;
}
}
} else { /// !.HasUnderlying -- this is stock being assigned
Debug(" oo ASSIGNMENT OF UNDERLYING ORDER FOR : " + oeSymb);
Debug(" oo STOCK EXERCISE ORDER EVENT FOR: " + order.Quantity + " shares." );
if (haltProcessing) {
Debug(" oo oo oo oo => Logging OnOrder() ");
}
didTheTrade = true;
if(tradeRecs.Any(t => t!=null && t.isOpen & t.uSymbol.Equals(oeSymb) & t.uQty == -order.Quantity * 100M)) {
Debug(" oo UPDATING 2ND TRADE RECORD");
var uTPR = tradeRecs.Where(t => t!=null && t.isOpen & t.uSymbol.Equals(oeSymb) & t.uQty == -order.Quantity * 100M).FirstOrDefault();
if (symbFilter != null) Plot("Stock Chart", "Sells", orderEvent.FillPrice);
tradeRecCount = 0; // reset tradeRec Counter ??? may be obviated
//uTPR.isOpen = false;
tprsToClose.Add(uTPR);
uTPR.uEndPrice = orderEvent.FillPrice;
uTPR.endDate = orderEvent.UtcTime;
if (uTPR.reasonForClose !=null || uTPR.reasonForClose != "") {
uTPR.reasonForClose = uTPR.reasonForClose + "OPTIONS ASSIGNMENT -- UNDERLYING CLOSED";
} else uTPR.reasonForClose = "OPTIONS ASSIGNMENT -- UNDERLYING CLOSED";
if (Portfolio[uTPR.pSymbol].Invested && uTPR.pSymbol != null) {
var sellPutTicket = MarketOrder(uTPR.pSymbol, -uTPR.pQty);
if (doTracing) Debug(" oo oo oo oo ooo Selling the PUT and setting the TPR.EndPrice");
if (sellPutTicket.Status == OrderStatus.Filled) {
uTPR.pEndPrice = sellPutTicket.AverageFillPrice;
}
}
if (Portfolio[uTPR.wcSymbol].Invested && uTPR.wcSymbol != null) {
var sellWCallTicket = MarketOrder(uTPR.wcSymbol, -uTPR.wcQty);
if (doTracing) Debug(" oo oo oo oo ooo Selling the Wing Call and setting the TPR.wcEndPrice");
if (sellWCallTicket.Status == OrderStatus.Filled) {
uTPR.wcEndPrice = sellWCallTicket.AverageFillPrice;
}
}
/// NOTE: OPTIONS WILL EXPIRE OR EXERCISE AT ENDPRICE = 0. THEREFORE THESE VALUES ARE NOT SET HERE
/// BECAUSE THE END PRICES MAY BE SET OTHERWISE ELSEWHERE
} else {
Debug(" oo oo oo oo => FAILED TO LOCATE 2ND TPR");
}
}
Debug(" ---------------------------------------------------------------------------");
} // Order.Type = OrderType.OptionExercise
else
{
Debug(" OO ** ** NON EXERCISE OPTION ORDER -- " + oeSymb);
Debug(" OO ** " + order.Type + ": " + orderEvent.UtcTime + ": " + orderEvent.Direction + " ** OO ");
Debug(" OO ** " + orderEvent.Status + ": " + orderEvent.Direction + " " + order.Quantity + " @ " + orderEvent.FillPrice );
if (oeSymb.HasUnderlying && order.Type == OrderType.Limit ) { /// Option
if (oeSymb.ID.OptionRight == OptionRight.Put)
{
Debug(" OO OO OO OO OO OO OO OO OO OO OO OO OO OO OO OO ");
Debug(" OO PUT OPTION LIMIT ORDER FOR : " + oeSymb);
Debug(" OO PROCESSING TPR IN NEXT ON DATA oo oo oo oo ");
// Debug(" OO OO OO OO OO OO OO OO OO OO OO OO OO OO OO OO ");
/*if (tradeRecs.Any(t => t.pSymbol.Equals(oeSymb) & t.pQty == -order.Quantity)) {
var transRec = tradeRecs.Where(t => t.pSymbol.Equals(oeSymb) & t.pQty == -order.Quantity).FirstOrDefault();
transRec.pEndPrice = orderEvent.FillPrice;
Debug(" OO ** Setting pEndPrice.");
} */
//Debug(" OO NOTE PUT EXPIRATION execute a market order to sell underlying");
} else if (oeSymb.ID.OptionRight == OptionRight.Call) {
Debug(" OO OO OO OO OO OO OO OO OO OO OO OO OO OO OO OO ");
Debug(" OO CALL OPTION LIMIT ORDER FOR : " + oeSymb);
Debug(" OO PROCESSING TPR IN NEXT ON DATA oo oo oo oo ");
// Debug(" OO OO OO OO OO OO OO OO OO OO OO OO OO OO OO OO ");
/*if (tradeRecs.Any(t => t.cSymbol.Equals(oeSymb) & t.cQty == -order.Quantity)) {
var transRec = tradeRecs.Where(t => t.cSymbol.Equals(oeSymb) & t.cQty == -order.Quantity).FirstOrDefault();
transRec.cEndPrice = orderEvent.FillPrice;
Debug(" OO ** Setting cEndPrice.");
}*/
//Debug(" OO NOTE CALL EXPIRATION execute a market order to sell underlying");
}
} else if (oeSymb.HasUnderlying && order.Type == OrderType.Market) {
if (oeSymb.ID.OptionRight == OptionRight.Put)
{
Debug(" OO OO OO OO OO OO OO OO OO OO OO OO OO OO OO OO ");
Debug(" OO PUT OPTION MARKET ORDER FOR : " + oeSymb);
Debug(" OO PROCESSING TPR SYNCHRONOUSLY IN LINE oo oo oo ");
// Debug(" OO OO OO OO OO OO OO OO OO OO OO OO OO OO OO OO ");
/*if (tradeRecs.Any(t => t.pSymbol.Equals(oeSymb) & t.pQty == -order.Quantity)) {
var transRec = tradeRecs.Where(t => t.pSymbol.Equals(oeSymb) & t.pQty == -order.Quantity).FirstOrDefault();
transRec.pEndPrice = orderEvent.FillPrice;
Debug(" OO ** Setting pEndPrice.");
} */
//Debug(" OO NOTE ALGO-DRIVEN PUT market order");
} else if (oeSymb.ID.OptionRight == OptionRight.Call) {
Debug(" OO OO OO OO OO OO OO OO OO OO OO OO OO OO OO OO ");
Debug(" OO CALL OPTION MARKET ORDER FOR : " + oeSymb);
Debug(" OO PROCESSING TPR SYNCHRONOUSLY IN LINE oo oo oo ");
// Debug(" OO OO OO OO OO OO OO OO OO OO OO OO OO OO OO OO ");
/*if (tradeRecs.Any(t => t.cSymbol.Equals(oeSymb) & t.cQty == -order.Quantity)) {
var transRec = tradeRecs.Where(t => t.cSymbol.Equals(oeSymb) & t.cQty == -order.Quantity).FirstOrDefault();
transRec.cEndPrice = orderEvent.FillPrice;
Debug(" OO ** Setting cEndPrice.");
}*/
//Debug(" OO NOTE ALGO-DRIVEN CALL MARKET ORDER");
}
} else if (!oeSymb.HasUnderlying) {
Debug(" OO OO OO OO OO OO OO OO OO OO OO OO OO OO OO OO ");
Debug(" OO UNDERLYING ORDER FOR : " + oeSymb);
// Debug(" OO OO OO OO OO OO OO OO OO OO OO OO OO OO OO OO ");
} else { // NON EXERCISE ORDER HAS UNDERLYING
Debug(" OO OO OO OO OO OO OO OO OO OO OO OO OO OO OO OO ");
Debug(" OO UNKNOWN ALGO ORDER ORDER FOR : " + oeSymb);
// Debug(" OO OO OO OO OO OO OO OO OO OO OO OO OO OO OO OO ");
/*if (tradeRecs.Any(tpr => tpr.uSymbol.Equals(oeSymb) & tpr.uQty == -order.Quantity)) {
var transRec = tradeRecs.Where(tpr => tpr.uSymbol.Equals(oeSymb) & tpr.uQty == -order.Quantity).FirstOrDefault();
Debug (" OO ** THERE IS A TPR THAT IS " + (transRec.isOpen ? " OPEN" : " CLOSED"));
transRec.isOpen = false;
transRec.uEndPrice = orderEvent.FillPrice;
transRec.endDate = orderEvent.UtcTime;
transRec.reasonForClose = "Options Expiration";
Plot("Stock Chart", "Sells", orderEvent.FillPrice);
}*/
}
Debug(" ---------------------------------------------------------------------------");
}
} // orderStatus = Filled
} catch (Exception errMsg)
{
Debug(" ERROR " + errMsg );
if (errMsg.Data.Count > 0) {
Debug(" Extra details:");
foreach (DictionaryEntry de in errMsg.Data)
Debug(" Key: {0,-20} Value: {1}'" + de.Key.ToString() + "'" + de.Value);
}
return;
}
}
//private void CheckExpiration() {
// foreach(var callOption in callOptions) {
// if(callOption.Symbol.ID.Date == Time.Date) {
// Debug($"{callOption.Symbol}");
// }
//}
// }
public override void OnEndOfDay(Symbol symbol)
{
if (symbol.SecurityType != SecurityType.Equity) return;
int i = 0;
if (symbFilter != null) {
//lastSto = sto.Current.Value; // store values from night before
//lastAd = ad.Current.Value;
// lastAdOsc = adOsc.Current.Value;
}
return;
}
public override void OnEndOfAlgorithm()
{
string saveString = "";
bool hasStock = false;
bool hasPuts = false;
bool hasCalls = false;
var tprEnum = tradeRecs.GetEnumerator();
while (tprEnum.MoveNext()) {
TradePerfRec tpr = tprEnum.Current;
if (tpr.isOpen) {
if (tpr.uEndPrice == 0 && tpr.cSymbol != null) {
tpr.uEndPrice = Securities[tpr.uSymbol].Price;
}
if (tpr.pEndPrice == 0 && tpr.pSymbol != null) {
tpr.pEndPrice = Securities[tpr.pSymbol].Price;
}
if (tpr.cEndPrice == 0 && tpr.cSymbol != null) {
tpr.cEndPrice = Securities[tpr.cSymbol].Price;
}
tpr.endDate = Time;
}
}
string jsonString = ConvertTradePerfRec(tradeRecs);
}
public bool CheckOptionInvested(Symbol symbol, Dictionary<Symbol, SymbolData> symbolDataBySymbol) {
if (symbol.SecurityType == SecurityType.Equity && symbolDataBySymbol.ContainsKey(symbol)) {
///if (Portfolio[symbol].Invested) { return true; }
foreach(var optionSymbol in symbolDataBySymbol[symbol].currentOptions) { if(Portfolio[optionSymbol].Invested) { return true; } }
}
if (symbol.SecurityType == SecurityType.Option && Portfolio[symbol].Invested) { return true; }
return false;
}
public void RemoveOptions(Symbol symbol) {
if (symbolDataBySymbol.ContainsKey(symbol)) {
foreach(var optionSymbol in symbolDataBySymbol[symbol].currentOptions) {
RemoveSecurity(optionSymbol);
Liquidate(optionSymbol);
}
symbolDataBySymbol.Remove(symbol);
}
}
public override void OnSecuritiesChanged(SecurityChanges changes)
{
//foreach (var universe in UniverseManager.Values) {
// // User defined universe has symbols from AddSecurity/AddEquity calls
// if (universe is UserDefinedUniverse) continue;
//}
// Debug("Removing:");
foreach(var security in changes.RemovedSecurities) {
var symbol = security.Symbol;
// Debug(symbol);
// if (CheckOptionInvested(symbol, symbolDataBySymbol)) { ///symbolDataBySymbol[symbol].currentPosition == true) {
// if (symbol.SecurityType == SecurityType.Equity) { AddEquity(symbol, Resolution.Minute); symbolDataBySymbol[symbol].isRollable = false; }
// else if (symbol.SecurityType == SecurityType.Option) { AddOptionContract(symbol, Resolution.Minute); symbolDataBySymbol[symbol.Underlying].isRollable = false; }
// continue;
// }
//RemoveOptions(symbol);
//Liquidate(symbol);
//RemoveSecurity(symbol);
}
foreach(var security in changes.AddedSecurities) {
Symbol thisSymbol = security.Symbol;
if (thisSymbol.SecurityType == SecurityType.Equity)
{
if (symbolDataBySymbol.ContainsKey(thisSymbol)) { continue; }
var sym = AddEquity(thisSymbol, Resolution.Minute);
var opt = AddOption(thisSymbol, Resolution.Minute, Market.USA, true, 0m);
//opt.SetFilter(universe => from symbol in universe.IncludeWeeklys()
// .Expiration(TimeSpan.Zero, TimeSpan.FromDays(360))
// where Math.Abs(universe.Underlying.Price - symbol.ID.StrikePrice) < 60 select symbol);
opt.SetFilter(-5, 1, TimeSpan.Zero, TimeSpan.FromDays(300));
opt.PriceModel = OptionPriceModels.CrankNicolsonFD(); /// necessary for Greeks
symbolDataBySymbol.Add(thisSymbol, new SymbolData(thisSymbol, true, false, opt.Symbol));
//sto = STO(thisSymbol, 14, Resolution.Daily); // Stochastic
if (symbFilter != null) {
ad = AD(thisSymbol, Resolution.Daily); // Accumulation / Distribution
adOsc = ADOSC(thisSymbol, 3, 14, Resolution.Daily); // Accumulation / Distribution Oscillator
adx = ADX(thisSymbol, 7, Resolution.Daily); // Average Directional Index
adxr = ADXR(thisSymbol, 7, Resolution.Daily); // Average Directional Index Rating
obv = OBV(thisSymbol, Resolution.Daily); // On Balance Volume
variance = VAR(thisSymbol, 14, Resolution.Daily); // Variance of this stock
Securities[thisSymbol].SetDataNormalizationMode(DataNormalizationMode.Raw);
Securities[thisSymbol].VolatilityModel = new StandardDeviationOfReturnsVolatilityModel(31);
}
}
}
//List<Symbol> keyList = new List<Symbol>(symbolDataBySymbol.Keys);
//Debug("Universe Underlying Securities on " + DateTime.Now.ToShortDateString() + ": " + keyList.Count.ToString());
//Debug("-- UU -- UU -- Universe Underlying Securities on " + CurrentSlice.Time.ToShortDateString() + ": " + keyList.Count.ToString());
// foreach(var security in keyList) {
// Debug(security.ToString());
// }
}
private void HistoricalSecurityInitializer(Security security)
{
var bar = GetLastKnownPrice(security);
security.SetMarketPrice(bar);
if(security.Type == SecurityType.Option){
var openInterest = History<OpenInterest>(security.Symbol, TimeSpan.FromDays(1));
var tradeBar = History<TradeBar>(security.Symbol, TimeSpan.FromDays(1));
}
}
private bool CheckBadDate(DateTime checkDate)
{
DateTime badDate1 = Convert.ToDateTime(GetParameter("BadDate"));
DateTime badDate2 = badDate1.AddMinutes(1);
//DateTime badDate1 = new DateTime(2020, 1, 6, 9, 45, 0);
//DateTime badDate2 = new DateTime(2020, 11, 1, 13, 45, 0);
if(checkDate.Equals(badDate1) | checkDate.Equals(badDate2))
{
return badDtParameter;
} else {
return false;
}
}
// |||||||||||||||||||||||||||||||||||||||||||||||
// Prints greeks for the corresponding symbol
public void PrintGreeks(ref Dictionary<Symbol, bool> foundOption, Slice thisSlice, Symbol pairKey, bool pairValue) {
decimal callDelta;
if (pairValue == true) { return; }
foreach(var chain in thisSlice.OptionChains) {
foreach(var option in chain.Value) {
if(pairKey.ToString() == option.ToString()) {
callDelta = option.Greeks.Delta;
foundOption[pairKey] = true;
///Debug(" || Succesfully added Greeks || " + pairKey + " Delta = " + callDelta.ToString());
//break;
}
}
}
}
// |||||||||||||||||||||||||||||||||||||||||||||||
// Loops through dictionary of active contracts
public void CheckGreeks(ref Dictionary<Symbol, bool> foundOption, Slice thisSlice) {
OptionContract callContract;
OptionChain callChain;
Symbol optSymbol;
Dictionary<Symbol, bool> tempDict = foundOption;
foreach(var pair in tempDict) {
Symbol pairKey = pair.Key;
bool pairValue = pair.Value;
PrintGreeks(ref foundOption, thisSlice, pairKey, pairValue);
}
}
} // class
public class SymbolData {
private Symbol symbol;
public bool isRollable;
public bool currentPosition;
public Symbol optSymbol;
public List<Symbol> currentOptions = new List<Symbol>();
public bool openInterestCheck = false;
public SymbolData(Symbol passedSymbol, bool rollable, bool position, Symbol symbOpt) {
symbol = passedSymbol;
isRollable = rollable;
currentPosition = position;
optSymbol = symbOpt;
}
}
} // namespaceusing QuantConnect.Securities.Option;
namespace QuantConnect.Algorithm.CSharp {
public partial class CollarAlgorithm : QCAlgorithm
{
public class PutSpread
{
public decimal stockPrice; // 2
public DateTime exDate; // 3 may not be necessary
public DateTime tradeDate; // 4
public DateTime putExpiry; // 5
public Symbol oldPutSymb; // 6
public Symbol newPutSymb; // 7
public decimal oldPutBid; // 8
public decimal newPutAsk; // 9
public decimal oldPutStrike; // 10
public decimal newPutStrike; // 11
public decimal newPutOpenInterest; // 12
//public decimal newPutDelta;
//public decimal newPutGamma;
//public decimal newPutVega;
//public decimal newPutRho;
//public decimal newPutTheta;
//public decimal newPutImpliedVol;
public decimal divAmt; // 13
public decimal divCount; // 14
public decimal divDollars; // 15
public decimal stkIncr; // 16 appreciation in stock value
public decimal intCost; // 17
public decimal downsideRisk; // 18
public decimal upsidePotential; // 19
public decimal netIncome; // 20
public decimal netOptions; // 21
public decimal haircut; // 22 committed capital in a portfolio margin account
public string description1; // 23
//public string description2;
//public string description3;
public override string ToString()
{
return this.description1;
}
public bool IsEmpty()
{
return this.description1.IsNullOrEmpty();
}
}
public List<PutSpread> AssemblePutSpreads(Slice slc, Dictionary<int, DateTime> expiries, TradePerfRec tPRec, IEnumerable<Symbol> allUndrOptSymbs, decimal sPrice, decimal incrAmt){
// only roll puts up if the appreciation in stock price + the expected dividends is greater than the cost of the put spread + interest cost
// appreciation = incrAmt
// get the expected dividends
int yearsInTrade = 0; // to calculate dividends
decimal monthsInTrade = 0; // to calculate dividends
int daysInTrade = 0; // to calculate interest
int intCost = 0; // interest cost
decimal dividends = 0.0M;
int k = 1; // initialize iterator for AddOptionContracts below
Symbol optSymbol; // initialize option symbol for building the list of contracts
Option tempOption; // initialize option contract for building list of contracts and obtaining pricing data
Option thisPutOpt; // initialize option contract for building list of contracts and obtaining pricing data
var justDate = slc.Time.Date; // separate out the DATEVALUE from the DateTime variable bc fedFundsRates are so indexed
LUD.thisFFRate = LUD.fedFundsRates[justDate]; // fedFundsRates is a Dictionary of all dates where DateTime index are all 12:00:00am
decimal oldPutPrem = Securities[tPRec.pSymbol].BidPrice; // need the price at which we might sell the puts;
List<Option> putOptionsList = new List<Option>();
DateTime oldPutExpiry = tPRec.expDate; // use old put expiry for selecting put options to examine
var atmPut = allUndrOptSymbs.Where(s => s.ID.OptionRight == OptionRight.Put) // get the ATM put strike for selecting put options to examine
.OrderBy(s => Math.Abs(s.ID.StrikePrice - sPrice))
.FirstOrDefault();
if (haltProcessing && doTracing) {
Debug(" ********* ******* WE GOT AN ATM PUT " );
}
var atmStrike = atmPut.ID.StrikePrice; // get the ATM strike
var lowStrike = tPRec.pStrike;
var highStrik = atmStrike;
//var lowStrike = (1 - (maxPutOTM / (decimal)100)) * atmStrike; // ~~ for selecting put options to examine
//var highStrike = (decimal)1.1 * atmStrike; // ~~ for selecting put options to examine
List<PutSpread> pSpreads = new List<PutSpread>(); // ~~ List for assembling filterd put options
var putSymbs = allUndrOptSymbs; // declare the variable before the conditional branching
// can we get current Put Expiration date?
if (doTracing) Debug("---------------------- PUTS ROLLUP EXPIRIES PASS 1 ----------------------------");
if (doTracing) Debug("--" + stockPrice.ToString() +", " + expiries[2].ToString("MM/dd/yy") + ", " + expiries[3].ToString("MM/dd/yy") + ", " + expiries[4].ToString("MM/dd/yy") + ", " + expiries[5].ToString("MM/dd/yy"));
/*putSymbs = allUndrOptSymbs.Where( o=> (DateTime.Compare(o.ID.Date, expiries[1])==0 |
DateTime.Compare(o.ID.Date, expiries[2])==0 |
DateTime.Compare(o.ID.Date, expiries[3])==0 |
DateTime.Compare(o.ID.Date, expiries[4])==0 ) &&
o.ID.OptionRight == OptionRight.Put &&
o.ID.StrikePrice >= lowStrike &&
o.ID.StrikePrice < atmStrike)
.OrderByDescending(o => o.ID.StrikePrice);
*/
putSymbs = allUndrOptSymbs.Where( o=> o.ID.Date.Subtract(slc.Time).Days >= 10 &
o.ID.OptionRight == OptionRight.Put &
o.ID.StrikePrice >= lowStrike &
o.ID.StrikePrice <= atmStrike)
.OrderByDescending(o => o.ID.StrikePrice);
if (haltProcessing) {
if (doTracing) IterateChain(putSymbs, "putSymbols");
}
if (putSymbs == null | putSymbs.Count()== 0)
{
if (doTracing) Debug(" AP AP AP AP putSymbs is null or empty ");
return pSpreads;
} // putSymbs !=null && putSymbs.Count() != 0 -- in other words continue
var pEnumerator = putSymbs.GetEnumerator(); // convert the options contracts list to an enumerator
while (pEnumerator.MoveNext()) // process the contracts enumerator to add the options
{
optSymbol = pEnumerator.Current;
tempOption = AddOptionContract(optSymbol, Resolution.Minute, true);
tempOption.PriceModel = OptionPriceModels.BinomialTian(); /// necessary for Greeks
putOptionsList.Add(tempOption);
}
var putEnum = putOptionsList.GetEnumerator(); // get the enumerator to build the List<PutSpread>
while (putEnum.MoveNext())
{
thisPutOpt = putEnum.Current;
//if ( thisPutOpt.Expiry.Subtract(slc.Time).Days >= 10 ) {
PutSpread pSpread = new PutSpread();
pSpread.stockPrice = sPrice;
pSpread.tradeDate = justDate;
pSpread.stkIncr = incrAmt;
pSpread.oldPutSymb = tPRec.pSymbol;
pSpread.newPutSymb = thisPutOpt.Symbol;
pSpread.oldPutBid = oldPutPrem;
pSpread.newPutAsk = thisPutOpt.AskPrice;
pSpread.oldPutStrike = tPRec.pSymbol.ID.StrikePrice;
pSpread.newPutStrike = thisPutOpt.StrikePrice;
pSpread.putExpiry = thisPutOpt.Expiry;
daysInTrade = (thisPutOpt.Expiry - justDate).Days; // use the new put option expiration to calculate potential days in trade
pSpread.intCost = (LUD.thisFFRate + LUD.ibkrRateAdj)/LUD.workingDays * (decimal) daysInTrade * stockPrice;
monthsInTrade = ((thisPutOpt.Expiry.Year - justDate.Year) * 12) + (thisPutOpt.Expiry.Month - justDate.Month);
pSpread.divCount = Math.Truncate(monthsInTrade/3.00M) + 1.00M; // add 1 for the next dividend and 1 for every 3 months thereafter
pSpread.divAmt = stockDividendAmount;
pSpread.divDollars = stockDividendAmount * pSpread.divCount;
// pSpread.divDollars = stockDividendAmount * pSpread.divCount;
pSpread.divDollars = stockDividendAmount * 1M; // for profit calc and filtering, omit more than one dividend. Many PTS's end before 1st dividend is paid
pSpread.netOptions = oldPutPrem - tPRec.pStartPrice - thisPutOpt.AskPrice; // get the total net cost of the options trade (not the spread traded)
pSpread.netIncome = incrAmt + pSpread.divDollars - pSpread.intCost; // net potential profit including unrealized gain in underlying since initial trade
//pSpread.newPutOpenInterest;
//pSpread.newPutDelta;
//pSpread.newPutGamma;
//pSpread.newPutVega;
//pSpread.newPutRho;
//pSpread.newPutTheta;
//pSpread.newPutImpliedVol;
//pSpread.haircut; // committed capital in a portfolio margin account
//pSpread.description1;
//pSpread.description2;
pSpreads.Add(pSpread);
//}
}
return pSpreads; // return filled pSpreads;
}
// ********************** GetBestPutSpread **************************************
// *** This sub routine takes in the assembled List of PutSpreads
// *** available in the Slice.Data and calculates the best spread to use
// *** to the roll up the puts
// ***********************************************************************************
public PutSpread GetBestPutSpread(List<PutSpread> pSpreads) {
PutSpread pSprd = new PutSpread(); // get a null empty PutSpread
pSprd = pSpreads.Where(s => s.netIncome + s.netOptions > 0 ).OrderByDescending( s => (s.netIncome + s.netOptions)/Math.Abs(s.stockPrice - s.newPutStrike)).FirstOrDefault();
if (haltProcessing) {
if (doTracing) Debug(" HALTED IN GETBESTPUTSPREAD -- CHECKING PSPREADS");
var orderedPSpreads = pSpreads.Where(s => s.netIncome + s.netOptions > 0 ).OrderByDescending( s => (s.netIncome + s.netOptions)/Math.Abs(s.stockPrice - s.newPutStrike));
IterateOrderedPutSpreadList(orderedPSpreads);
}
// null pSpread can occur when sPrice>oldPStrike but (sPrice-oldPStrike)/oldPStrike < ~2%: Also, rolling forward would cost money.
return pSprd;
}
}
}namespace QuantConnect {
/// 2020-12-03: Arranged all trade pathways, usingDeltas and not, to utilze GetPotentialCollars() ///////
/// ####-##-##: in order to IterateOrderedMatrices solely when executing a trade.
/// 2020-12-04: Added [[bestSSQRColumn = new SSQRColumn();]] to prevent looping and Matrix Iteration after initial SSQRMatrix buiding
/// ####-##-## This was found to occur and created multiple copies of the same SSQR in subsequent OnData() events.
/// 2020-12-07: Corrected RollTheCollar to calculate callQty by putPrem/callPrem (as is done in ExecuteTheTrade()).
/// ####-##-## Also added bool didTheTrade to IterateOrderedSSQRMatix solely when actually trading
/// 2020-12-08 Found GetPotentialCollars for ABBV would only return 2 divs (not 3 or 4) in 2015-10. April Options missing. Has May '16 options
/// ####-##-## conferred with John, and decided to look further (LEAPS) for more possible trades. Added fifthExpirationDate to GetOptionsExpiries()
/// 2020-12-08 Prevented duplicate call/put contracts from being added to SSQRMatrix in AssembleSSQRMatrix (!SSQRMatrix.Any(o=>o.optSymbo == optSymbol)
/// 2020-12-13 Re-configured assembleSSQRMatrix to put and call list enumarators with all the options for 2-5 dividends, and loop 1X
/// ####-##-## Build SSQR only occurs for calls >= put strike and expiration.
/// 2020-12-13 Evaluation of SSQR Matrix reveals the potential of using call time spreads (selling longer dated calls to pay for puts)
/// 2020-12-15 Saw several instances of divide-by-zero error when evaluating vcc/pot. loss (stockprice - putstrike)
/// ####-##-## decided to reformulate the algorithm to sort first by loss potential and then by VCC.
/// 2020-12-16 SIGNIFICANT -- modified bestSSQRColumn to sort descending by Math.Abs(stockPrice-putStrike) then ascending by putPremium/callPremium to get lowest risk and least call coverage
/// 2021-01-04 Captured DivideByZero errors when StockPrice = PutStrike in CCOR calculations
/// 2021-01-06 Added LogTrace to turn Debug on/off
/// 2021-01-06 Debug placing and filling of limit orders for Call and Put closure
/// 2021-01-07 refined debug placing/filling of Call/Put closure -- include MKT orders to better trace
/// 2021-01-19 debugged oldRollDate. Never set initially and not always set in various branches of code.
/// 2021-01-19 Found that in longer expirations, may try to set AddedMonths to 24. Error where Months%12 =0
/// 2021-01-21 Added code to exercise puts when rolling is more expensive than exercising.
/// 2021-01-24 Added code to conditionally roll up puts when stock appreciates
/// 2021-01-31 Added code in OnOrder() to detect call assignment so that the primary TradeRec collar PUTs are sold uEndPrice is recorded and record is closed
/// 2021-01-31 Modified OTM code because in VCC put and call expirations may be different. Old code didnt trap all OTM situations
/// 2021-02-01 Implemented calling Divididend Check to move code bytes to a different .cs file
/// 2021-02-05 Wrapped OnEndOfDay in try-catch as well as .GetOpenOrders() routines.
/// 2021-02-05 Found that LimitOrderTicket.Update() was not executing -- replaced update with MarketOrder
/// 2021-02-08 ERROR: Found System.InvalidOperationException: Collection was modified; enumeration operation may not execute.
/// Remedied this by creating a list<int> of oLOs.Indices to remove in a second step
/// 2021-02-10 Version 13 Found that slightly OTM 2nd TPRs will not roll at expiration because they are OTM but spread is very small ($1.00). Thus,
/// had to force exercise
/// 2021-02-10 Version 13 Found that the orderTicket.Quantity follows the option, not the stock. Have to multiply by 100M in order to find the TPR
/// 2021-02-10 Version 14 wrote foreach(2ndTPR in SecondTPRs) to process additional 2nd TPRs
/// 2021-02-12 Version 15 reduced minDivs on PutRoll to 1 and only look out to 4th Div, not 5th. Found appreciating stocks move up faster and longer durations unnecessary
/// 2021-02-15 changed formatting codes in IterateOrderedPutSpreads to make visible the ExpirationDate and to limit the decimals to 2 places
/// 2021-02-17 fixed RollPut where expireDateDelta2P<1 and OTM--call Close2TPR. If ITM, then Exercise PUT
/// 2021-02-18 Verssion 16 Found the 2nd TPR loop was using "current2ndRec" (1st 2nd TPR) data, not the actual sTPR from the loop. In situations with more than 1 2nd TPR, was totally wrong
/// 2021-02-20 Version 17 Modified GetExpiries to ensure expires[1] is more than 10 days after the trade date
/// 2021-02-21 modified to allow various paths, CheckDiv, CheckCall, CheckPut, & CheckOTM to execute serially until a good threshold and non-losing roll can be found
/// until the last day, when a Kill or Close is called and forced. Modified OnOrder to track LEAN-intitiated call assignment
/// 2021-02-23 Add GrossPnL and SSQR.netIncome to TPRs for analysis of roll PnL
/// 2021-02-28 Attempted evaluation of ITM based upon actual option premiums rather than an arbitrary 5% based solely upon strikes -- failed due to QC internal algo's
/// 2021-03-03 Base 2ndTPR split based upon intitial short call premium. Rationale is that stock appreciation above that number results in nullification of inititial short term capital collar credit.
/// 2021-03-03 Modified 2ndTPR roll up based upon incrAmount > cost-to-sell-original-puts
/// 2021-03-03 fixed a nit in creating thetaTPR.isSecondary -- make it false to prevent null pointers in processing puts in 2nd TPR Rec
/// 2021-03-05
/// 2021-03-10 Converted to Wing Trade -- added PerfRec columns for wing call performance tracking and removed 2ndTPR Put Rolling and thetaCall processing
/// 2021-03-12 Amended oLO (open limit order) processing to accomondate shoring calls to open collars and wing calls.
/// 2021-03-12 WING VERSION 3 ELIMINATED CONVERSION TRADES -- SET CALLSTRIKE >> PUTSTRIKE
/// 2021-03-12 WING VERSION 4 FIXED WINGFACTOR ERROR IN ROLLS
/// 2021-03-12 WING VERSION 4C implemented hasDividends check
/// 2021-03-12 WING VERSION 4D replaced TPR iteration loop AtEndOfAlogrithm() with expanded line-by-line string concatenation.... could not get actual options symbols otherwise
/// 2021-03-21 WING VERSION 5 adjusted DownsideRisk to use Collar.netBid. Check for ITM WingCall to sell ahead of ITM ShortCall (new code in OnData() after Dividend Approachment
/// 2021-10-17 Moved all CheckRoll.cs code for evaluating and processing rolls based upon expirations and options-monieness into TradePerfRec class.
/// Then, in Main.cs OnData() the list of 1st TPR's are iterated and processed by calling tpr.CheckRoll() method.
/*var OpenOrders = Transactions.GetOpenOrders(); // Get the open orders to search for open limit orders
if (OpenOrders.Count() > 0) { // process them only if there's any open
foreach (var OrderTkt in OpenOrders){ // loop through and process open options limit orders (HasUnderlying)
if (OrderTkt.Status == OrderStatus.Submitted && OrderTkt.Type == OrderType.Limit) {
if (OrderTkt.Symbol.HasUnderlying) {
if (OrderTkt.Symbol.ID.OptionRight == OptionRight.Call) {
var orderUnderlyingPrice = Securities[OrderTkt.Symbol.ID.Underlying.Symbol].Price;
var Ticket = Extensions.ToOrderTicket(OrderTkt,Securities.SecurityTransactionManager);
var orderLimitPrice = Ticket.Get(OrderField.LimitPrice);
var orderStrikePrice = Ticket.Symbol.ID.StrikePrice;
if (orderLimitPrice < orderUnderlyingPrice - orderStrikePrice + 0.10M) { /// this is the criteria for placing a call buyback limit order. This contition will exist if the underlying price has moved up
Ticket.Update(new UpdateOrderFields{LimitPrice = orderUnderlyingPrice - orderStrikePrice + 0.10M});
}
} else if (OrderTkt.Symbol.ID.OptionRight == OptionRight.Put) {
var orderUnderlyingPrice = Securities[OrderTkt.Symbol.ID.Underlying.Symbol].Price;
var orderLimitPrice = OrderTkt.Get(OrderField.LimitPrice);
var orderStrikePrice = OrderTkt.Symbol.ID.StrikePrice;
if (orderLimitPrice > orderStrikePrice - orderUnderlyingPrice - 0.10M) { /// this is the criteria for placing a put sell-to-close limit order. This contition will exist if the underlying price has moved down.
OrderTkt.Update(new UpdateOrderFields{LimitPrice = orderStrikePrice - orderUnderlyingPrice - 0.10M});
}
}
}
}
}
}*/
/*
var OpenTickets = Transactions.GetOrderTickets(); // Get all the orders to search for open limit orders
if (OpenTickets.Count() > 0) { // process them only if there's any open
Debug(" |||||||| We have " + OpenTickets.Count() + " tickets");
foreach (var Ticket in OpenTickets){ // loop through and process open options limit orders (HasUnderlying)
if (Ticket.Status == OrderStatus.Submitted && Ticket.OrderType == OrderType.Limit) {
if (Ticket.Symbol.HasUnderlying) {
Debug(" |||||||| Ticket for " + Ticket.Symbol + " is " + Ticket.Status + " submitted at " + Ticket.Time + " for " + Ticket.Quantity + ".");
if ((int)data.Time.Subtract(Ticket.Time).TotalMinutes > 15) {
if (Ticket.Symbol.ID.OptionRight == OptionRight.Call) {
var orderUnderlyingPrice = Securities[Ticket.Symbol.ID.Underlying.Symbol].Price;
var orderLimitPrice = Ticket.Get(OrderField.LimitPrice);
var orderStrikePrice = Ticket.Symbol.ID.StrikePrice;
var lPrice = orderUnderlyingPrice - orderStrikePrice + 0.10M;
if (orderLimitPrice < orderUnderlyingPrice - orderStrikePrice + 0.10M) { /// this is the criteria for placing a call buyback limit order. This contition will exist if the underlying price has moved up
//Debug(" |||||||| with " + Ticket.Symbol.ID.Underlying.Symbol + " trading at " + orderUnderlyingPrice + ", updating " + Ticket.Symbol + "limit order to new limit price: " + lPrice );
//Ticket.Update(new UpdateOrderFields{LimitPrice = orderUnderlyingPrice - orderStrikePrice + 0.10M});
Ticket.Cancel();
Debug(" |||||||| With " + Ticket.Symbol.ID.Underlying.Symbol + " trading at " + orderUnderlyingPrice + ", updating " + Ticket.Quantity + " of " + Ticket.Symbol + "limit order to market order");
var buyCallTkt = MarketOrder(Ticket.Symbol, Ticket.Quantity);
if (buyCallTkt.Status == OrderStatus.Filled ){
bool anyTPRs = tradeRecs.Any(tr => tr.cSymbol.Equals(Ticket.Symbol) && -tr.cQty == Ticket.Quantity);
if (anyTPRs) {
var callTradeRec = tradeRecs.Where(tr => tr.cSymbol.Equals(Ticket.Symbol) && -tr.cQty == Ticket.Quantity).FirstOrDefault();
callTradeRec.cEndPrice = buyCallTkt.AverageFillPrice;
//foreach (TradePerfRec tpr in callTradeRecs) {
//tpr.cEndPrice = buyCallTkt.AverageFillPrice;
//}
}
}
}
} else if (Ticket.Symbol.ID.OptionRight == OptionRight.Put) {
var orderUnderlyingPrice = Securities[Ticket.Symbol.ID.Underlying.Symbol].Price;
var orderLimitPrice = Ticket.Get(OrderField.LimitPrice);
var orderStrikePrice = Ticket.Symbol.ID.StrikePrice;
var lPrice = orderStrikePrice - orderUnderlyingPrice - 0.10M;
if (orderLimitPrice > orderStrikePrice - orderUnderlyingPrice - 0.10M) { /// this is the criteria for placing a put sell-to-close limit order. This contition will exist if the
//Debug(" |||||||| with " + Ticket.Symbol.ID.Underlying.Symbol + " trading at " + orderUnderlyingPrice + ", updating " + Ticket.Symbol + "limit order to new limit price: " + lPrice ); //underlying price has moved down.
//Ticket.Update(new UpdateOrderFields{LimitPrice = orderStrikePrice - orderUnderlyingPrice - 0.10M});
Ticket.Cancel();
Debug(" |||||||| With " + Ticket.Symbol.ID.Underlying.Symbol + " trading at " + orderUnderlyingPrice + ", updating " + Ticket.Quantity + " of " + Ticket.Symbol + "limit order to market order");
var sellPutTkt = MarketOrder(Ticket.Symbol, Ticket.Quantity);
if (sellPutTkt.Status == OrderStatus.Filled ){
bool anyTPRs = tradeRecs.Any(tr => tr.pSymbol.Equals(Ticket.Symbol) && -tr.pQty == Ticket.Quantity);
if (anyTPRs) {
var putTradeRec = tradeRecs.Where(tr => tr.pSymbol.Equals(Ticket.Symbol) && -tr.pQty == Ticket.Quantity).FirstOrDefault();
putTradeRec.pEndPrice = sellPutTkt.AverageFillPrice;
//foreach (TradePerfRec tpr in putTradeRecs) {
//tpr.pEndPrice = sellPutTkt.AverageFillPrice;
//}
} // is there TPR
} // if order filled
} // limit price needs to be changed
} /// < 15" after order submission
} // PUT
} // OPTION ORDER
} // FOR LOOP
}
}
} catch (Exception errMsg)
{
Debug(" ERROR " + errMsg );
if (errMsg.Data.Count > 0) {
Debug(" Extra details:");
foreach (DictionaryEntry de in errMsg.Data)
Debug(" Key: {0,-20} Value: {1}'" + de.Key.ToString() + "'" + de.Value);
}
} */
}using QuantConnect.Securities.Option;
namespace QuantConnect.Algorithm.CSharp {
public partial class CollarAlgorithm : QCAlgorithm
{
public class SSQRColumn
{
public decimal stockPrice = 0;
public DateTime exDate = DateTime.Now;
public DateTime putExpiry = DateTime.Now;
public DateTime callExpiry = DateTime.Now;
public int daysInPosition = 0;
public decimal interestCost = 0;
public Symbol uSymbol;
public Symbol putSymbol;
public Symbol callSymbol;
public Symbol wCallSymbol;
public decimal putPremium = 0; // paid for buying the body
public decimal callPremium = 0; // received for selling back call
public decimal wCallPremium = 0; // paid for buying the wings
public decimal putStrike = 0;
public decimal callStrike = 0;
public decimal wCallStrike = 0;
public decimal putOpenInterest = 0;
public decimal callOpenInterest = 0;
public decimal putDelta = 0;
public decimal callDelta = 0;
public decimal wcDelta = 0;
public decimal wingFactor = 0;
public decimal putGamma = 0;
public decimal callGamma = 0;
public decimal wcGamma = 0;
public decimal putVega = 0;
public decimal callVega = 0;
public decimal putRho = 0;
public decimal callRho = 0;
public decimal putTheta = 0;
public decimal callTheta = 0;
public decimal putImpliedVol = 0;
public decimal callImpliedVol = 0;
public decimal divAmt = 0;
public int divCount = 0;
public decimal downsideRisk = 0;
public decimal upsidePotential = 0;
public decimal netIncome = 0;
public decimal netOptions = 0;
public decimal divDollars = 0;
public decimal haircut = 0; // committed capital in a portfolio margin account
public decimal ROC = 0; // Return on Capital
public decimal ROR = 0; // Return on Risk
public decimal CCOR = 0; // Call Coverage over downside Risk
public string description1 = "";
public string description2 = "";
//public string description3;
public override string ToString()
{
return this.description1;
}
public bool IsEmpty()
{
return this.description1.IsNullOrEmpty();
}
}
}
}///////////////////////////// 2020-12-01: Added CCOR member to SSQR Column and to description2 for SSQR Matrices spreadsheet
using System.Linq;
using QuantConnect.Securities.Option;
namespace QuantConnect.Algorithm.CSharp {
//
// Make sure to change "BasicTemplateAlgorithm" to your algorithm class name, and that all
// files use "public partial class" if you want to split up your algorithm namespace into multiple files.
//
public partial class CollarAlgorithm : QCAlgorithm
{
// ********************** assembleSSQRMatrix **************************************
// *** This sub routine takes in the options expiries and all the symbols
// *** available in the Slice.Data and builds the puts chains and calls symbols lists
// *** The puts and calls symbols lists are used to build the contracts lists
// ** The contracts lists are used to build the SSQR Matrix
// ***********************************************************************************
// = assembleSSQRMatrix(algo, LD, expiries);
/*
foreach (var universe in UniverseManager.Values) {
// User defined universe has symbols from AddSecurity/AddEquity calls
if (universe is UserDefinedUniverse) {
continue;
}
List<Symbol> UniverseMembers = new List<Symbol>(universe.Members.Keys);
foreach (Symbol symb in UniverseMembers) {
i = i + 1;
Debug("," + i.ToString() + ", " + symb.Value);
}
}
*/
// *** NEED TO ENSURE THAT THE CALL IS NOT ITM <= EXPIRY - 10 DAYS --- PREVENT CALL ASSIGNMENT
public void AssembleSSQRMatrix(QCAlgorithm algo, ref LookupData LD, Dictionary<int, DateTime> expiries)
{
int i = 1;
if (LD.doTracing) algo.Debug($" -- AA AA ASSEMBLE SSQR MATRIX FOR {thisSymbol}");
if (LD.haltProcessing)
{
algo.Debug(" @@@@@ logging assembleSSQR processing");
foreach (var universe in UniverseManager.Values) {
// User defined universe has symbols from AddSecurity/AddEquity calls
if (universe is UserDefinedUniverse) {
continue;
}
List<Symbol> UniverseMembers = new List<Symbol>(universe.Members.Keys);
foreach (Symbol symb in UniverseMembers) {
i = i + 1;
Debug("," + i.ToString() + ", " + symb.Value);
}
}
}
Symbol symbU = LD.uSymbol;
//List<OptionChain> allUnderlyingOptions = new List<OptionChain>(); // chain object to get all options
//allUnderlyingOptions = thisSlice.OptionChains.Values.Where(u => u.Underlying.Symbol.Equals(symbU)).ToList();
OptionChain allUnderlyingOptions = null; // chain opbjec to get all contracts
OptionChain putChain; // chain object to get put contracts
OptionChain callChain; // chain object to get call contracts
OptionChain wcChain; // chain object to get wc contracts
OptionChain atmChain; // chain object to ATM call
List<OptionContract> putContracts = new List<OptionContract>();
List<OptionContract> callContracts = new List<OptionContract>();
List<OptionContract> wCallContracts = new List<OptionContract>();
OptionContract putContract; // contract object to collect put greeks
OptionContract callContract; // contract object to collect call greeks
//OptionContract wcContract; // contract object to collect wing call greeks
Greeks putGreeks;
Greeks callGreeks;
Greeks wcGreeks;
Slice thisSlice = algo.CurrentSlice;
DateTime tradeDate = thisSlice.Time; // current date, presumed date of trade
// if(!thisSlice.OptionChains.TryGetValue(SD.optSymbol, out allUnderlyingOptions)) return; /// NOTE: DOES NOT RETURN wcChain
foreach(var chain in thisSlice.OptionChains.Values){
if (chain.Underlying.Symbol != symbU) { continue; }
allUnderlyingOptions = chain;
break;
}
if (allUnderlyingOptions == null) {
if (LD.doTracing) algo.Debug("-- No options returned for " + symbU.ToString() + " at " + thisSlice.Time);
return; // return null SSQRMatrix and pass control back to OnData()
}
// Get the ATM call contract
var atmCall = allUnderlyingOptions.Where(s => s.Right == OptionRight.Call)
.OrderBy(s => Math.Abs(stockPrice - s.Strike))/// - stockPrice))
.FirstOrDefault();
var atmPut = allUnderlyingOptions.Where(s => s.Right == OptionRight.Put)
.OrderBy(s => Math.Abs(stockPrice - s.Strike)) /// - stockPrice))
.FirstOrDefault();
var atmStrike = atmCall.Strike;
if (atmStrike == 0 ) { return;}
var lowStrike = (1 - (LD.maxPutOTM / (decimal)100)) * atmStrike; // ~~ eventually need a mechanism to determine strike steps
var highStrike = (decimal)1.1 * atmStrike; // ~~ and use strike steps to set upper and lower bounds
// decimal highWCStrike = 0; // for evaluating the range of wing call strikes
// decimal lowWCStrike = 0; // for evaluating the range of wing call strikes
// decimal wcInterval = 0; // for calculating wing calls
// examine options expiries to get proper dividend-correlated time-frames
// Alex informed me that the openInterest data has to be warmed up
// Alex further informed me that .OpenInterest does not work, rather, use .Value
//var callOpenInterest = History<OpenInterest>(atmCall, TimeSpan.FromDays(5)).FirstOrDefault();
//var putOpenInterest = History<OpenInterest>(atmPut, TimeSpan.FromDays(5)).FirstOrDefault();
//var totOpenInterest = callOpenInterest.Value + putOpenInterest.Value;
//if (doTracing) Debug("0O0O0O0O0O0O0O0O0O0O0O0O0O0O0O0O0O0O0O0O0O0O0O0O0O0O0O0O0O0O0O0O0O0O0O0O0O0O0O");
//if (doTracing) Debug("0O0O0O0O0O0O0O0O0O0O0O0O OPEN INTEREST 0O0O0O0O0O0O0O0O0O0O0O0O0O0O0");
//if (doTracing) Debug(" The total Put + Call Open Interest for " + atmCall.ID.Underlying + " is " + atmCallOpt.OpenInterest + ".");
//if (doTracing) Debug("0O0O0O0O0O0O0O0O0O0O0O0O0O0O0O0O0O0O0O0O0O0O0O0O0O0O0O0O0O0O0O0O0O0O0O0O0O0O0O");
int k = 1; // initialize iterator for AddOptionContracts below
Symbol optSymbol; // initialize option symbol for building the list of contracts
Option tempOption; // initialize option contract for building list of contracts and obtaining pricing data
List<Option> callOptionsList = new List<Option>();
List<Option> putOptionsList = new List<Option>();
List<Option> wcCallsList = new List<Option>();
DateTime whichExpiry = new DateTime();
//daysInTrade = ((TimeSpan) (whichExpiry - tradeDate)).Days; // get the # of days from trade date to expiry for carry cost
///////// NOTE : CATCH THE EXCEPTION WHERE LOOKUP FAILS
var justDate = tradeDate.Date; // separate out the DATEVALUE from the DateTime variable
LD.thisFFRate = LD.fedFundsRates[justDate]; // fedFundsRates is a Dictionary where DateTime index are all 12:00:00am
//interestCost = (thisFFRate + ibkrRateAdj)/workingDays * (decimal) daysInTrade * stockPrice;
// create a range of expiration dates from the prior expiration to the whichExpiry date.
//callSymbolsForThisExpiry = allUnderlyingOptionsSymbols.Where( o=> DateTime.Compare(o.ID.Date, pastExpiry) > 0 && DateTime.Compare(o.ID.Date, whichExpiry)<=0 &&
if (LD.haltProcessing) {
algo.Debug("---------------------- Expiries ----------------------------");
algo.Debug("-----" + stockPrice.ToString() + ", " + lowStrike.ToString() + ", " + highStrike.ToString() + ", " + expiries[2].ToString("MM/dd/yy") + ", " + expiries[3].ToString("MM/dd/yy") + ", " + expiries[4].ToString("MM/dd/yy") + ", " + expiries[5].ToString("MM/dd/yy"));
//IterateChain(allUnderlyingOptionsSymbols, "allUnderlyingOptionsSymbols");
}
callContracts = allUnderlyingOptions.Where( o=> ( DateTime.Compare(o.Expiry, expiries[2])==0 |
DateTime.Compare(o.Expiry, expiries[3])==0 |
DateTime.Compare(o.Expiry, expiries[4])==0 |
DateTime.Compare(o.Expiry, expiries[5])==0 ) &&
o.Right == OptionRight.Call &&
o.Strike >= lowStrike &&
o.Strike < highStrike)
.OrderByDescending(o => o.Strike).ToList();
// **************** Check if any calls are returned. If not, increment expiries by 1 month and try again
if (callContracts == null | callContracts.Count() == 0)
{
if (LD.doTracing) Debug("-- get callContracts failed 1st Pass "); /// use the expiries[1] date as the seed and find the subsequent 4 3-month expirations
expiries[2] = FindNextOptionsExpiry(expiries[1], 4);
expiries[3] = FindNextOptionsExpiry(expiries[1], 7);
expiries[4] = FindNextOptionsExpiry(expiries[1], 10);
expiries[5] = FindNextOptionsExpiry(expiries[1], 13);
callContracts = allUnderlyingOptions.Where( o=> ( DateTime.Compare(o.Expiry, expiries[2])==0 |
DateTime.Compare(o.Expiry, expiries[3])==0 |
DateTime.Compare(o.Expiry, expiries[4])==0 |
DateTime.Compare(o.Expiry, expiries[5])==0 ) &&
o.Right == OptionRight.Call &&
o.Strike >= lowStrike &&
o.Strike < highStrike)
.OrderByDescending(o => o.Strike).ToList();
if (LD.haltProcessing) {
if (LD.doTracing) algo.Debug("---------------------- Expiries 2nd Pass ----------------------------");
if (LD.doTracing) algo.Debug("--" + stockPrice.ToString() +", " + expiries[2].ToString("MM/dd/yy") + ", " + expiries[3].ToString("MM/dd/yy") + ", " + expiries[4].ToString("MM/dd/yy") + ", " + expiries[5].ToString("MM/dd/yy"));
//if (doTracing);(callSymbolsForThisExpiry, "callSymbols");
}
// ***************** If no calls are returned in 2nd pass, exit with null SSQRMatrix
if (callContracts == null || callContracts.Count() == 0)
{
if (LD.doTracing) algo.Debug("-- get callContracts failed 2nd Pass ");
return;
} else if (LD.doTracing) algo.Debug("-- get callContracts succeeded 2nd Pass ");
} else {
if (LD.doTracing) algo.Debug(" -- getCallContracts succeded 1st pass "); // ***************** Log successful 1st pass options search
}
//callOptionsList.Clear();
// if the first attempt at obtaining calls fails, then expiries[2-5] are incremented by 1 month. If that fails
// this subroutine was exited before here. In any case, if calls can be obtained, puts can be as well
//putSymbolsForThisExpiry = allUnderlyingOptionsSymbols.Where( o=> DateTime.Compare(o.ID.Date, pastExpiry) > 0 && DateTime.Compare(o.ID.Date, whichExpiry)<=0 &&
putContracts = allUnderlyingOptions.Where( o=> ( DateTime.Compare(o.Expiry, expiries[2])==0 |
DateTime.Compare(o.Expiry, expiries[3])==0 |
DateTime.Compare(o.Expiry, expiries[4])==0 |
DateTime.Compare(o.Expiry, expiries[5])==0 ) &&
o.Right == OptionRight.Put &&
o.Strike >= lowStrike &&
o.Strike < atmStrike)
.OrderByDescending(o => o.Strike).ToList();
if (LD.haltProcessing) {
if (LD.doTracing) algo.Debug("---------------------- Expiries PUTS Pass ----------------------------");
if (LD.doTracing) algo.Debug(" --" + stockPrice.ToString() +", " + expiries[2].ToString("MM/dd/yy") + ", " + expiries[3].ToString("MM/dd/yy") + ", " + expiries[4].ToString("MM/dd/yy") + ", " + expiries[5].ToString("MM/dd/yy"));
//if (doTracing) IterateChain(putSymbolsForThisExpiry, "putSymbols");
}
if (putContracts == null | putContracts.Count()== 0)
{
if (LD.doTracing) algo.Debug("-- get putSymbolsForThisExpiry failed 2nd Pass (after call succeeded)");
return; // return null SSQRMatrix and pass control back to OnData()
}
if (LD.doTracing) Debug("-- get putSymbolsForTheseExpiries succeeded.");
var pEnumerator = putContracts.GetEnumerator();
// Now iterate through the puts and sub-iterate through the calls to assemble the SSQRMatrix
// for pricing, puts are bought at the offer and calls are sold at the bid prices.
// Each price should be the midpoint between the open and close.
while (pEnumerator.MoveNext())
{
var cEnumerator = callContracts.GetEnumerator();
putContract = pEnumerator.Current;
atmCall = callContracts.Where(s => DateTime.Compare(s.Expiry, putContract.Expiry)==0) /// get atmCall for this Put Option Expiration
.OrderBy(s => Math.Abs(s.Strike - stockPrice))
.FirstOrDefault();
wCallContracts.Clear();
wCallContracts = callContracts.Where( o=> ( DateTime.Compare(o.Expiry, putContract.Expiry)==0) &
o.Strike >= atmStrike &
o.Strike <= (decimal)1.1 * atmCall.Strike).Distinct().ToList();
if (LD.haltProcessing & LD.doTracing) Debug($" -- Put Option {pEnumerator.Current} ");
wCallContracts.Sort((x,y) => x.Strike.CompareTo(y.Strike));
var wcEnumerator = wCallContracts.GetEnumerator();
while (cEnumerator.MoveNext())
{
callContract = cEnumerator.Current;
//if (thisCallStrike > thisPutStrike & DateTime.Compare(thisCallExpiry,thisPutExpiry)>=0 ) // only add put/call combinations where call strike is above put strike and call expiry is equal to or later than put
if ((callContract.Strike > putContract.Strike & DateTime.Compare(callContract.Expiry, putContract.Expiry)>=0) | (callContract.Strike >= putContract.Strike & DateTime.Compare(callContract.Expiry,putContract.Expiry)>0 )) // only add put/call combinations where call strike is equal to or above put strike and call expiry is later than put OR (c.strike>=put.strike AND c.Expiry>=p.Expiry)
{
foreach (var wcContract in wCallContracts) {
if (wcContract.Strike > callContract.Strike ) {
SSQRColumn thisSSQRColumn = buildSSQRColumn(putContract, callContract, wcContract, algo, LD);
if (thisSSQRColumn != null) LD.SSQRMatrix.Add(thisSSQRColumn);
}
}
} // if thisCallStrike == thisPutStrike
} // while callEnum
} // while putEnum
if (LD.doTracing) Debug($" -- AA AA RETURNED {LD.SSQRMatrix.Count()} SSQR MATRICES FOR {LD.uSymbol}" );
{
} // !null
return;
} // AssembleSSQRMatrix
// ********************** buildSSQRColumn **************************************
// *** This sub routine takes in the variables for the iterated put and call Options Lists
// *** as well as the dividends count, dividend amount, and stock price
// *** and returns an SSQRColumt to be added to the SSQRMatrix list
// ***********************************************************************************
public SSQRColumn buildSSQRColumn(OptionContract thisPutOpt, OptionContract thisCallOpt, OptionContract wcOpt, QCAlgorithm algo, LookupData LD)
//public SSQRColumn buildSSQRColumn(Option thisPutOpt, Option thisCallOpt, OptionContract pGrks, OptionContract cGrks, DateTime whichExpiry, DateTime tradeDate, DateTime exDate, int dividends, decimal amtDividend, decimal stockPrice, int daysInTrade, decimal intCost)
{
decimal thisSpread = 1M;
decimal wingFactor = .2M; // factor to determine wings contract load
decimal wingPremium = 1; // added premium to do the wings
int monthsInTrade = 0;
int daysInTrade = 0;
int dividends = 0;
Slice thisSlice = algo.CurrentSlice;
decimal stockPrice = thisSlice[LD.uSymbol].Price;
SSQRColumn thisColumn = new SSQRColumn(); // get a new SSQRColumn
if (thisPutOpt.AskPrice == 0 | thisCallOpt.BidPrice == 0) return thisColumn; // don't build SSQRColumns with missing premium values
DateTime tradeDate = algo.CurrentSlice.Time;
daysInTrade = (thisPutOpt.Expiry - tradeDate).Days;
decimal intCost = (LD.thisFFRate + LD.ibkrRateAdj)/LD.workingDays * (decimal) daysInTrade * stockPrice;
if (haltProcessing) {
Debug(" Logging buildSSQRColumn processing") ;
}
monthsInTrade = thisPutOpt.Expiry.Month - LD.exDivdnDate.Month;
if( thisPutOpt.Expiry.Year != LD.exDivdnDate.Year) {
monthsInTrade = monthsInTrade + 12;
}
if (divFrequency.Equals("monthly", StringComparison.OrdinalIgnoreCase)) {
dividends = monthsInTrade + 1;
} else {
dividends = monthsInTrade/3 + 1; // add 1 for the next dividend and 1 for every 3 months thereafter
}
thisColumn.uSymbol = LD.uSymbol;
thisColumn.putSymbol = thisPutOpt.Symbol;
thisColumn.callSymbol = thisCallOpt.Symbol;
thisColumn.wCallSymbol = wcOpt.Symbol; // atm call for this column (based upon put)
thisColumn.putPremium = thisPutOpt.AskPrice;
thisColumn.callPremium = thisCallOpt.BidPrice;
thisColumn.wCallPremium = wcOpt.AskPrice; //
thisColumn.putStrike = thisPutOpt.Strike;
thisColumn.callStrike = thisCallOpt.Strike;
thisColumn.wCallStrike = wcOpt.Strike;
thisColumn.exDate = LD.exDivdnDate;
thisColumn.putExpiry = thisPutOpt.Expiry;
thisColumn.callExpiry = thisCallOpt.Expiry;
thisColumn.putDelta = thisPutOpt.Greeks.Delta;
thisColumn.callDelta = thisCallOpt.Greeks.Delta;
thisColumn.wcDelta = wcOpt.Greeks.Delta;
thisColumn.putGamma = thisPutOpt.Greeks.Gamma;
thisColumn.callGamma = thisCallOpt.Greeks.Gamma;
thisColumn.wcGamma = wcOpt.Greeks.Gamma;
//thisColumn.putVega = thisPutOpt.Greeks.Vega;
//thisColumn.callVega = thisCallOpt.Greeks.Vega;
//thisColumn.putRho = thisPutOpt.Greeks.Rho;
//thisColumn.callRho = thisCallOpt.Greeks.Rho;
//thisColumn.putTheta = thisPutOpt.Greeks.Theta;
//thisColumn.callTheta = thisCallOpt.Greeks.Theta;
thisColumn.putImpliedVol = thisPutOpt.ImpliedVolatility;
thisColumn.callImpliedVol = thisCallOpt.ImpliedVolatility;
thisColumn.divAmt = LD.divdndAmt;
thisColumn.divCount = dividends;
thisColumn.stockPrice = stockPrice;
thisColumn.daysInPosition = daysInTrade;
thisColumn.interestCost = intCost;
thisSpread = thisCallOpt.Strike - thisPutOpt.Strike;
if (!LD.ibkrHairCuts.ContainsKey( (thisSpread)) )
{
//Debug("*^*^*^*^*^*^*^*^*^*^**^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*");
//Debug("Make a haircut entry for " + (thisCallStrike - thisPutStrike).ToString());
//Debug("*^*^*^*^*^*^*^*^*^*^**^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*");
if (thisSpread < 5M)
{
thisColumn.haircut = .5M;
} else thisColumn.haircut = thisSpread;
}else
{
thisColumn.haircut = LD.ibkrHairCuts[thisSpread];
}
decimal divDollars = LD.divdndAmt * dividends;
thisColumn.divDollars = divDollars;
decimal stockLossIfCalled = (thisCallOpt.Strike>stockPrice) ? 0 : (thisColumn.putPremium>thisColumn.callPremium) ? (thisColumn.callStrike - stockPrice) : 0; // loss=0 if cStrike>stkPrice, otherwise negative ***Loss (negative value) if ITM calls are assigned (0 if #calls<#puts)
decimal netOptions = -thisColumn.putPremium + thisColumn.callPremium; /// netOptions equals negative putPrem (expense) plus positive call premium (income)
thisColumn.netOptions = netOptions;
thisColumn.netIncome = divDollars + netOptions - intCost; // Net Income in SSQR.xls subtracts interest cost but does not allow for appreciation to OTM call strike /// obviated in Wing System which has an upside long call
wingFactor = (netOptions + divDollars - intCost) / wingPremium; // wing factor defined as income(loss) from options plus dividend minus interest cost divided by the premium paid for the wings
if (wingFactor < 0) wingFactor = 0;
if (wingFactor > 0.2M ) wingFactor = 0.2M;
thisColumn.wingFactor = wingFactor;
thisColumn.ROC = (divDollars + netOptions + stockLossIfCalled - intCost) / thisColumn.haircut; // store ROC for statistical analysis
// 2021-03-21 -- (factored in netOptions into downsideRisk calculation)
//decimal downsideRisk = thisPutStrike - stockPrice + divDollars + netOptions - intCost; // downside risk is defined as the potential loss due to stock price depreciation _
decimal downsideRisk = ((stockPrice - thisColumn.netOptions) > thisColumn.putStrike) ? stockPrice - netOptions - thisColumn.putStrike + thisColumn.interestCost: thisColumn.interestCost; // downside risk is the net price of the collar - putStrike (deliberately discounts dividends as they are not guaranteed past the declared dividend)
thisColumn.downsideRisk = downsideRisk; // subtracts dividends collected and net options premiums and intCost
decimal upsidePotential = (thisColumn.callStrike>stockPrice) ? thisColumn.callStrike - stockPrice + divDollars + netOptions - intCost : divDollars + netOptions - intCost; // When writing OTM calls, there is a potential
thisColumn.upsidePotential = upsidePotential; // upside appreciation from net collar cost to the call strike.
// 2021-03-24 -- -- changed sign on downsideRisk from negative to positive. Earlier iterations represented downside risk as negative (putStrike - stock purchase price).
thisColumn.ROR = upsidePotential/downsideRisk; // store ROR for statistical analysis
/*if (stockPrice == thisPutStrike) {
thisColumn.CCOR = (1 - thisPutPrem/thisCallPrem)/0.01M; // get the maximum upside potential for a unit of actual risk
} else {
thisColumn.CCOR = (1 - thisPutPrem/thisCallPrem)/(stockPrice - thisPutStrike);
} */
// 2021-03-21 -- -- changed to ordered by downsideRisk/upsidePotential
//thisColumn.CCOR = netOptions/downsideRisk; // get the maximum upside potential for a unit of actual risk
thisColumn.CCOR = downsideRisk/upsidePotential;
thisColumn.description1 = "Combination in " + LD.uSymbol + " @ " + stockPrice + " is the " + thisColumn.putStrike + "/" + thisColumn.callStrike + " collar ";
thisColumn.description2 = "," + thisColumn.uSymbol + "," + String.Format("{0:0.00}", stockPrice) + "," + LD.exDivdnDate.ToString("MM/dd/yy") + ","
+ dividends + "," + String.Format("{0:0.00}", LD.divdndAmt) + "," + String.Format("{0:0.00}",divDollars) + "," + daysInTrade + ", "
+ String.Format("{0:0.00}", intCost) + ", " + thisColumn.putExpiry.ToString("MM/dd/yy") + ", " + thisColumn.callExpiry.ToString("MM/dd/yy") + ", "
+ String.Format("{0:0.00}",thisColumn.putStrike) + ", " + String.Format("{0:0.00}",thisColumn.putPremium) + ", "
+ String.Format("{0:0.00}",thisColumn.callStrike) + ", " + String.Format("{0:0.00}", thisColumn.callPremium) + ", "
+ String.Format("{0:0.00}", thisColumn.wCallStrike) + ", " + String.Format("{0:0.00}", thisColumn.wCallPremium) + ", "
+ String.Format("{0:0.00}",thisColumn.putDelta) + ", " + String.Format("{0:0.00}", thisColumn.callDelta) + ", "
+ String.Format("{0:0.00}",thisColumn.netOptions) + ", " + String.Format("{0:0.00}", thisColumn.netIncome) + ", " + String.Format("{0:0.00}", thisColumn.haircut) + ", "
+ String.Format("{0:0.00}",thisColumn.ROC) + "," + String.Format("{0:0.00}", thisColumn.upsidePotential) + ","
+ String.Format("{0:0.00}", thisColumn.downsideRisk) + "," + String.Format("{0:0.00}",thisColumn.ROR) + "," + String.Format("{0:0.00}", thisColumn.CCOR ) + ","
+ String.Format("{0:0.00}", thisColumn.wingFactor) + "," + thisColumn.putSymbol + "," + thisColumn.callSymbol;
return thisColumn;
}
// ********************** AddCorrespondingPut *******************************************
// *** This code will add the put option which corresponds to the call shorted
// *** for purposes of evaluating it in ex-dividend approachment.
// *** Option must be constructed with correct parameters before it can be added
// ******************************************************************************************
public Option AddCorrespondingPut(Symbol tradableCall, ref List<Symbol> currentOptions)
{
int indexOfC = tradableCall.ToString().LastIndexOf("C");
char[] charArrayC = tradableCall.ToString().ToCharArray();
char[] charArrayP = charArrayC;
charArrayP[indexOfC] = 'P';
string putString = new string(charArrayP);
var putSymbol = QuantConnect.Symbol.CreateOption(
tradableCall.Underlying,
Market.USA,
OptionStyle.American,
OptionRight.Put,
tradableCall.ID.StrikePrice,
tradableCall.ID.Date);
Option correspondingPut = AddOptionContract(putSymbol);
currentOptions.Add(correspondingPut.Symbol);
return correspondingPut;
}
// ********************** GetCorrespondingPut *******************************************
// *** This code will get the put option which corresponds to the call shorted
// *** for purposes of evaluating it in ex-dividend approachment --
// *** ??? return Symbol or string?
// ******************************************************************************************
public string GetCorrespondingPut(Symbol tradableCall)
{
int indexOfC = tradableCall.ToString().LastIndexOf("C");
char[] charArrayC = tradableCall.ToString().ToCharArray();
char[] charArrayP = charArrayC;
charArrayP[indexOfC] = 'P';
string putString = new string(charArrayP);
return putString;
}
public SSQRColumn fillSSQRColumn ()
{
SSQRColumn anotherSSQRColumn = new SSQRColumn();
return anotherSSQRColumn;
}
// ********************** GetOptionsExpiries **************************************
// *** Use this to find and return the next 4 options expirations expirations dates
// *** Function will determine if a date is a holiday and subtract 1 day
// ***********************************************************************************
public Dictionary<int, DateTime> GetOptionExpiries(DateTime tradeD, DateTime nextExDate, DateTime thisMonthExpiry, bool isPrimary){
// Initialize expiration date variables //
DateTime firstExpiry = new DateTime();
DateTime secondExpiry = new DateTime();
DateTime thirdExpiry = new DateTime();
DateTime fourthExpiry = new DateTime();
DateTime fifthExpiry = new DateTime();
// Initialize the dictionary for return
// 1 : first expiry
// 2 : second expiry...
Dictionary<int, DateTime> expiries = new Dictionary<int, DateTime>();
// is the nextExDate before or after the 3rd Friday? Before ? use this month expiration
// After ? use next month's expiration.
if (isPrimary) // isPrimary ? 1stTPR : 2ndTPR 1stTPR do monthly options every quarter : 2ndTPR do monthly options every month
{
if (DateTime.Compare(nextExDate, thisMonthExpiry) <= 0)
{
firstExpiry = FindNextOptionsExpiry(thisMonthExpiry, 0); // first figure out the options expriry for exDivDate month
if (firstExpiry.Subtract(tradeD).Days <= 10) { // if firstExpiry is less than 10 days after tradeDate, assignment risk is too high. Move expiries back a month
firstExpiry = FindNextOptionsExpiry(thisMonthExpiry, 1);
secondExpiry = FindNextOptionsExpiry(thisMonthExpiry, 4);
thirdExpiry = FindNextOptionsExpiry(thisMonthExpiry, 7);
fourthExpiry = FindNextOptionsExpiry(thisMonthExpiry, 10);
fifthExpiry = FindNextOptionsExpiry(thisMonthExpiry, 13);
} else
{
secondExpiry = FindNextOptionsExpiry(thisMonthExpiry, 3);
thirdExpiry = FindNextOptionsExpiry(thisMonthExpiry, 6);
fourthExpiry = FindNextOptionsExpiry(thisMonthExpiry, 9);
fifthExpiry = FindNextOptionsExpiry(thisMonthExpiry, 12);
}
} else
{
firstExpiry = FindNextOptionsExpiry(thisMonthExpiry, 1);
secondExpiry = FindNextOptionsExpiry(thisMonthExpiry, 4);
thirdExpiry = FindNextOptionsExpiry(thisMonthExpiry, 7);
fourthExpiry = FindNextOptionsExpiry(thisMonthExpiry, 10);
fifthExpiry = FindNextOptionsExpiry(thisMonthExpiry, 13);
}
} else { // this is for 2ndTPRs -- monthly options every month to catch some
if (DateTime.Compare(nextExDate, thisMonthExpiry) <= 0)
{
firstExpiry = FindNextOptionsExpiry(thisMonthExpiry, 0);
secondExpiry = FindNextOptionsExpiry(thisMonthExpiry, 1);
thirdExpiry = FindNextOptionsExpiry(thisMonthExpiry, 2);
fourthExpiry = FindNextOptionsExpiry(thisMonthExpiry, 3);
fifthExpiry = FindNextOptionsExpiry(thisMonthExpiry, 4);
}else
{
firstExpiry = FindNextOptionsExpiry(thisMonthExpiry, 1);
secondExpiry = FindNextOptionsExpiry(thisMonthExpiry, 2);
thirdExpiry = FindNextOptionsExpiry(thisMonthExpiry, 3);
fourthExpiry = FindNextOptionsExpiry(thisMonthExpiry, 4);
fifthExpiry = FindNextOptionsExpiry(thisMonthExpiry, 5);
}
}
expiries.Add(1, firstExpiry);
expiries.Add(2, secondExpiry);
expiries.Add(3, thirdExpiry);
expiries.Add(4, fourthExpiry);
expiries.Add(5, fifthExpiry);
return expiries;
}
// ********************** FindNextOptionsExpiry **************************************
// *** Use this to find and return the next options expirations date x months ahead
// *** Check the new date to make sure it isn't a holiday and if it is, subtract 1 day
// ********************************************************************************************
public DateTime FindNextOptionsExpiry(DateTime thisExpiry, int addedMonths){
// Given a 3rd friday expiration, it will find the next 3rd friday expiration, addedMonths ahead
// figure out how to handle holidays such as Good Friday, April 19, 2019.
// **************** should this be amended for non-quarterly dividend frequencies? ****************
int year = thisExpiry.Year;
int month = thisExpiry.Month;
while (addedMonths >= 12) {
year = year + 1;
addedMonths = addedMonths - 12;
}
month = month + addedMonths;
// Adjust if bigger than 12
if(month > 12){
month = month % 12;
year = year + 1;
}
if (haltProcessing) {
Debug(" Logging FindNextOptionsExpiry() " + year.ToString() + "-" + month.ToString() );
}
DateTime findDate = FindDay(year, month, DayOfWeek.Friday, 3);
// Evaluate if found expirations fall upon holidays and if they do, decrement them 1 day
while (USHoliday.Dates.Contains(findDate)) findDate = findDate.AddDays(-1);
return findDate;
}
// ********************** FindDay *******************************************************
// *** Generalized function to find and return a DateTime for a given year, month, DayOfWeek
// *** and occurrence in the month.
// ***
// ********************************************************************************************
public DateTime FindDay(int year, int month, DayOfWeek Day, int occurrence)
{
if (haltProcessing) {
Debug(" Logging FindDay() " + year.ToString() + "-" + month.ToString() + "-" + Day.ToString() + ", at " + occurrence.ToString() + " day");
}
// Given a valid month, it will find the datetime for the 3rd friday of the month
if (occurrence <= 0 || occurrence > 5)
throw new Exception("occurrence is invalid");
DateTime firstDayOfMonth = new DateTime(year, month, 1);
//Substract first day of the month with the required day of the week
var daysneeded = (int)Day - (int)firstDayOfMonth.DayOfWeek;
//if it is less than zero we need to get the next week day (add 7 days)
if (daysneeded < 0) daysneeded = daysneeded + 7;
//DayOfWeek is zero index based; multiply by the occurrence to get the day
var resultedDay = (daysneeded + 1) + (7 * (occurrence - 1));
if (resultedDay > (firstDayOfMonth.AddMonths(1) - firstDayOfMonth).Days)
throw new Exception(String.Format("No {0} occurrence(s) of {1} in the required month", occurrence, Day.ToString()));
if (month == 2) {
if (year == 2016 | year == 2020) {
if (resultedDay > 29) {
resultedDay = resultedDay - 29;
month = 3;
}
} else {
if (resultedDay > 28) {
resultedDay = resultedDay - 28;
month = 3;
}
}
}
try
{
return new DateTime(year, month, resultedDay);
}
catch
{
throw new Exception($"Invalid date: {year}/{month}/{resultedDay}");
}
}
// ********************** IterateChain *******************************************************
// *** Generalized function to iterate through and print members of an IEnumerable
// *** This is used for debugging only
// ********************************************************************************************
public void IterateChain(IEnumerable<Symbol> thisChain, string chainName)
{
int k = 1;
Symbol optSymbol;
var enumerator = thisChain.GetEnumerator();
Debug(" |||||||||||||||||||||||||||||||| NEW OPTION SYMBOL CHAIN |||||||||||||||||||||||||||||||");
Debug("There are " + thisChain.Count() + " options symbols in this " + chainName + ". ");
while (enumerator.MoveNext())
{
optSymbol = enumerator.Current;
//Debug("Iterated " + k + " times");
//Debug(optSymbol.Value);
Debug(optSymbol.Value + " " + optSymbol.ID.StrikePrice + " " + optSymbol.ID.Date + " " + optSymbol.ID.OptionRight);
k++;
}
//Debug(" ---------------------------------------------------------------------------------------------");
}
// ********************** IterateContracts *******************************************************
// *** Generalized function to iterate through and print members of an IEnumerable of Contracts
// *** This is used for debugging only
// ********************************************************************************************
public void IterateContracts(List<Option> thisOptionsList)
{
int k = 1;
Option thisOption;
var enumerator = thisOptionsList.GetEnumerator();
Debug(" |||||||||||||||||||||||||||||||| NEW OPTION CONTRACTS LIST |||||||||||||||||||||||||||||||");
Debug("There are " + thisOptionsList.Count() + " contracts in this options list.");
while (enumerator.MoveNext())
{
thisOption = enumerator.Current;
//Debug("Iterated " + k + " times");
//Debug("Option Chain: " + thisOption.ToString());
//Debug(thisOption.StrikePrice + " " + thisOption.Expiry + " " + thisOption.Right + " " + thisOption.GetLastData());
Debug(thisOption.StrikePrice + " " + thisOption.Expiry + " " + thisOption.Right + " BID: " + thisOption.BidPrice + " ASK: " + thisOption.AskPrice);
k++;
}
//Debug(" ---------------------------------------------------------------------------------------------");
}
// ********************** Iterate Matrix *******************************************************
// *** Generalized function to iterate through and print members of an IEnumerable of Contracts
// *** This is used for debugging only
// ********************************************************************************************
public void IterateSSQRMatrix(List<SSQRColumn> thisMatrix)
{
int k = 1;
SSQRColumn thisColumn;
var matrixEnum = thisMatrix.GetEnumerator();
Debug(" |||||||||||||||||||||||||||||||| NEW OPTION SSQRMatrix |||||||||||||||||||||||||||||||");
Debug("There are " + thisMatrix.Count() + " columns in this SSQRMatrix.");
// 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
Debug(",Ticker,Stock Price,Ex-Date,# Dividends,Dividend,Dollars,Days In,Interest,PExpiry, CExpiry, PutStrike,PutASK,CallStrike,CallBid, atmStrike, atmCallAsk, PutDelta, CallDelta, NetOptions,Net Income,Haircut,ROC,Upside,Downside,ROR,CCOR, wingFactor, PutSymb, CallSymb");
while (matrixEnum.MoveNext())
{
thisColumn = matrixEnum.Current;
//Debug("Iterated " + k + " times");
Debug(thisColumn.description2);
k++;
}
Debug(" ---------------------------------------------------------------------------------------------");
}
// ********************** Iterate Ordered Matrix ***********************************************
// *** Generalized function to iterate through and print members of an IEnumerable of Contracts
// *** This is used for debugging only tricky part is passing an IOrderedEnumerable into this
// ****************************************************************************************************
public void IterateOrderedSSQRMatrix(IOrderedEnumerable<SSQRColumn> thisOrdMatrix)
{
int k = 1;
Debug(" |||||||||||||||||||||||||||||||| NEW TRADABLE SSQRMatrix |||||||||||||||||||||||||||||||");
Debug("There are " + thisOrdMatrix.Count() + " columns in this SSQRMatrix.");
// 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
Debug(",Ticker,Stock Price,Ex-Date,# Dividends,Dividend,Dollars,Days In,Interest,PExpiry, CExpiry, PutStrike,PutASK,CallStrike,CallBid, atmStrike, atmCallAsk, PutDelta, CallDelta, NetOptions,Net Income,Haircut,ROC,Upside,Downside,ROR,CCOR, wingFactor, PutSymb, CallSymb");
foreach (SSQRColumn thisColumn in thisOrdMatrix)
{
//Debug("Iterated " + k + " times");
Debug(thisColumn.description2);
//Debug(" ");
k++;
if (k == 21) break;
}
}
// ********************** Iterate Ordered PutSpread **********************************************
// *** Generalized function to iterate through and print members of an IEnumerable of PutSpreads
// *** This is used for debugging only tricky part is passing an IOrderedEnumerable into this
// ****************************************************************************************************
public void IterateOrderedPutSpreadList(IOrderedEnumerable<PutSpread> thisOrdSpreads)
{
string logLine = ""; // for writing the logs
int k = 1;
Debug(" |||||||||||||||||||||||||||||||| NEW TRADABLE PutSpreads List |||||||||||||||||||||||||||||||");
Debug(",¶¶,There are " + thisOrdSpreads.Count() + " PutSpreads in this List.");
// 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
//Debug("¶¶,Stock Price, Ex-Date, Trade Date, pExpiry, oldPutSymb, newPutSymb, oldBid, newAsk, oldStrike, newStrike, Open Interst, Div Amt, # Dividends, Div Dollars, stock Incr,Interest,DownSide, Upside, Net Income, NetOptions, Haircut, Descr
logLine = ",¶¶";
foreach (PutSpread thisSpread in thisOrdSpreads)
{
if (k==1){ // iterate field names
foreach (var fieldN in typeof(PutSpread).GetFields())
{
logLine = logLine + "," + fieldN.Name;
}
Debug(logLine);
logLine = ",¶¶";
//k = k + 1;
}
foreach (var fieldV in typeof(PutSpread).GetFields())
{
if (fieldV.GetType() == typeof(decimal)) {
logLine = logLine + "," + String.Format("{0:0.00}", fieldV.GetValue(thisSpread));
}
else if (fieldV.GetType() == typeof(DateTime)) {
logLine = logLine + "," + String.Format("{0:MM/dd/yy H:mm:ss}", fieldV.GetValue(thisSpread));
}
else logLine = logLine + "," + fieldV.GetValue(thisSpread);
}
Debug(logLine);
logLine = ",¶¶";
//Debug("Iterated " + k + " times");
//Debug(thisSpread.description1);
//Debug(" ");
k++;
//if (k == 11) break;
}
}
}
}using QuantConnect.Securities.Option;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
namespace QuantConnect.Algorithm.CSharp
{
public partial class CollarAlgorithm : QCAlgorithm
{
private bool goodThresh2 = false;
////////////////////////////////////////////////////////////////////////////////////
//
// ExecuteTrade
//
////////////////////////////////////////////////////////////////////////////////////
public void ExecuteTrade(Slice data, SSQRColumn bestSSQRColumn)
{
thisCCOR = bestSSQRColumn.CCOR;
decimal maxWingFactor = 0;
decimal thisWingFactor = 0;
decimal wingPremium = 0;
decimal thisNetOptions = bestSSQRColumn.netOptions;
if (haltProcessing)
{
Debug(" Logging ExecuteTheTrade() ");
}
//goodThresh = (thisCCOR >= CCORThresh);
goodThresh = true;
if (goodThresh)
{
//sharesToBuy = Math.Round(stockDollarValue/stockPrice/100, 0) * 100; // set in top of OnData()
optionsToTrade = sharesToBuy/100;
//callsToTrade = Decimal.Round(optionsToTrade * bestSSQRColumn.putPremium / bestSSQRColumn.callPremium); /// legacy VCCPTS code
//Debug(tradableColumn.ToString());
Symbol tradablePut = bestSSQRColumn.putSymbol;
Symbol tradableCall = bestSSQRColumn.callSymbol;
Symbol tradableWCall = bestSSQRColumn.wCallSymbol;
if (Securities[tradableCall].AskPrice + bestSSQRColumn.callStrike < stockPrice) // make sure that no one can buy the option for less than the stock
{
Debug($" @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ EXERCISE PREVENTION FADE FOR {bestSSQRColumn.uSymbol} @@@@@@@@@@@@");
Debug(" @@@@@@@@@@@@@@@@@@@ CALL ASK: " + Securities[tradableCall].AskPrice + " Strike: " + bestSSQRColumn.callStrike + " Stock Price: " + stockPrice +" @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
Debug(" @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
return;
}
tradeRecCount = tradeRecCount + 1; // increment trade record count
collarIndex = collarIndex + 1;
doTheTrade = true;
var stockTicket = MarketOrder(bestSSQRColumn.uSymbol, sharesToBuy);
if (stockTicket.Status == OrderStatus.Filled)
{
didTheTrade = true;
if (symbFilter != null) Plot("Stock Chart", "Buys", stockTicket.AverageFillPrice + 5);
// make a new TradePerfRec
TradePerfRec thisNewCollar = new TradePerfRec();
thisNewCollar.strtngCndtn = "INITIAL COLLAR";
thisNewCollar.isOpen = true;
thisNewCollar.isInitializer = true;
thisNewCollar.tradeRecCount = tradeRecCount;
thisNewCollar.index = collarIndex;
thisNewCollar.startDate = data.Time;
thisNewCollar.expDate = bestSSQRColumn.putExpiry;
thisNewCollar.thetaExpiration = bestSSQRColumn.callExpiry;
thisNewCollar.uSymbol = bestSSQRColumn.uSymbol;
thisNewCollar.cSymbol = tradableCall;
thisNewCollar.pSymbol = tradablePut;
thisNewCollar.wcSymbol = tradableWCall;
thisNewCollar.uStartPrice = stockTicket.AverageFillPrice;
thisNewCollar.pStrike = bestSSQRColumn.putStrike;
thisNewCollar.cStrike = bestSSQRColumn.callStrike;
thisNewCollar.wcStrike = bestSSQRColumn.wCallStrike;
thisNewCollar.uQty = (int)stockTicket.QuantityFilled;
thisNewCollar.ROR = thisROR;
thisNewCollar.ROC = thisROC;
thisNewCollar.CCOR = thisCCOR;
thisNewCollar.RORThresh = RORThresh;
thisNewCollar.ROCThresh = ROCThresh;
thisNewCollar.CCORThresh = CCORThresh;
//thisNewCollar.tradeCriteria = switchROC ? "ROC" : "ROR";
thisNewCollar.tradeCriteria = "Wing";
thisNewCollar.stockADX = lastAdx;
thisNewCollar.stockADXR = lastAdxr;
thisNewCollar.stockOBV = lastObv;
//thisNewCollar.stockAD = lastAd;
//thisNewCollar.stockADOSC = lastAdOsc;
//thisNewCollar.stockSTO = lastSto;
thisNewCollar.stockVariance = lastVariance;
thisNewCollar.SSQRnetProfit = stockTicket.QuantityFilled * bestSSQRColumn.netIncome;
//Option logCorrespondingPut = AddCorrespondingPut(tradableCall, ref symbolDataBySymbol[bestSSQRColumn.uSymbol].currentOptions); // Add the corresponding put here so system tracks its price for Ex-dividend approachment
//logCorrespondingPut = AddCorrespondingPut(bestSSQRColumn.wCallSymbol, ref symbolDataBySymbol[bestSSQRColumn.uSymbol].currentOptions); // Add the wing call corresponding put here so system tracks its price for Ex-Dividend approachment
doTheTrade = true;
if (thisNewCollar.cStrike < thisNewCollar.uStartPrice) {
var limitPrice = (Securities[tradableCall].AskPrice - Securities[tradableCall].BidPrice) / 2M; // get the mid point for the limit price
var callTicket = LimitOrder(tradableCall, -optionsToTrade, limitPrice); // sell limit order
thisNewCollar.cQty = -(int)optionsToTrade;
OpenLimitOrder oLO = new OpenLimitOrder();
oLO.oTicket = callTicket;
oLO.tpr = thisNewCollar;
oLO.oRight = OptionRight.Call;
oLOs.Add(oLO);
//if (closePutTicket.Status == OrderStatus.Submitted) oldTradeRec.pEndPrice = limitPrice;
} else {
var callTicket = MarketOrder(tradableCall, -optionsToTrade);
if (callTicket.Status == OrderStatus.Filled)
{
thisNewCollar.cStartPrice = callTicket.AverageFillPrice;
thisNewCollar.cQty = (int)callTicket.QuantityFilled;
}
}
thisWingFactor = bestSSQRColumn.wingFactor;
var putTicket = MarketOrder(tradablePut, (1 + thisWingFactor) * optionsToTrade);
if (putTicket.Status == OrderStatus.Filled)
{
thisNewCollar.pStartPrice = putTicket.AverageFillPrice;
thisNewCollar.pQty = (int)putTicket.QuantityFilled;
}
if (thisWingFactor > 0) {
var wCallTicket = MarketOrder(tradableWCall, thisWingFactor * optionsToTrade);
if (wCallTicket.Status == OrderStatus.Filled) {
thisNewCollar.wcStartPrice = wCallTicket.AverageFillPrice;
thisNewCollar.wcQty = (int)wCallTicket.QuantityFilled;
}
}
doTheTrade = true;
tradeRecs.Add(thisNewCollar);
Debug("-");
} // marketOrder(bestSSQRColumn.uSymbol) == filled
} // goodThresh is TRUE
return;
}
///////////////////////////////////////////////////////////////////////////////////
// Close2ndTPR
////////////////////////////////////////////////////////////////////////////////////
public void Close2ndTPR (TradePerfRec closeRec, DateTime closeDate, string reason)
{
decimal limitPrice = 0;
if (haltProcessing)
{
//Debug(" Logging Close2ndTPR ");
}
doTheTrade = true;
var stockTicket = MarketOrder(closeRec.uSymbol, -closeRec.uQty); // sell the stock
Debug(" C2 ** MARKET ORDER TO SELL " + closeRec.uQty.ToString() + " shares of " + closeRec.uSymbol + " at the market.");
if (doTracing) Debug(" C2 ** C2 ** STARTING CLOSE2ndTPR PROCESSING ** C2 ** C2 ");
if (doTracing) Debug(" -- ");
if (doTracing) {
foreach(var kvp in Securities) /// make sure there's no leaking of abandoned stocks or options
{
var security = kvp.Value;
if (security.Invested)
{
//saveString = "," + security.Symbol + ", " + security.Holdings.Quantity + Environment.NewLine;
Debug($" |||| HOLDINGS: {security.Symbol} : {security.Holdings.Quantity} @ {security.BidPrice} by {security.AskPrice}");
}
}
}
if (stockTicket.Status == OrderStatus.Filled)
{
//closeRec.isOpen = false;
tprsToClose.Add(closeRec);
closeRec.uEndPrice = stockTicket.AverageFillPrice;
if (symbFilter != null) Plot("Stock Chart", "Sells", stockTicket.AverageFillPrice + 1);
if (symbFilter != null) Plot("Stock Chart", "PTSs", divPlotValue);
tradeRecCount = 0; // reset trade record count
}
doTheTrade = true;
Debug(" C2 ** C2 ** C2 ** C2 ** KILLING 2nd TPR ** C2 ** C2 ** C2 ** C2 ** C2 ** ");
//Debug(" C2 ** Stock Price: " + stockPrice.ToString() + " Call Bid/Offer: " + closeRec.cSymbol.BidPrice.ToString() + "/" + closeRec.cSymbol.AskPrice.ToString());
if (closeRec.pStrike >= stockPrice) /// ITM Put -- use limit order
{
limitPrice = closeRec.pStrike - stockPrice + 0.10M;
closePutTicket = LimitOrder(closeRec.pSymbol, -closeRec.pQty, limitPrice); // sell the puts
OpenLimitOrder oLO = new OpenLimitOrder();
oLO.oTicket = closePutTicket;
oLO.tpr = closeRec;
oLO.oRight = OptionRight.Put;
oLOs.Add(oLO);
Debug(" C2 ** LIMIT ORDER TO SELL " + closeRec.pQty.ToString() + " contracts of " + closeRec.pSymbol + " at " + limitPrice.ToString());
Debug("-");
} else {
closePutTicket = MarketOrder(closeRec.pSymbol, -closeRec.pQty); // sell the puts
Debug(" C2 ** MARKET ORDER TO SELL " + closeRec.pQty.ToString() + " contracts of " + closeRec.pSymbol + " at the market." );
Debug("-");
}
if (closePutTicket.Status == OrderStatus.Filled)
{
closeRec.pEndPrice = closePutTicket.AverageFillPrice;
}
closeRec.reasonForClose = reason;
closeRec.endDate = closeDate; // set the end date of this collar
Debug(" C2 ** C2 ** C2 ** C2 ** CLOSED 2nd TPR ** C2 ** C2 ** C2 ** C2 ** C2 ** ");
Debug("-");
}
///////////////////////////////////////////////////////////////////////////////////
// KillTheCollar
////////////////////////////////////////////////////////////////////////////////////
public bool KillTheCollar(TradePerfRec killRec, ref LookupData LUD, string reason)
{
bool bKTC = false; // controls Main.cs foreach TPR routine -- exit the for loop if .isOpen is changed.
decimal limitPrice = 0;
decimal currUPrice = Securities[killRec.uSymbol].Price;
decimal currPPrice = killRec.pSymbol != null ? Securities[killRec.pSymbol].BidPrice : 0;
decimal currCPrice = killRec.cSymbol != null ? Securities[killRec.cSymbol].AskPrice : 0;
decimal currWCPrice = killRec.wcSymbol != null ? Securities[killRec.wcSymbol].BidPrice : 0;
decimal stockPrice = Securities[killRec.uSymbol].Price;
//decimal sellPnL = 0;
//decimal exrcsPnL = 0;
if (doTracing) Debug($" KK ** KK ** STARTING KILLTHECOLLAR PROCESSING FOR {thisSymbol} ** KK ** KK ");
if (doTracing) Debug(" -- ");
if (doTracing) {
foreach(var kvp in Securities) /// make sure there's no leaking of abandoned stocks or options
{
var security = kvp.Value;
if (security.Invested)
{
//saveString = "," + security.Symbol + ", " + security.Holdings.Quantity + Environment.NewLine;
Debug($" |||| HOLDINGS: {security.Symbol} : {security.Holdings.Quantity} @ {security.BidPrice} by {security.AskPrice}");
}
}
Debug($" |||| SELL OPTS P&L: " + String.Format("{0:0.00}", currSellPnL));
Debug($" |||| Exrcs PUT P&L: " + String.Format("{0:0.00}", currExrcsPutPnL));
Debug($" |||| Exrcs CALL P&L: " + String.Format("{0:0.00}", currExrcsCallPnL));
}
if (haltProcessing)
{
Debug(" Logging KILLTHECOLLAR ");
}
doTheTrade = true;
// determine if this is an ITM call or ITM put and within 1 day of expiry
if (killRec.pSymbol != null && stockPrice <= putStrike && LUD.daysRemainingP <= 1) {
// determine if it's more expensive to sell or exercise ***** remember, killRec.cQty is negative for collars (sold calls)
if (killRec.currExrcsPutPnL > killRec.currSellPnL) { // for an ITM PUT, both costs should be negative
if (doTracing) Debug($" KK ** KK ** EXERCISING PUTS AND CALLS THETA IN KILLTHECOLLAR FOR {thisSymbol} ** KK ** KK ");
if (killRec.cSymbol != null) { // Exercise the PUTs. Let longer expiry calls ride to attempt theta decay
//var shrtCall = (Option)Securities[killRec.cSymbol];
//TimeSpan daysToCallExpiry = shrtCall.Expiry.Subtract(killDate);
/*if (daysToCallExpiry.Days > 10 ) {
Debug(" OO CALL " + shrtCall + " EXPIRES IN " + daysToCallExpiry.Days + "DAYS. CREATING THETA TPR.");
// create a thetaTPR to move the call data and track it. Buy it back when theta decays.
TradePerfRec newThTPR = new TradePerfRec();
newThTPR.uSymbol = killRec.uSymbol;
newThTPR.index = killRec.index;
newThTPR.isOpen = true;
newThTPR.isInitializer = true;
newThTPR.isSecondary =false;
newThTPR.isTheta = true;
newThTPR.startDate = killRec.startDate;
newThTPR.strtngCndtn = "SPINNING OFF THETA CALLS";
newThTPR.expDate = shrtCall.Expiry;
newThTPR.cSymbol = killRec.cSymbol;
newThTPR.cStrike = killRec.cStrike;
newThTPR.cQty = killRec.cQty;
newThTPR.cStartPrice = killRec.cStartPrice;
newThTPR.tradeCriteria = killRec.tradeCriteria;
tradeRecs.Add(newThTPR);
killRec.cSymbol = null; // eliminate the call from the existint TPR
killRec.cStartPrice = 0;
killRec.cQty = 0;
} else { */
if (doTracing) Debug(" KK ** KK ** BUYING BACK SHORT CALLS IN KILLTHECOLLAR ** KK ** KK ");
closeCallTicket = MarketOrder(killRec.cSymbol, -killRec.cQty); // buy the calls
Debug(" KK ** MARKET ORDER TO BUY " + killRec.cQty.ToString() + " contracts of " + killRec.cSymbol + " at the market.");
Debug("-");
if (closeCallTicket.Status == OrderStatus.Filled)
{
killRec.cEndPrice = closeCallTicket.AverageFillPrice;
}
}
if (doTracing) Debug(" ------- ");
if (doTracing) Debug(" KK ** KK ** EXERCISING PUTS IN KILLTHECOLLAR ** KK ** KK ");
closePutTicket = ExerciseOption(killRec.pSymbol, killRec.pQty); /// underlying and calls will be closed in onOrder() event
killRec.grossPnL = currExrcsPutPnL; /// log the PnL used in runtime decision
//potentialCollars.Clear();
bestSSQRColumn = new SSQRColumn();
bKTC = true;
return bKTC;
}
if (doTracing) Debug(" KK ** KK ** CLOSE POSITIONS IN KILLTHECOLLAR ** KK ** TT ");
goto noExercise;
}
if (killRec.cSymbol != null && stockPrice >= callStrike && LUD.daysRemainingC <= 1) {
if (doTracing) Debug(" KK ** KK ** EXERCISING CALLS AND SELLING BACK PUTS IN KILLTHECOLLAR ** KK ** TT ");
if (currExrcsCallPnL > currSellPnL) { // for an ITM CALL, both costs should be positive
if (doTracing) Debug(" KK ** KK ** EXIT KILLTHECOLLAR AND AWAIT CALL EXERCISE** KK ** TT ");
killRec.grossPnL = currExrcsCallPnL; // log the PnL used in runtime decision
return bKTC; // get out of the OnData() and await LEAN-driven call exercise
}
if (doTracing) Debug(" KK ** KK ** CLOSING POSITIONS IN KILLTHECOLLAR ** KK ** TT ");
}
noExercise:
//if OTM or it's less costly to execute orders, then do so here.
var stockTicket = MarketOrder(killRec.uSymbol, -killRec.uQty); // sell the stock
Debug(" KK ** MARKET ORDER TO SELL " + killRec.uQty.ToString() + " shares of " + killRec.uSymbol + " at the market."); // Log the sale
if (stockTicket.Status == OrderStatus.Filled)
{
Debug(" KK ** KK ** UPDATING U END PRICE ** KK ** KK"); // Log the UPDATING
//killRec.isOpen = false; /// add the killTPR to TPRS to close;
tprsToClose.Add(killRec);
killRec.uEndPrice = stockTicket.AverageFillPrice;
if (symbFilter != null) Plot("Stock Chart", "Sells", stockTicket.AverageFillPrice + 1);
tradeRecCount = 0; // reset trade record count
}
doTheTrade = true;
Debug(" KK ** KK ** KK ** KK ** KILLING COLLAR ** KK ** KK ** KK ** KK ** KK ** ");
//Debug(" KK ** Stock Price: " + stockPrice.ToString() + " Call Bid/Offer: " + killRec.cSymbol.BidPrice.ToString() + "/" + killRec.cSymbol.AskPrice.ToString());
if (killRec.cSymbol != null) { // Exercise the PUTs. Buy back any calls if possible
var shrtCall = (Option)Securities[killRec.cSymbol];
TimeSpan daysToCallExpiry = shrtCall.Expiry.Subtract(LUD.dtTst);
/*if (daysToCallExpiry.Days > 10 ) {
Debug(" OO CALL " + shrtCall + " EXPIRES IN " + daysToCallExpiry.Days + ". CREATING THETA TPR.");
// create a thetaTPR to move the call data and track it. Buy it back when theta decays.
TradePerfRec newThTPR = new TradePerfRec();
newThTPR.uSymbol = killRec.uSymbol;
newThTPR.index = killRec.index;
newThTPR.isOpen = true;
newThTPR.isInitializer = true;
newThTPR.isSecondary = true;
newThTPR.isTheta = true;
newThTPR.startDate = killRec.startDate;
newThTPR.strtngCndtn = "SPINNING OFF THETA CALLS";
newThTPR.expDate = shrtCall.Expiry;
newThTPR.cSymbol = killRec.cSymbol;
newThTPR.cQty = killRec.cQty;
newThTPR.cStartPrice = killRec.cStartPrice;
newThTPR.tradeCriteria = killRec.tradeCriteria;
tradeRecs.Add(newThTPR);
killRec.cSymbol = null; // eliminate the call from the existint TPR
killRec.cStartPrice = 0;
killRec.cQty = 0;
} else */
if (killRec.cStrike <= stockPrice) { /// ITM Call -- use limit order
limitPrice = stockPrice - killRec.cStrike + 0.10M;
closeCallTicket = LimitOrder(killRec.cSymbol, -killRec.cQty, limitPrice);
OpenLimitOrder oLO = new OpenLimitOrder();
oLO.oTicket = closeCallTicket;
oLO.tpr = killRec;
oLO.oRight = OptionRight.Call;
oLOs.Add(oLO);
Debug(" KK ** LIMIT ORDER TO BUY TO CLOSE SHORT CALL " + killRec.cQty.ToString() + " contracts of " + killRec.cSymbol + " at " + limitPrice.ToString());
} else {
closeCallTicket = MarketOrder(killRec.cSymbol, -killRec.cQty); // buy the calls
Debug(" KK ** MARKET ORDER TO BUY TO CLOSE SHORT CALL" + killRec.cQty.ToString() + " contracts of " + killRec.cSymbol + " at the market.");
if (closeCallTicket.Status == OrderStatus.Filled)
{
killRec.cEndPrice = closeCallTicket.AverageFillPrice;
}
}
}
Debug("---------------------------------------");
if (killRec.pStrike >= stockPrice) /// ITM Put -- use limit order
{
limitPrice = killRec.pStrike - stockPrice + 0.10M;
closePutTicket = LimitOrder(killRec.pSymbol, -killRec.pQty, limitPrice); // sell the puts
OpenLimitOrder oLO = new OpenLimitOrder();
oLO.oTicket = closePutTicket;
oLO.tpr = killRec;
oLO.oRight = OptionRight.Put;
oLOs.Add(oLO);
Debug(" KK ** LIMIT ORDER TO SELL TO CLOSE " + killRec.pQty.ToString() + " contracts of " + killRec.pSymbol + " at " + limitPrice.ToString());
Debug("-");
} else {
closePutTicket = MarketOrder(killRec.pSymbol, -killRec.pQty); // sell the puts
Debug(" KK ** MARKET ORDER TO SELL TO CLOSE " + killRec.pQty.ToString() + " contracts of " + killRec.pSymbol + " at the market." );
Debug("-");
}
if (closePutTicket.Status == OrderStatus.Filled)
{
killRec.pEndPrice = closePutTicket.AverageFillPrice;
Debug(" KK ** UPDATING PUT PRICE TO " + killRec.pEndPrice + " ** KK ** KK");
}
if (killRec.wcSymbol != null && killRec.wcQty != 0 && killRec.wcEndPrice == 0) {
if (killRec.wcStrike < stockPrice) /// ITM Put -- use limit order
{
limitPrice = stockPrice - killRec.wcStrike + 0.10M;
Debug(" KK ** LIMIT ORDER TO SELL TO CLOSE WING " + killRec.wcQty.ToString() + " contracts of " + killRec.wcSymbol + " at " + limitPrice.ToString());
closeWCallTicket = LimitOrder(killRec.wcSymbol, -killRec.wcQty, limitPrice); // sell the puts
OpenLimitOrder oLO = new OpenLimitOrder();
oLO.oTicket = closeWCallTicket;
oLO.tpr = killRec;
oLO.oRight = OptionRight.Call;
oLO.isWingCall = true;
oLOs.Add(oLO);
Debug("-");
} else {
closeWCallTicket = MarketOrder(killRec.wcSymbol, -killRec.wcQty); // sell the puts
Debug(" KK ** LIMIT ORDER TO SELL TO CLOSE WING " + killRec.wcQty.ToString() + " contracts of " + killRec.wcSymbol + " at " + limitPrice.ToString());
Debug("-");
}
if (closeWCallTicket.Status == OrderStatus.Filled)
{
killRec.wcEndPrice = closePutTicket.AverageFillPrice;
Debug(" KK ** UPDATING WING END PRICE TO " + killRec.wcEndPrice + " ** KK ** KK");
}
}
killRec.reasonForClose = reason;
killRec.endDate = LUD.dtTst; // set the end date of this collar
killRec.grossPnL = currSellPnL; // for logging and analysis of runtime conditions
Debug("-");
return bKTC;
}
///////////////////////////////////////////////////////////////////////////////////
// RollPut
////////////////////////////////////////////////////////////////////////////////////
/*
public void RollPut(Slice slcData, DateTime nExDvDt, TradePerfRec oldTPR, IEnumerable <Symbol> undrOptsSymbols, decimal sPrice, decimal incrAmt, string reason, bool forceAction){
int rollQty = 0; // change in qty, difference between total stock and covered stock = uncovered stock == amount to roll up.
int findYear = slcData.Time.Year;
int findMonth = slcData.Time.Month;
PutSpread bestPutSpread;
OrderTicket closePutTicket; // used to close the open puts
OrderTicket openPutTicket; // used to open (roll up) new puts
if (haltProcessing) {
Debug(" RP ** RP ** RP ** Logging ROLLPUT RR ** RR ** RR **");
}
if (doTracing) Debug(" RP ** RP ** STARTING ROLL2NDPUT PROCESSING ** RP ** RP ");
if (doTracing) Debug(" -- ");
if (doTracing) {
foreach(var kvp in Securities) /// make sure there's no leaking of abandoned stocks or options
{
var security = kvp.Value;
if (security.Invested)
{
//saveString = "," + security.Symbol + ", " + security.Holdings.Quantity + Environment.NewLine;
Debug($" |||| HOLDINGS: {security.Symbol} : {security.Holdings.Quantity} @ {security.BidPrice} by {security.AskPrice}");
}
}
Debug($" |||| SELL OPTS P&L: " + String.Format("{0:0.00}", currSellPnL));
Debug($" |||| Exrcs PUT P&L: " + String.Format("{0:0.00}", currExrcsPutPnL));
Debug($" |||| Exrcs CALL P&L: " + String.Format("{0:0.00}", currExrcsCallPnL));
}
// Compute the 3rd Friday of this month [options expiration] ---> do not adjust for potential holiday here
DateTime thisMonthExpiry = FindDay(findYear, findMonth, DayOfWeek.Friday, 3);
// Use the 3rd Friday of the current month to seed the function to return the next 4 ex-dividends expiries adjusted for holidays
Dictionary<int, DateTime> expiries = GetOptionExpiries(slcData.Time, nExDvDt, thisMonthExpiry, false); /// final parameter, bool, isPrimary = true ? 1stTPR : 2ndTPR
List<PutSpread> pSpreads = AssemblePutSpreads(slcData, expiries, oldTPR, undrOptsSymbols, sPrice, incrAmt);
if (pSpreads == null | pSpreads.Count() == 0) {
if (doTracing) Debug(" RP RP RP RP FAILED ROLLPUT -- NO PSPREADS");
if (doTracing) Debug(" - ");
return bKTC; // loop around and try again
}
bestPutSpread = GetBestPutSpread(pSpreads);
if (bestPutSpread == null) {
// if (haltProcessing) { /// 2021-02-17 removed this
//if (doTracing) Debug(" Logging ROLLPUT --NULL BESTPUTSPREAD -- ITERATE");
if (doTracing) Debug(" RP 2nd TPR PROCESSING CANNOT ROLL " + thisSymbol.ToString() + " CANNOT GET bestPutSpread -- FORCE PUT EXERCISE OOOOOOOOOOO"); // EXERCISE THE PUT removing PUTs and STOCK. Buy back calls in OnOrder()
if (doTracing) Debug(" RP FORCE PUT EXERCISE OR CLOSE ON PUT: " + secondLongPutSymbol + " -- OOOOOOOOOOO OOOOOOOO OOOOOOOOOOO"); // EXERCISE THE PUT removing PUTs and STOCK. Buy back calls in OnOrder()
if (doTracing){
var orderedPSpreads = pSpreads.Where(s => s.netIncome + s.netOptions > 0 ).OrderByDescending( s => (s.netIncome + s.netOptions)/Math.Abs(s.stockPrice - s.newPutStrike));
//var orderedPSpreads = pSpreads.OrderByDescending(s=>s.netIncome + s.netOptions);
IterateOrderedPutSpreadList(orderedPSpreads);
}
if (oldTPR.isSecondary) { // close secondary tickets only
if (oldTPR.pStrike > sPrice & forceAction) {
oldTPR.reasonForClose = "FAILED TO OBTAIN PUT ROLL SPREAD";
var putExerciseTicket = ExerciseOption(oldTPR.pSymbol, oldTPR.pQty);
} else if (oldTPR.pStrike < sPrice & forceAction) {
Close2ndTPR(oldTPR, slcData.Time, " CLOSING 2nd TPR at Expiration with stock @: " + String.Format("{0:C2}", sPrice));
}
if (doTracing) Debug(" ************** END 2nd TPR ITM PUT CALC ****************");
if (doTracing) Debug("-");
}
if (symbFilter != null) Plot("Stock Chart", "PTSs", divPlotValue);
return bKTC; // loop around and try again
}
if (doTracing){
var orderedPSpreads = pSpreads.OrderByDescending(s=>s.netIncome + s.netOptions);
IterateOrderedPutSpreadList(orderedPSpreads);
}
/// Roll up the collar
if (!oldTPR.isSecondary && oldTPR.pQty > oldTPR.cQty) {
rollQty = oldTPR.pQty + oldTPR.cQty; // call Qty is stored as negative value. this is equivalent: abs(p)-abs(c)
Debug(" RP ** RP ** RP ** RP ** ROLLING UP PUTS ** RP ** RP ** RP ** RP ** RP ** ");
doTheTrade = true;
Debug(" RP ** MARKET ORDER TO SELL " + rollQty + " contracts of " + oldTPR.pSymbol + " at market");
closePutTicket = MarketOrder(oldTPR.pSymbol, -rollQty); // sell the puts
Debug(" RP ** MARKET ORDER TO BUY " + rollQty + " contracts of " + bestPutSpread.newPutSymb + " at market");
openPutTicket = MarketOrder(bestPutSpread.newPutSymb, rollQty); // buy the higher puts
// first adjust the old tradePerfRec to decrement pQty and uQty. It remains open to be processed for the remaining covered, collared stock.
oldTPR.pQty = oldTPR.pQty - rollQty; // decrement oldTPR to fully covered collar. Leave it open for future roll processing
oldTPR.uQty = oldTPR.uQty - (100 * rollQty);
TradePerfRec newTPR1 = new TradePerfRec(); // create a tradePerfRec #1 for the puts sold, solely to log their P/L (including underlying unrealized P/L).
TradePerfRec newTPR2 = new TradePerfRec(); // create a TradePerfRec #2 for the new Synthetic Call (stock-covered puts)
newTPR1.uSymbol = newTPR2.uSymbol = oldTPR.uSymbol; // newTPR1 for the uncovered synthetic call (put + stock) portion of the original collar
newTPR1.index = newTPR2.index = oldTPR.index; // maintain collarIndex throughout the entire sequence of collars and synthCalls
newTPR1.uQty = rollQty * 100; // log the starting and ending values and close the TradePerfRec
newTPR1.uStartPrice = oldTPR.uStartPrice;
newTPR1.uEndPrice = sPrice;
newTPR1.pSymbol = oldTPR.pSymbol;
newTPR1.pStrike = oldTPR.pStrike;
newTPR1.expDate = oldTPR.expDate;
newTPR1.pQty = rollQty;
newTPR1.pStartPrice = oldTPR.pStartPrice;
newTPR1.startDate = oldTPR.startDate;
newTPR1.endDate = slcData.Time;
newTPR1.isOpen = false;
newTPR1.isInitializer = false;
newTPR1.isSecondary = true;
newTPR1.numDividends = oldTPR.numDividends;
newTPR1.divIncome = oldTPR.divIncome;
newTPR1.tradeRecCount = oldTPR.tradeRecCount;
newTPR1.ROR = oldTPR.ROR;
newTPR1.ROC = oldTPR.ROC;
newTPR1.CCOR = oldTPR.CCOR;
newTPR1.tradeCriteria = oldTPR.tradeCriteria;
newTPR1.strtngCndtn = "OLD SYNTH CALL -- MAIN COLLAR SPLIT ON APPRECIATION";
newTPR1.reasonForClose = "P ROLL OLD FRAGMENT SPLIT-SOLD PUTS SPrice @ " + String.Format("{0:0.00}",sPrice) + " up " + String.Format("{0:0.00}", incrAmt) ;
if (closePutTicket.Status == OrderStatus.Filled)
{
newTPR1.pEndPrice = closePutTicket.AverageFillPrice;
}
newTPR2.uQty = rollQty * 100; // newTPR2 for the new uncovered synthetic call (put + stock)
newTPR2.uStartPrice = sPrice; // log the starting values for underlying and puts.
newTPR2.pSymbol = bestPutSpread.newPutSymb;
newTPR2.pStrike = bestPutSpread.newPutStrike;
newTPR2.pQty = rollQty;
newTPR2.expDate = bestPutSpread.putExpiry;
newTPR2.startDate = slcData.Time;
newTPR2.isOpen = true;
newTPR2.isInitializer = true; // mark the first synthCall TPR as initializer
newTPR2.isSecondary = true;
//newTPR2.
newTPR2.tradeRecCount = 1;
newTPR2.ROR = oldTPR.ROR;
newTPR2.ROC = oldTPR.ROC;
newTPR2.CCOR = oldTPR.CCOR;
newTPR2.tradeCriteria = oldTPR.tradeCriteria;
newTPR2.strtngCndtn = "NEW SYNTH CALL -- COLLAR SPLIT ON APPRECIATION";
if (openPutTicket.Status == OrderStatus.Filled)
{
newTPR2.pStartPrice = openPutTicket.AverageFillPrice;
}
tradeRecs.Add(newTPR1);
tradeRecs.Add(newTPR2);
if (symbFilter != null) Plot("Stock Chart", "PTSs", divPlotValue);
if (doTracing) Debug(" RP ** RP ** END OF ROLL PUT FROM PRIMARY TPR ** RP ** RP ** ");
} else if (oldTPR.isSecondary) {
//
rollQty = oldTPR.pQty; // call Qty is stored as negative value. this is equivalent: abs(p)-abs(c)
Debug(" RP ** RP ** RP ** RP ** ROLLING UP PUTS ** RP ** RP ** RP ** RP ** RP ** ");
doTheTrade = true;
Debug(" RP ** MARKET ORDER TO SELL " + rollQty + " contracts of " + oldTPR.pSymbol + " at market");
closePutTicket = MarketOrder(oldTPR.pSymbol, -rollQty); // sell the puts
Debug(" RP ** MARKET ORDER TO BUY " + rollQty + " contracts of " + bestPutSpread.newPutSymb + " at market");
openPutTicket = MarketOrder(bestPutSpread.newPutSymb, rollQty); // buy the higher puts
// first adjust the old tradePerfRec to decrement pQty and uQty. It remains open to be processed for the remaining covered, collared stock.
//oldTPR.pQty = oldTPR.pQty - rollQty; // whether this is the first secondary TPR, or a subsequent,
//oldTPR.uQty = 100M * rollQty;
TradePerfRec newTPR1 = new TradePerfRec(); // create a tradePerfRec #1 for the puts sold, solely to log their P/L.
//TradePerfRec newTPR2 = new TradePerfRec(); // create a TradePerfRec #2 for the new Synthetic Call (stock-covered puts)
foreach (var field in typeof(TradePerfRec).GetFields()) // copy oldTPR to newTPR1
{
field.SetValue(newTPR1, field.GetValue(oldTPR));
}
oldTPR.uEndPrice = sPrice;
if (closePutTicket.Status == OrderStatus.Filled)
{
oldTPR.pEndPrice = closePutTicket.AverageFillPrice;
}
oldTPR.endDate = slcData.Time;
oldTPR.isOpen = false;
oldTPR.grossPnL = closePutTicket.AverageFillPrice - oldTPR.pStartPrice;
oldTPR.reasonForClose = "P ROLLUP " + oldTPR.uSymbol + " IS " + String.Format("{0:0.00}",sPrice) + "WHICH STARTED @ " + String.Format("{0:0.00}", oldTPR.uStartPrice);
newTPR1.uStartPrice = sPrice; // set the newTPR.uPrice to 0-delta current sPrice
if (openPutTicket.Status == OrderStatus.Filled)
{
newTPR1.pStartPrice = openPutTicket.AverageFillPrice;
}
newTPR1.pSymbol = bestPutSpread.newPutSymb; // set the pSymbol to the bestPutSpread put symbol
newTPR1.pStrike = bestPutSpread.newPutStrike;
newTPR1.expDate = bestPutSpread.putExpiry;
newTPR1.startDate = slcData.Time;
newTPR1.numDividends = 0;
newTPR1.divIncome = 0;
newTPR1.isInitializer = false; // tied to 1st synthCall TPR
newTPR1.isSecondary = true;
newTPR1.tradeRecCount = oldTPR.tradeRecCount + 1; // increment this iteration of TPR
newTPR1.strtngCndtn = reason;
//newTPR1.reasonForClose = "";
//newTPR1.ROR = oldTPR.ROR;
//newTPR1.ROC = oldTPR.ROC;
//newTPR1.CCOR = oldTPR.CCOR;
//newTPR1.tradeCriteria = oldTPR.tradeCriteria;
if (symbFilter != null) Plot("Stock Chart", "PTSs", divPlotValue);
tradeRecs.Add(newTPR1);
if (doTracing) Debug(" RP ** RP ** END OF ROLL PUT FROM SECONDARY TPR ** RP ** RP ** ");
}
}
*/
///////////////////////////////////////////////////////////////////////////////////
//
// RollTheCollar
//
////////////////////////////////////////////////////////////////////////////////////
public bool RollTheCollar(CollarAlgorithm algo, ref LookupData LUD, TradePerfRec oldTradeRec, ref SSQRColumn bestSSQRColumn, string reason)
{
Slice data = algo.CurrentSlice;
decimal stockPrice = data[LUD.uSymbol].Price;
thisCCOR = bestSSQRColumn.CCOR;
decimal thisNetOptions = bestSSQRColumn.netOptions;
decimal limitPrice = 0;
decimal maxWingFactor = 0;
decimal thisWingFactor = 0;
decimal wingPremium = 0;
OrderTicket closeCallTicket;
OrderTicket closePutTicket;
OrderTicket closeWCallTicket;
if (haltProcessing)
{
Debug(" Logging ROLL ");
}
if (symbFilter != null) Plot("Stock Chart", "Rolls", stockPrice + 5);
Symbol oldShortCallSymb = oldTradeRec.cSymbol;
Symbol oldLongPutSymb = oldTradeRec.pSymbol;
Symbol oldWCCallSymb = oldTradeRec.wcSymbol;
// Cannot execute options spread orders at this time in QuantConnect, so do the collar as
// individual legs
// 1st sell the long put
Debug(" ROLLING ** STARTING ** ROLLING ** STARTING ** ROLLING ** STARTING ** ROLLING ** STARTING ** ROLLING ** STARTING ** ");
doTheTrade = true;
if (doTracing) Debug(" -- ");
if (doTracing) {
foreach(var kvp in Securities) /// make sure there's no leaking of abandoned stocks or options
{
var security = kvp.Value;
if (security.Invested)
{
//saveString = "," + security.Symbol + ", " + security.Holdings.Quantity + Environment.NewLine;
Debug($" |||| HOLDINGS: {security.Symbol} : {security.Holdings.Quantity} @ {security.BidPrice} by {security.AskPrice}");
}
}
Debug($" |||| SELL OPTS P&L: " + String.Format("{0:0.00}", currSellPnL));
Debug($" |||| Exrcs PUT P&L: " + String.Format("{0:0.00}", currExrcsPutPnL));
Debug($" |||| Exrcs CALL P&L: " + String.Format("{0:0.00}", currExrcsCallPnL));
}
if (oldTradeRec.pStrike >= stockPrice) /// ITM Put -- use limit order to close
{
limitPrice = oldTradeRec.pStrike - stockPrice + 0.10M;
Debug(" ROLLING ** LIMIT ORDER TO SELL " + oldTradeRec.pQty.ToString() + " contracts of " + oldTradeRec.pSymbol + " at " + limitPrice.ToString());
closePutTicket = LimitOrder(oldTradeRec.pSymbol, -oldTradeRec.pQty, limitPrice); // sell the puts
OpenLimitOrder oLO = new OpenLimitOrder();
oLO.oTicket = closePutTicket;
oLO.tpr = oldTradeRec;
oLO.oRight = OptionRight.Put;
oLOs.Add(oLO);
//if (closePutTicket.Status == OrderStatus.Submitted) oldTradeRec.pEndPrice = limitPrice;
} else {
Debug(" ROLLING ** MARKET ORDER TO SELL TO CLOSE " + oldTradeRec.pQty.ToString() + " contracts of " + oldTradeRec.pSymbol + " at market");
closePutTicket = MarketOrder(oldTradeRec.pSymbol, -oldTradeRec.pQty); // sell the puts
}
if (closePutTicket.Status == OrderStatus.Filled)
{
oldTradeRec.pEndPrice = closePutTicket.AverageFillPrice;
Debug(" ROLLING ** UPDATING PUT " + oldTradeRec.pSymbol + " END PRICE @ " + oldTradeRec.pEndPrice );
}
Debug("-");
// 2nd, buy back the long call
doTheTrade = true;
if (oldTradeRec.cStrike <= stockPrice) /// ITM Call -- use limit order
{ /// call QTY should be negative from the opening short trade
limitPrice = stockPrice - oldTradeRec.cStrike + 0.10M;
Debug(" ROLLING ** LIMIT ORDER TO BUY TO CLOSE " + oldTradeRec.cQty.ToString() + " contracts of " + oldTradeRec.cSymbol + " at " + limitPrice.ToString());
closeCallTicket = LimitOrder(oldTradeRec.cSymbol, -oldTradeRec.cQty, limitPrice);
//if (closeCallTicket.Status == OrderStatus.Submitted) oldTradeRec.cEndPrice = limitPrice;
OpenLimitOrder oLO = new OpenLimitOrder();
oLO.oTicket = closeCallTicket;
oLO.tpr = oldTradeRec;
oLO.oRight = OptionRight.Call;
oLOs.Add(oLO);
} else {
Debug(" ROLLING ** MARKET ORDER TO BUY TO CLOSE " + oldTradeRec.cQty.ToString() + " contracts of " + oldTradeRec.cSymbol + " at market");
closeCallTicket = MarketOrder(oldTradeRec.cSymbol, -oldTradeRec.cQty); // buy the calls
Debug(" ROLLING ** UPDATING CALL " + oldTradeRec.cSymbol + "END PRICE @ " + oldTradeRec.cEndPrice );
}
Debug("-");
if (closeCallTicket.Status == OrderStatus.Filled)
{
oldTradeRec.cEndPrice = closeCallTicket.AverageFillPrice;
Debug(" ROLLING ** UPDATING CALL END PRICE @ " + oldTradeRec.cEndPrice );
}
// 3rd, buy back the long call
doTheTrade = true;
if (oldTradeRec.wcSymbol != null && oldTradeRec.wcQty != 0 && oldTradeRec.wcEndPrice == 0) {
if (oldTradeRec.wcStrike <= stockPrice) /// ITM aCall -- use limit order
{ /// call QTY should be negative from the opening short trade
limitPrice = stockPrice - oldTradeRec.wcStrike + 0.10M;
Debug(" ROLLING ** LIMIT ORDER TO SELL TO CLOSE WING CALL " + oldTradeRec.wcQty.ToString() + " contracts of " + oldTradeRec.wcSymbol + " at " + limitPrice.ToString());
closeWCallTicket = LimitOrder(oldTradeRec.wcSymbol, -oldTradeRec.wcQty, limitPrice);
//if (closeCallTicket.Status == OrderStatus.Submitted) oldTradeRec.cEndPrice = limitPrice;
oldTradeRec.wcEndPrice = limitPrice; // set the wc Call End Price here bc finding this record in OnOrder() will be very difficult
OpenLimitOrder oLO = new OpenLimitOrder();
oLO.oTicket = closeWCallTicket;
oLO.tpr = oldTradeRec;
oLO.oRight = OptionRight.Call;
oLO.isWingCall = true;
oLOs.Add(oLO);
} else {
Debug(" ROLLING ** MARKET ORDER TO SELL TO CLOSE WING CALL " + oldTradeRec.wcQty.ToString() + " contracts of " + oldTradeRec.wcSymbol + " at market");
closeWCallTicket = MarketOrder(oldTradeRec.wcSymbol, -oldTradeRec.wcQty); // buy the calls
}
Debug("-");
if (closeCallTicket.Status == OrderStatus.Filled)
{
oldTradeRec.wcEndPrice = closeWCallTicket.AverageFillPrice;
Debug(" ROLLING ** UPDATING WING CALL " + oldTradeRec.wcSymbol + "END PRICE @ " + oldTradeRec.wcEndPrice );
}
}
// Keep the stock, but close this trade performance record.
Debug(" ROLLING ** ROLLING ** ROLLING ** ROLLING ** ROLLING ** SELL NEW COLLAR ** ROLLING ** ROLLING ** ROLLING ** ROLLING ** ROLLING ** ");
oldTradeRec.uEndPrice = stockPrice;
oldTradeRec.reasonForClose = reason;
//oldTradeRec.isOpen = false;
oldTradeRec.endDate = data.Time;
oldTradeRec.grossPnL = currSellPnL; // rolling essentially sells the existing options. Log the currSellPnL for analysis purposes
oldTradeRec.SSQRnetProfit = oldTradeRec.uQty*bestSSQRColumn.netIncome; // log the best SSQRColumn.netIncome for tracking purposes
// Put on a new collar and start a new trade performance record
// make a new TradePerfRec
tradeRecCount = oldTradeRec.tradeRecCount + 1; // increment trade record count
TradePerfRec thisNewTPRec = new TradePerfRec();
thisNewTPRec.uSymbol = thisSymbol; // keep the underlying symbol
thisNewTPRec.cSymbol = bestSSQRColumn.callSymbol;
thisNewTPRec.pSymbol = bestSSQRColumn.putSymbol;
thisNewTPRec.wcSymbol = bestSSQRColumn.wCallSymbol;
thisNewTPRec.uStartPrice = stockPrice; // log the current slice stock price
thisNewTPRec.uQty = oldTradeRec.uQty; // maintain the same quantity
//thisNewTPRec.isOpen = true; // this new trade performance record is open
thisNewTPRec.isInitializer = false; // this is a continuation Collar
thisNewTPRec.strtngCndtn = "MAIN COLLAR ROLL / " + reason;
thisNewTPRec.index = oldTradeRec.index; // maintain the collarIndex through the entire sequence of collars
thisNewTPRec.tradeRecCount = tradeRecCount; // count the trades
thisNewTPRec.startDate = data.Time; // set the start date
thisNewTPRec.pStrike = bestSSQRColumn.putStrike;
thisNewTPRec.cStrike = bestSSQRColumn.callStrike;
thisNewTPRec.wcStrike = bestSSQRColumn.wCallStrike;
thisNewTPRec.expDate = bestSSQRColumn.putExpiry; // set the options Expiry
thisNewTPRec.thetaExpiration = bestSSQRColumn.callExpiry; // set the theta Expiry
thisNewTPRec.ROC = bestSSQRColumn.ROC;
thisNewTPRec.ROR = bestSSQRColumn.ROR;
thisNewTPRec.CCOR = bestSSQRColumn.CCOR;
thisNewTPRec.RORThresh = RORThresh;
thisNewTPRec.ROCThresh = ROCThresh;
thisNewTPRec.CCORThresh = CCORThresh;
//thisNewTPRec.tradeCriteria = switchROC ? "ROC" : "ROR";
thisNewTPRec.tradeCriteria = "Wing";
thisNewTPRec.stockADX = lastAdx;
thisNewTPRec.stockADXR = lastAdxr;
thisNewTPRec.stockOBV = lastObv;
//thisNewTPRec.stockAD = lastAd;
//thisNewTPRec.stockADOSC = lastAdOsc;
//thisNewTPRec.stockSTO = lastSto;
thisNewTPRec.stockVariance = lastVariance;
//Debug(tradableColumn.ToString());
var tradablePut = bestSSQRColumn.putSymbol; // retrieve the put to buy
var tradableCall = bestSSQRColumn.callSymbol; // retrieve the call to sell
var tradableWCall = bestSSQRColumn.wCallSymbol; // retrievce wc call to sell
// Option logCorrespondingPut = AddCorrespondingPut(tradableCall, ref symbolDataBySymbol[thisSymbol].currentOptions); // Add the corresponding put here so system tracks its price for Ex-dividend approachment
// logCorrespondingPut = AddCorrespondingPut(bestSSQRColumn.wCallSymbol, ref symbolDataBySymbol[thisSymbol].currentOptions); // Add the wing call corresponding put here so system tracks its price for Ex-Dividend approachment
// netOptions should be greater than the put premium + wc call premium. Figure out how many wings can be bought.
//wingPremium = bestSSQRColumn.wingFactor;
// thisWingFactor = bestSSQRColumn.wingFactor;
thisWingFactor = 1;
doTheTrade = true;
//calculate the # of call Options to sell in $-Neutral Variable Call Coverage model:
optionsToTrade = oldTradeRec.uQty/100;
//callsToTrade = Decimal.Round(optionsToTrade * bestSSQRColumn.putPremium / bestSSQRColumn.callPremium); /// VCCPTS legacy code
// *** /// **** tradablePut can be null
doTheTrade = true;
Debug(" ROLLING ** EXECUTING PUT BUY MARKET ORDER TO OPEN " + ((1 + thisWingFactor) * optionsToTrade) + " contracts of " + tradablePut );
var putTicket = MarketOrder(tradablePut, (1 + thisWingFactor) * optionsToTrade);
if (putTicket.Status == OrderStatus.Filled)
{
thisNewTPRec.pSymbol = tradablePut;
thisNewTPRec.pStartPrice = putTicket.AverageFillPrice;
thisNewTPRec.pQty = (int)putTicket.QuantityFilled;
Debug(" ROLLING ** UPDATING PUT START PRICE TO " + thisNewTPRec.pStartPrice + " FOR " + thisNewTPRec.pQty + " CONTRACTS" );
}
doTheTrade = true;
Debug(" ROLLING ** EXECUTING CALL SELL MARKET ORDER TO OPEN " + optionsToTrade + " contracts of " + tradableCall );
var callTicket = MarketOrder(tradableCall, -optionsToTrade);
//var callTicket = MarketOrder(tradableCall, -callsToTrade);
if (callTicket.Status == OrderStatus.Filled)
{
thisNewTPRec.cSymbol = tradableCall;
thisNewTPRec.cStartPrice = callTicket.AverageFillPrice;
thisNewTPRec.cQty = (int)callTicket.QuantityFilled;
Debug(" ROLLING ** UPDATING SHORT CALL START PRICE TO " + thisNewTPRec.cStartPrice + " FOR " + thisNewTPRec.cQty + " CONTRACTS" );
}
doTheTrade = true;
if (thisWingFactor > 0) {
Debug(" ROLLING ** EXECUTING WING CALL BUY MARKET ORDER TO OPEN " + (thisWingFactor*optionsToTrade) + " contracts of " + tradableWCall );
var wCallTicket = MarketOrder(tradableWCall, thisWingFactor * optionsToTrade);
if (wCallTicket.Status == OrderStatus.Filled) {
thisNewTPRec.wcSymbol = tradableWCall;
thisNewTPRec.wcStartPrice = wCallTicket.AverageFillPrice;
thisNewTPRec.wcQty = (int)wCallTicket.QuantityFilled;
Debug(" ROLLING ** UPDATING WING CALL START PRICE TO " + thisNewTPRec.wcStartPrice + " FOR " + thisNewTPRec.wcQty + " CONTRACTS" );
} else {
Debug(" ROLLING ** WING FACTOR IS 0 -- NO WINGS ADDED");
}
}
/// Roll is done. save the new trade performance record
var orderedSSQRMatrix = LUD.SSQRMatrix.OrderByDescending(p => p.CCOR);
IterateOrderedSSQRMatrix(orderedSSQRMatrix);
// IterateTradeRecord(thisNewTPRec);
tprsToClose.Add(oldTradeRec);
tprsToOpen.Add(thisNewTPRec);
//tradeRecs.Add(thisNewTPRec);
return true;
}
///////////////////////////////////////////////////////////////////////////////////
//
// GetBestCollar 1 parameters
//
////////////////////////////////////////////////////////////////////////////////////
public SSQRColumn GetBestCollar(CollarAlgorithm algo, ref LookupData LD)
{
if (haltProcessing)
{
Debug(" @@@@@@ Logging GetPotentialCollars 1");
}
Slice thisSlice = CurrentSlice;
Symbol thisStock = LD.uSymbol;
// First get the underlying stock price in this Slice
decimal stockPrice = thisSlice[thisStock].Price;
SSQRColumn bestTradableColumn = new SSQRColumn();
OptionChain putChain; // instantiate an OptionChain var for updating SSQRMatrix with slice data
OptionChain callChain; //
OptionChain wcallChain; //
OptionContract putContract; //
OptionContract callContract; //
Symbol ssqrPutSymbol; // instantiate a Symbol var for updating SSQRMatrix with slice Data
Symbol ssqrCallSymbol; //
// Second get its options symbols
var allUnderlyingOptionsSymbols = OptionChainProvider.GetOptionContractList(thisStock, thisSlice.Time);
if (allUnderlyingOptionsSymbols.Count() == 0) // missing data at this time
{
Debug(" DDDDDDDDDDDDDDDDDDDDD Missing Data at " + thisSlice.Time + " no options for " + thisStock);
List<SSQRColumn> blankCollarsList = new List<SSQRColumn>();
return bestTradableColumn;
}
int findYear = thisSlice.Time.Year;
int findMonth = thisSlice.Time.Month;
// Compute the 3rd Friday of this month [options expiration] ---> do not adjust for potential holiday here
DateTime thisMonthExpiry = FindDay(findYear, findMonth, DayOfWeek.Friday, 3);
// Use the 3rd Friday of the current month to seed the function to return the next 4 ex-dividends expiries adjusted for holidays
Dictionary<int, DateTime> expiries = GetOptionExpiries(thisSlice.Time, LD.exDivdnDate, thisMonthExpiry, true);
// now assemble the SSQR matrix using the expiries dictionary and the contracts lists
LD.SSQRMatrix.Clear();
AssembleSSQRMatrix(this, ref LD, expiries);
/*foreach (SSQRColumn ssqrC in passedMatrix) /// loop through the SSQRMatris to update the deltas and open interest
{
ssqrPutSymbol = ssqrC.putSymbol;
ssqrCallSymbol = ssqrC.callSymbol;
if (thisSlice.OptionChains.TryGetValue(ssqrPutSymbol, out ssqrPutChain))
{
Debug(" HEY THE ssqrPutChain count is " + ssqrPutChain + " AT " + thisSlice.Time + " in FROM COLLARS.");
} else {
Debug(" HEY NO OPTIONS IN THIS SLICE in FROM COLLARS" + thisSlice.Time);
}
if (thisSlice.OptionChains.TryGetValue(ssqrCallSymbol, out ssqrCallChain))
{
// Moved this code to Main.cs *** ssqrCallChain will not be included in the same Slice
// where the options contracts are added.
}
}
*/
// Get the SSQRColumn with the best reward to risk
if (LD.SSQRMatrix == null | LD.SSQRMatrix.Count == 0) return bestTradableColumn; /// found it's possible to have no SSQRs, if so, pass the empty/null SSQRColumn to calling routine
var qualifyingCollars = LD.SSQRMatrix.Where(s=>s.putPremium!=0 & s.putPremium<=s.callPremium).Count();
if (qualifyingCollars == 0) return bestTradableColumn;
// bestTradableColumn = passedMatrix.OrderByDescending(p => p.CCOR).FirstOrDefault();
bestTradableColumn = LD.SSQRMatrix.OrderBy(bTC => bTC.CCOR).FirstOrDefault(); /// 2021-03-21 -- changed from OrderedByDescending ..... using downsideRisk/upsidePotential
return bestTradableColumn;
}
///////////////////////////////////////////////////////////////////////////////////
//
// GetBestCollar 2 parameters
//
////////////////////////////////////////////////////////////////////////////////////
public SSQRColumn GetBestCollar(QCAlgorithm algo, ref LookupData LD, SymbolData SD)
{
if (haltProcessing)
{
Debug(" @@@@@@ Logging GetPotentialCollars");
}
Slice thisSlice = algo.CurrentSlice;
Symbol thisStock = LD.uSymbol;
// First get the underlying stock price in this Slice
decimal stockPrice = thisSlice[thisStock].Price;
SSQRColumn bestTradableColumn = new SSQRColumn();
OptionChain putChain; // instantiate an OptionChain var for updating SSQRMatrix with slice data
OptionChain callChain; //
OptionChain wcallChain; //
OptionContract putContract; //
OptionContract callContract; //
Symbol ssqrPutSymbol; // instantiate a Symbol var for updating SSQRMatrix with slice Data
Symbol ssqrCallSymbol; //
// Second get its options symbols
var allUnderlyingOptionsSymbols = OptionChainProvider.GetOptionContractList(thisStock, thisSlice.Time);
if (allUnderlyingOptionsSymbols.Count() == 0) // missing data at this time
{
Debug(" DDDDDDDDDDDDDDDDDDDDD Missing Data at " + thisSlice.Time + " no options for " + thisStock);
List<SSQRColumn> blankCollarsList = new List<SSQRColumn>();
return bestTradableColumn;
}
int findYear = thisSlice.Time.Year;
int findMonth = thisSlice.Time.Month;
// Compute the 3rd Friday of this month [options expiration] ---> do not adjust for potential holiday here
DateTime thisMonthExpiry = FindDay(findYear, findMonth, DayOfWeek.Friday, 3);
// Use the 3rd Friday of the current month to seed the function to return the next 4 ex-dividends expiries adjusted for holidays
Dictionary<int, DateTime> expiries = GetOptionExpiries(thisSlice.Time, LD.exDivdnDate, thisMonthExpiry, true);
// now assemble the SSQR matrix using the expiries dictionary and the contracts lists
AssembleSSQRMatrix(algo, ref LD, expiries);
/*foreach (SSQRColumn ssqrC in passedMatrix) /// loop through the SSQRMatris to update the deltas and open interest
{
ssqrPutSymbol = ssqrC.putSymbol;
ssqrCallSymbol = ssqrC.callSymbol;
if (thisSlice.OptionChains.TryGetValue(ssqrPutSymbol, out ssqrPutChain))
{
Debug(" HEY THE ssqrPutChain count is " + ssqrPutChain + " AT " + thisSlice.Time + " in FROM COLLARS.");
} else {
Debug(" HEY NO OPTIONS IN THIS SLICE in FROM COLLARS" + thisSlice.Time);
}
if (thisSlice.OptionChains.TryGetValue(ssqrCallSymbol, out ssqrCallChain))
{
// Moved this code to Main.cs *** ssqrCallChain will not be included in the same Slice
// where the options contracts are added.
}
}
*/
// Get the SSQRColumn with the best reward to risk
if (LD.SSQRMatrix.Count == 0) return bestTradableColumn; /// found it's possible to have no SSQRs, if so, pass the empty/null SSQRColumn to calling routine
var qualifyingCollars = LD.SSQRMatrix.Where(s=>s.putPremium!=0 & s.putPremium<=s.callPremium).Count();
if (qualifyingCollars == 0) return bestTradableColumn;
// bestTradableColumn = passedMatrix.OrderByDescending(p => p.CCOR).FirstOrDefault();
bestTradableColumn = LD.SSQRMatrix.OrderBy(bTC => bTC.CCOR).FirstOrDefault(); /// 2021-03-21 -- changed from OrderedByDescending ..... using downsideRisk/upsidePotential
return bestTradableColumn;
}
}
}using QuantConnect.Securities.Option;
using Newtonsoft.Json;
namespace QuantConnect.Algorithm.CSharp {
public partial class CollarAlgorithm : QCAlgorithm
{
public class optGrksRec {
//algo.Debug(thisContract.Symbol.Value + ", " + thisContract.BidPrice + ", " + thisContract.AskPrice + ", " + thisContract.LastPrice + ", " +
//thisContract.OpenInterest + ", "+ testVol + ", " + thisContract.TheoreticalPrice + ", " + thisContract.Greeks.Delta + ", " + thisContract.ImpliedVolatility);
// "Gamma: " + thisContract.Greeks.Gamma + "Vega: " + thisContract.Greeks.Vega + "Rho: " + thisContract.Greeks.Rho + "Theta: " + thisContract.Greeks.Theta / 365 +4
public string uSymbol; // Underlying Symbol
public string BidPrice; // Bid Price
public string AskPrice; // Ask Price
public string LastPrice; // Last Price
public string OpenInterest; // Open Interest
public string TheoreticalPrice; // Theoretical Price
public string Delta; // Delta
public string ImpliedVolatility; // Implied Vol
public string Gamma; // Gamma
public string Vega; // Vega
public string Rho; // Rho
public string Theta; // Theta
public string ToJson()
{
string json = JsonConvert.SerializeObject(this, Formatting.Indented);
return json;
}
}
public class TradePerfRec
{
public Symbol uSymbol; // 1 Underlying Symbol
public int index; // 2 Index to trace the trade and all offspring P&L
public bool isOpen = false; // 3 Is the trade ongoing (open)?
public bool isInitializer = false; // 4 Is this the collar-initializing trade
public bool isSecondary = false; // 5 Is this a put roll up
public bool isTheta = false; // 6 Is this a solely-call TPR
public int tradeRecCount; // 7 counter for trade records -- use in the single-stock use case
public DateTime startDate; // 8 starting date for collar
public DateTime endDate; // 9 ending date for the collar
public string strtngCndtn; // 10 for 2nd TPRs, record the starting conditions
public string reasonForClose; // 11 reason why collar was killed (ITM options roll, etc.)
public DateTime expDate; // 12 expiration date for collar
public DateTime thetaExpiration; // 13 expiration date for the short call
public Symbol pSymbol; // 14 Put Symbol
public Symbol cSymbol; // 15 Call Symbol
public Symbol wcSymbol; // 16 Wing Call Symbol
public decimal pStrike; // 17 put strike
public decimal cStrike; // 18 call strike
public decimal wcStrike; // 19 ATM Call Strike
public decimal pDelta; // 20 put Delta
public decimal cDelta; // 21 call Delta
public decimal wcDelta; // 22 atm Call Delta
public decimal pGamma; // 23 put Gamma
public decimal cGamma; // 24 call Gamma
public decimal wcGamma; // 25 atm Call Gamma
public int uQty; // 26 number of underlying shares
public int pQty; // 27 number of put contracts
public int cQty; // 28 number of call contracts
public int wcQty; // 29 number of wing call contracts
public decimal uStartPrice; // 30 Underlying Price when trade put on
public decimal pStartPrice; // 31 Put Price when trade put on
public decimal cStartPrice; // 32 Call Price when trade put on
public decimal wcStartPrice; // 33 ATM Call Price when trade put on
public decimal uEndPrice; // 34 Underlying Price when trade taken off
public decimal pEndPrice; // 35 Put Price when trade taken off
public decimal cEndPrice; // 36 Call Price when trade taken off
public decimal wcEndPrice; // 37 ATM Call Price when trade taken off
public int numDividends; // 38 # of dividends collected during the trade
public decimal divIncome; // 39 $'s collected in Dividend income during the trade
public decimal betaValue; // 40 beta value of underlying when trade put on
public decimal RORThresh; // 41 Threshold for ROR
public decimal ROCThresh; // 42 Threshold for ROC
public decimal CCORThresh; // 43 Threshold for CCOR
public string tradeCriteria; // 44 ROR or ROC or CCOR
public decimal ROR; // 45 ROR calculation from SSQR Matrix
public decimal ROC; // 46 ROC calculation from SSQR Matrix
public decimal CCOR; // 47 CCOR calculation from SSQR Matrix
public decimal stockADX; // 48 Average Directional Index Value
public decimal stockADXR; // 49 Average Directional Index Rating
public decimal stockOBV; // 50 On Balance Volume
public decimal stockAD; // 51 Accumulation/Distribution
public decimal stockADOSC; // 52 Accumulation/Distribution Oscillator
public decimal stockSTO; // 53 Stochastic value
public decimal stockVariance; // 54 Variance of underlying stock
public decimal currSellPnL; // 55.. Rolltime evaluation of PnL if selling
public decimal currExrcsPutPnL; // 56.. Rolltime evaluation of PnL if exercising put
public decimal currExrcsCallPnL; // 57.. Rolltime evaluation of PnL if calls are assigned
public decimal grossPnL; // 58 runtime calculation of PnL at close;
public decimal SSQRnetProfit; // 59 runtime calculation of replacement bestSSQR net Profit
// **** put class methods here to use collection of TradePerfRecs as basis to examine positions for expirations and assignments
public bool CheckRolling(CollarAlgorithm algo, ref LookupData LUD)
{
Slice slc = algo.CurrentSlice;
Symbol symbUndr = LUD.uSymbol;
string strTckr = symbUndr.Value;
decimal stkPrc = slc[symbUndr].Price;
LUD.dtTst = slc.Time;
LUD.GetNextExDate(algo);
this.GetPnLs(algo, ref LUD, ref stkPrc);
int daysRemainingDiv = LUD.exDivdnDate.Subtract(slc.Time).Days;
if (daysRemainingDiv < 4 && daysRemainingDiv > 0)
{
LUD.SSQRMatrix.Clear();
if (this.CheckDivRoll(algo, ref LUD, ref daysRemainingDiv)) return true;
}
LUD.daysRemainingC = this.cSymbol.ID.Date.Subtract(LUD.dtTst).Days;
LUD.daysRemainingP = this.pSymbol.ID.Date.Subtract(LUD.dtTst).Days;
if (((stkPrc - this.cStrike)/stkPrc >= .05M && LUD.daysRemainingC <= 10 && LUD.daysRemainingC > 1) || ((stkPrc - this.cStrike) > 0 && LUD.daysRemainingC <= 1))
{
LUD.SSQRMatrix.Clear();
if (this.CheckCallRoll(algo, ref LUD)) return true;
}
if (( (this.pStrike - stkPrc )/stkPrc >= .05M && LUD.daysRemainingP <= 10 && LUD.daysRemainingP > 1) || ( (this.pStrike > stkPrc) && LUD.daysRemainingP <= 1) )
{
LUD.SSQRMatrix.Clear();
if (this.CheckPutRoll(algo, ref LUD)) return true;
}
if ((LUD.daysRemainingC <= 1 && stkPrc <= this.cStrike) | (LUD.daysRemainingP <= 1 && stkPrc >= this.pStrike)) // this is the put expiration by design. the puts always control the collar and the risk
{
LUD.SSQRMatrix.Clear();
if (CheckOTMRoll(algo, ref LUD) ) return true;
}
return false;
}
private void GetPnLs(CollarAlgorithm algo, ref LookupData LUD, ref decimal stockPrice)
{
decimal currPutPrice = algo.Securities[this.pSymbol].BidPrice;
decimal currCallPrice = algo.Securities[this.cSymbol].AskPrice;
this.currSellPnL = (this.uQty*(stockPrice-this.uStartPrice)) + (100*this.pQty*(currPutPrice - this.pStartPrice)) + (-100*this.cQty*(this.cStartPrice - currCallPrice)) + (100*this.wcQty*(this.wcEndPrice - this.wcStartPrice));
this.currExrcsPutPnL = (this.uQty*(this.pStrike-this.uStartPrice)) + (100*this.pQty*(0 - this.pStartPrice)) + (-100*this.cQty*(this.cStartPrice - currCallPrice)) + (100*this.wcQty*(this.wcEndPrice - this.wcStartPrice));
this.currExrcsCallPnL = (this.uQty*(this.cStrike-this.uStartPrice)) + (100*this.pQty*(currPutPrice - this.pStartPrice)) + (-100*this.cQty*(this.cStartPrice - 0)) + (100*this.wcQty*(this.wcEndPrice - this.wcStartPrice));
}
//*************************************************************************************************
//************** CheckDividendRoll *******************************************************
//*************************************************************************************************
private bool CheckDivRoll(CollarAlgorithm algo, ref LookupData LUD, ref int daysRemaining)
{
bool isRolled = false;
string strCorrSpndngPut = this.GetCorrspndngPut();
decimal decCrrSpndgPutPrice = algo.Securities[strCorrSpndngPut].AskPrice;
Slice slc = algo.CurrentSlice;
if (decCrrSpndgPutPrice < LUD.divdndAmt)
{
if (LUD.doTracing) algo.Debug(" ************** BEGIN APPROACHMENT CALC FOR " + this.uSymbol + " priced @" + algo.Securities[this.uSymbol].Price );
if (LUD.doTracing) algo.Debug(" ************** EX-Date: " + LUD.exDivdnDate.ToString() );
if (LUD.doTracing) algo.Debug(" ************** DIVIDEND " + LUD.divdndAmt.ToString() + " Extrinsic Value: " + decCrrSpndgPutPrice.ToString() );
//bestSSQRColumn = GetBestSSQR(data, LUD.uSymbol, nextExDate); // this is the normal route of non-delta execution
SSQRColumn bestSSQRColumn = new SSQRColumn();
bestSSQRColumn = algo.GetBestCollar(algo, ref LUD);
if (bestSSQRColumn == null || bestSSQRColumn.IsEmpty())
{
if (daysRemaining <= 1) // Risk of Dividend Assignment too high at Ex-Dividend Date so if haven't been able to get at RollTheCollar, kill it here
{
if (LUD.doTracing) algo.Debug(" OOOOOOOOOOOO NO bestSSQR ON LAST DAY OF DIVIDEND-FORCED EXERCISE -- KILL THE COLLAR OOOOOOOOOO");
isRolled = algo.KillTheCollar(this, ref LUD, "NO bestSSQR ON LAST DAY OF DIVIDEND-APPROACHMENT -- KILL" );
LUD.SSQRMatrix.Clear();
bestSSQRColumn = new SSQRColumn();
if (LUD.doTracing) algo.Debug("************** END APPROACHMENT PROCESSING ******************");
if (LUD.doTracing) algo.Debug("-");
return isRolled; // Don't execute further processing in this slice if rolled due to dividend approachment
} else {
if (LUD.doTracing) algo.Debug("************** END DIV APPROACHMENT PROCESSING -- NULL bestSSQR -- TRY AGAIN ******************");
if (LUD.doTracing) algo.Debug("-");
return isRolled; // Exit CheckDivRoll if there's no SSQR Column to process but don't move onto CallExpiryEvaluation for this reason
}
}
if (!bestSSQRColumn.IsEmpty() )
{
//TimeSpan expireDateDeltaSSQR = bestSSQRColumn.putExpiry.Subtract(slD.Time);
//goodThresh = (bestSSQRColumn.CCOR >= CCORThresh);
bool goodThresh = true;
if (goodThresh) // roll the position forward
{
//newRollDate = slD.Time.Date;
// don't do the roll if one has just been done --
// sometimes ex-dividend dates are within 10 days of options expiration and a roll has already been done
decimal stockPrice = algo.Securities[this.uSymbol].Price;
TimeSpan expireDateDeltaSSQR = bestSSQRColumn.putExpiry.Subtract(slc.Time);
if ((bestSSQRColumn.callStrike < stockPrice) && expireDateDeltaSSQR.Days <= 10 ) // make sure that the collar won't be assigned because we're in the options danger zone
{ /////// THIS SHOULD NOT HAPPEN IN v17 AND BEYOND BECAUSE LINQ WAS AMENDED TO PREVENT THESE OPTIONS
if (LUD.doTracing) algo.Debug(" @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ DIVIDEND EXERCISE ROLL ABORT -- CALL PREVENTION @@@@@@@@@@@@@@@@@@@@@@@");
if (LUD.doTracing) algo.Debug(" @@@@@@@@@@@@@@@@@@@ CALL ASK: " + algo.Securities[this.cSymbol].AskPrice + " Strike: " + bestSSQRColumn.callStrike + " Stock Price: " + algo.Securities[this.uSymbol].Price +" @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
if (LUD.doTracing) algo.Debug(" @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@");
if (LUD.doTracing) algo.Debug("-");
if (LUD.doTracing) algo.Debug("************** END APPROACHMENT PROCESSING ******************");
if (LUD.doTracing) algo.Debug("-");
LUD.SSQRMatrix.Clear();
bestSSQRColumn = new SSQRColumn();
// DO NOT KILL THE COLLAR HERE.
return isRolled; // Exit CheckDivRoll if there's no SSQR Column to process but don't move onto CallExpiryEvaluation for this reason
}
if (LUD.doTracing) algo.Debug(" ************** BEGIN DIV APPROACHMENT ROLL ****************");
//iterate potetialCollars here solely when executing a trade
if (this.currSellPnL > 0 | this.uQty * bestSSQRColumn.netIncome > Math.Abs(this.currSellPnL)) { // Roll solely if we can sell the current collar profitably
bool didTheTrade = algo.RollTheCollar(algo, ref LUD, this, ref bestSSQRColumn, "DIVIDEND APPROACHMENT ROLL");
if (didTheTrade) {
isRolled = true;
//oldRollDate = slc.Time.Date; // set the oldRollDate to Date of Roll
if (LUD.doTracing) algo.Debug(" ************** SUCCESSFUL DIV APPROACHMENT ROLL WITH SSQR: ");
var orderedSSQRMatrix = LUD.SSQRMatrix.OrderByDescending(p => p.CCOR);
algo.IterateOrderedSSQRMatrix(orderedSSQRMatrix);
//didTheTrade = false;
} else if (daysRemaining <= 1) // Risk of Dividend Assignment too high at Ex-Dividend Date so if haven't been able to get at RollTheCollar, kill it here
{
isRolled = algo.KillTheCollar(this, ref LUD, "KILL- FAILED ROLL 1ST TPR IN DIVIDEND-FORCED EXERCISE ON LAST DAY" ); // KillTheCollar may return to try again as well
}
LUD.SSQRMatrix.Clear();
bestSSQRColumn = new SSQRColumn();
return isRolled;
} else {
algo.Debug(" 00 Some code");
if (daysRemaining <= 1) // Risk of Dividend Assignment too high at Ex-Dividend Date so if haven't been able to get at RollTheCollar, kill it here
{
isRolled = algo.KillTheCollar(this, ref LUD, "KILL- LOSS ON 1ST TPR IN DIVIDEND-FORCED EXERCISE ON LAST DAY" ); // KillTheCollar may return to try again as well
}
LUD.SSQRMatrix.Clear();
bestSSQRColumn = new SSQRColumn();
if (LUD.doTracing) algo.Debug("************** END APPROACHMENT PROCESSING ******************");
if (LUD.doTracing) algo.Debug("-");
return isRolled; // Don't execute further processing in this slice if rolled due to dividend approachment
}
if (LUD.doTracing) algo.Debug(" ************** END DIV APPROACHMENT ROLL ****************");
if (LUD.doTracing) algo.Debug("-");
if (LUD.doTracing) algo.Debug("************** END DIV APPROACHMENT PROCESSING ******************");
if (LUD.doTracing) algo.Debug("-");
return isRolled; // get out of this Slice
// prevent immediate call assignment
} else { // NOT goodThresh --- kill the collar
if (daysRemaining <= 1) // Risk of Dividend Assignment too high at Ex-Dividend Date so if haven't been able to get at RollTheCollar, kill it here
{
if (LUD.doTracing) algo.Debug(" OOOOOOOOOOOO BAD THRESH ON DIVIDEND-FORCED EXERCISE -- KILL THE COLLAR ON LAST DAY OOOOOOOOOO");
isRolled = algo.KillTheCollar(this, ref LUD, "KILL- LAST DAY BAD THRESH ON DIVIDEND-FORCED EXERCISE" ); // KillTheCollar may return to try again as well
LUD.SSQRMatrix.Clear();
bestSSQRColumn = new SSQRColumn();
if (LUD.doTracing) algo.Debug("************** END APPROACHMENT PROCESSING ******************");
if (LUD.doTracing) algo.Debug("-");
return isRolled;
} else {
if (LUD.doTracing) algo.Debug(" OOOOOOOOOOOO BAD THRESH ON DIVIDEND-FORCED EXERCISE -- RETURN AND TRY AGAIN");
}
LUD.SSQRMatrix.Clear();
bestSSQRColumn = new SSQRColumn();
if (LUD.doTracing) algo.Debug("************** END APPROACHMENT PROCESSING ******************");
if (LUD.doTracing) algo.Debug("-");
return isRolled; // Don't execute further processing in this slice if rolled due to dividend approachment
} // not goodThresh
return isRolled;
} // !bestSSQRColumn /// there was no bestSSQRColumn
} /// *** decCrrSpndgPutPrice > LUD.divdndAmt
return isRolled;
}
//*************************************************************************************************
//************** CheckCallRoll *******************************************************
//*************************************************************************************************
public bool CheckCallRoll (CollarAlgorithm algo, ref LookupData LUD)
{
// Determine if it should be rolled forward.
bool isRolled = false;
Slice slD = algo.CurrentSlice;
if (LUD.doTracing) algo.Debug(" ************** BEGIN ITM CALL CALC FOR {LUD.uSymbol} ****************");
//bestSSQRColumn = GetBestSSQR(data, LUD.uSymbol, nextExDate);
SSQRColumn bestSSQRColumn = algo.GetBestCollar(algo, ref LUD);
if (LUD.SSQRMatrix.Count == 0) {
if (LUD.daysRemainingC <= 1) { // if at the last day of call expiration and haven't yet rolled, kill the collar.
if (LUD.doTracing) algo.Debug($" ********* END ITM CALL FORCED ASSIGNMENT PROCESSING FOR {LUD.uSymbol} -- NO POTENTIAL COLLARS ON LAST DAY *************");
isRolled = algo.KillTheCollar(this, ref LUD, "KILL ITM CALL ASSIGNMENT -- NO POTENTIAL COLLARS ON LAST DAY");
LUD.SSQRMatrix.Clear();
bestSSQRColumn = new SSQRColumn();
if (LUD.doTracing) algo.Debug($" OOOOOOOOO TT END CHECK IMPLICIT CALL ASSIGNMENT FOR {LUD.uSymbol} OOOOOOOOO");
if (LUD.doTracing) algo.Debug("-----");
}
algo.Debug($" ************** END ITM CALL CALC PROCESSING FOR {LUD.uSymbol} -- NO MATRICES ***");
return isRolled; // if no collars then return and loop around again
}
if (bestSSQRColumn == null || bestSSQRColumn.IsEmpty() ) {
if (LUD.daysRemainingC <= 1)
{ // if at the last day of call expiration and haven't yet rolled, kill the collar.
if (LUD.doTracing) algo.Debug($" ********* END ITM CALL FORCED ASSIGNMENT PROCESSING FOR {LUD.uSymbol} -- bestSSQR null or empty ON LAST DAY");
algo.KillTheCollar(this, ref LUD, "KILL ITM CALL ASSIGNMENT -- EMPTY BEST COLLAR ON LAST DAY");
LUD.SSQRMatrix.Clear();
bestSSQRColumn = new SSQRColumn();
if (LUD.doTracing) algo.Debug($" TT END CHECK IMPLICIT CALL ASSIGNMENT FOR {LUD.uSymbol} OOOOOOOOO");
if (LUD.doTracing) algo.Debug("-");
} else
{
if (LUD.doTracing) algo.Debug($" ************** END ITM CALL CALC FOR {LUD.uSymbol} -- null bestSSQRColumn *************");
LUD.SSQRMatrix.Clear();
bestSSQRColumn = new SSQRColumn();
}
return isRolled; // return and exit OnData()
}
bool goodThresh = bestSSQRColumn.CCOR >= CCORThresh;
if (goodThresh) // roll the position forward
{
if (LUD.doTracing) algo.Debug($" ************** BEGIN ITM CALL ROLL FOR {LUD.uSymbol} ****************");
decimal stockPrice = algo.Securities[bestSSQRColumn.uSymbol].Price;
// check to make sure we don't roll into a collar that will be exercised
// SHOULD NOT EXECUTE IN v17+ BECAUSE LINQ MODIDFIED TO PREVENT SUCH OPTIONS
if (algo.Securities[bestSSQRColumn.callSymbol].AskPrice + bestSSQRColumn.callStrike < stockPrice) // make sure that no one can buy the option for less than the stock
{
if (LUD.doTracing) algo.Debug($" @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ABORT ITM CALL ROLL TO PREVENT EXERCISE FOR {LUD.uSymbol} @@@@@@@@@@@");
if (LUD.doTracing) algo.Debug(" @@@@@@@@@@@@@@@@@@@ CALL ASK: " + algo.Securities[bestSSQRColumn.callSymbol].AskPrice + " Strike: " + bestSSQRColumn.callStrike + " Stock Price: " + stockPrice +" @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
if (LUD.doTracing) algo.Debug(" @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
if (LUD.doTracing) algo.Debug("-");
if (LUD.daysRemainingC <= 1) // Risk of Dividend Assignment too high at Ex-Dividend Date so if haven't been able to get at RollTheCollar, kill it here
{
algo.KillTheCollar(this, ref LUD, "ABORT ITM CALL ROLL TO PREVENT EXERCISE ON LAST DAY" ); // KillTheCollar may return to try again as well
}
LUD.SSQRMatrix.Clear();
bestSSQRColumn = new SSQRColumn();
if (LUD.doTracing) algo.Debug($" TT END CHECK IMPLICIT CALL ASSIGNMENT FOR {LUD.uSymbol} OOOOOOOOO");
if (LUD.doTracing) algo.Debug($" ------------------------------------------------ ");
return isRolled;
}
if (algo.symbolDataBySymbol[LUD.uSymbol].isRollable == true && (this.currSellPnL > 0 | this.uQty * bestSSQRColumn.netIncome > Math.Abs(this.currSellPnL))) // only roll the collar if the current record may be closed profitably-- otherwise seek exercise in kill
//if (currSellPnL > 0 )
{ /// Roll the Collar if the bestSSQRColumn won't be subsequently exercised.
if (algo.RollTheCollar(algo, ref LUD, this,ref bestSSQRColumn, "ROLL--ITM CALL EXPIRATION APPROACHMENT")) {
if (LUD.doTracing) algo.Debug($" ************** ROLLED ITM CALLS COMPLETED FOR {LUD.uSymbol}*************");
var orderedSSQRMatrix = LUD.SSQRMatrix.OrderBy(p => p.CCOR);
algo.IterateOrderedSSQRMatrix(orderedSSQRMatrix);
//didTheTrade = false;
} else if (LUD.daysRemainingC <= 1) {
if (LUD.doTracing) algo.Debug($" ************** UNSUCCESSFUL ROLL FOR {LUD.uSymbol} -- KILL ITM PUT COLLAR ON LAST DAY **************");
algo.KillTheCollar(this, ref LUD, "KILL- LOSS IN 1st TPR IN ITM CALL ROLL" ); // Goto KillTheCollar and determine whether to close or allow call assignment there
LUD.SSQRMatrix.Clear();
bestSSQRColumn = new SSQRColumn();
if (LUD.doTracing) algo.Debug($" TT END CHECK IMPLICIT CALL ASSIGNMENT FOR {LUD.uSymbol} OOOOOOOOO");
if (LUD.doTracing) algo.Debug($" ------------------------------------------------ ");
}
} else if (LUD.daysRemainingC <= 1) {
algo.Debug($" ************** UNPROFITABLE ROLL FOR {LUD.uSymbol} -- KILL ITM PUT COLLAR ON LAST DAY **************");
algo.KillTheCollar(this, ref LUD, "KILL- LOSS IN 1st TPR IN ITM CALL ROLL" ); // Goto KillTheCollar and determine whether to close or allow call assignment there
LUD.SSQRMatrix.Clear();
bestSSQRColumn = new SSQRColumn();
if (LUD.doTracing) algo.Debug($" TT END CHECK IMPLICIT CALL ASSIGNMENT FOR {LUD.uSymbol} OOOOOOOOO");
if (LUD.doTracing) algo.Debug($" ------------------------------------------------ ");
return isRolled;
}
} else // If not goodThresh, but expireDateDelta<=1, may get assigned on ITM calls
{ // This programmatic flow allows days expireDateDelta -9 through -2 to be evaluated sequentially
// because stock price fluctuations may trigger assignment in that date range. But on the last day
// and the call is ITM, assignment will probably happen. If goodThresh above, RollTheCollar was called
// Put options should expire without value but sell them and capture whatever value possible
// exercise the calls here while puts may be sold for some value, even a penny. <4¢ can be sold for 0 commission
// capture the ending prices and close the TradePerformanceRecord by removing the old instance and inserting the updated copy
if (LUD.doTracing) algo.Debug($" ************** END ITM CALL FORCED ASSIGNMENT PROCESSING FOR {LUD.uSymbol}-- BAD THRESH ****************");
if (LUD.daysRemainingC <= 1) {
if (LUD.doTracing) algo.Debug($" ************** KILL COLLAR IN ITM CALL FORCED ASSIGNMENT PROCESSING FOR {LUD.uSymbol} -- BAD THRESH ON LAST DAY");
algo.KillTheCollar(this, ref LUD, "KILL ITM CALL -- PREVENT ASSIGNMENT");
}
LUD.SSQRMatrix.Clear();
bestSSQRColumn = new SSQRColumn();
if (LUD.doTracing) algo.Debug($" TT END CHECK IMPLICIT CALL ASSIGNMENT FOR {LUD.uSymbol} OOOOOOOOO");
if (LUD.doTracing) algo.Debug($" ------------------------------------------------ ");
return isRolled; // exit OnData() and loop around again until last day. May get assigned!
//ExerciseOption(shortedCallSymbol, Decimal.ToInt32(this.cQty)); // LEAN error, cannot exercise short options
}
LUD.SSQRMatrix.Clear();
bestSSQRColumn = new SSQRColumn();
if (LUD.doTracing) algo.Debug($" TT END CHECK IMPLICIT CALL ASSIGNMENT FOR {LUD.uSymbol} OOOOOOOOO");
if (LUD.doTracing) algo.Debug($" ------------------------------------------------ ");
return false;
// endif ITM calls -10 -> Expiry. Probably do an elseif {ITM puts here to definitively trap all assignments
} // end CheckCallRoll function
//*************************************************************************************************
//************** CheckPutRoll *******************************************************
//*************************************************************************************************
public bool CheckPutRoll (CollarAlgorithm algo , ref LookupData LUD)
{
bool isRolled = false;
// Determine if it should be rolled forward.
if (LUD.doTracing) algo.Debug($" ************** BEGIN ITM PUT CALC FOR {LUD.uSymbol} ****************");
Slice slD = algo.CurrentSlice;
decimal stockPrice = algo.Securities[LUD.uSymbol].Price;
//bestSSQRColumn = GetBestSSQR(data, LUD.uSymbol, nextExDate);
SSQRColumn bestSSQRColumn = algo.GetBestCollar(algo, ref LUD);
if (LUD.SSQRMatrix.Count == 0) {
if (LUD.daysRemainingP <= 1) {
if (LUD.doTracing) algo.Debug($" ********* END ITM PUT FORCED ASSIGNMENT PROCESSING FOR {LUD.uSymbol} -- NO POTENTIAL COLLARS ON LAST DAY *************");
isRolled = algo.KillTheCollar(this, ref LUD, "KILL ITM PUT ASSIGNMENT -- NO POTENTIAL COLLARS ON LAST DAY");
LUD.SSQRMatrix.Clear();
bestSSQRColumn = new SSQRColumn();
if (LUD.doTracing) algo.Debug($" TT END CHECK IMPLICIT PUT ASSIGNMENT FOR {LUD.uSymbol} OOOOOOOOO");
if (LUD.doTracing) algo.Debug("-----");
}
algo.Debug($" ************** END ITM PUT CALC FOR {LUD.uSymbol} -- NO POTCOLS ***");
return isRolled; // if no collars then return and loop around again
}
if (bestSSQRColumn == null || bestSSQRColumn.IsEmpty() ) {
if (LUD.daysRemainingP <= 1) { // if at the last day of put expiration and haven't yet rolled, kill the collar.
if (LUD.doTracing) algo.Debug($" ********* KILL 1st TPR ON LAST DAY OF ITM PUT PROCESSING FOR {LUD.uSymbol} *************");
isRolled = algo.KillTheCollar(this, ref LUD, "KILL ITM PUT ASSIGNMENT -- EMPTY BEST COLLARS ON LAST DAY");
LUD.SSQRMatrix.Clear();
bestSSQRColumn = new SSQRColumn();
if (LUD.doTracing) algo.Debug($" TT END CHECK IMPLICIT PUT ASSIGNMENT FOR {LUD.uSymbol} OOOOOOOOO");
if (LUD.doTracing) algo.Debug("--------");
} else {
if (LUD.doTracing) algo.Debug($" ********* END ITM PUT FORCED ASSIGNMENT PROCESSING FOR {LUD.uSymbol} -- bestSSQR null or empty LOOPING TO TRY AGAIN");
LUD.SSQRMatrix.Clear();
bestSSQRColumn = new SSQRColumn();
return isRolled; // loop around and try again
}
}
Symbol tradablePut = bestSSQRColumn.putSymbol;
Symbol tradableCall = bestSSQRColumn.callSymbol;
decimal fTPRPutPrice = algo.Securities[tradablePut].BidPrice;
// determine if the loss on the put leg is greater than the intial "real potential loss". If it is, exercise the position
/*if ((this.pStartPrice - fTPRPutPrice) > (this.uStartPrice + this.pStartPrice - this.cStartPrice) )
{
if (LUD.doTracing) algo.Debug(" TT ITM PUT EXPIRATION -- FORCE PUT ASSIGNMENT CHEAPER OOOOOOOOOOO"); // EXERCISE THE PUT removing PUTs and STOCK. Buy back calls in OnOrder()
var closeCallTicket = MarketOrder(shortedCallSymbol, -this.cQty);
if (closeCallTicket.Status == OrderStatus.Filled)
{
this.cEndPrice = closeCallTicket.AverageFillPrice;
}
var putExerciseTicket = ExerciseOption(longPutSymbol, this.pQty);
potentialCollars.Clear();
bestSSQRColumn = new SSQRColumn();
if (LUD.doTracing) algo.Debug(" ************** END ITM PUT CALC -- EXERCISED PUTS ******");
return isRolled;
} */
bool goodThresh = bestSSQRColumn.CCOR >= CCORThresh;
if (goodThresh) // roll the position forward
{
// check bestSSQRColumn to make sure we don't roll into a collar that will be subsequently exercised
// this was fixed in v17+ by adding condition to .where() of LINQ to prevent such options from being returned
if (algo.Securities[tradableCall].AskPrice + bestSSQRColumn.callStrike < stockPrice) // make sure that no one can buy the option for less than the stock
{
if (LUD.doTracing) algo.Debug($" @@@@@@@@@@@@@@@@@@@ ITM PUT ROLL ABORT FOR {LUD.uSymbol} -- IMMEDIATE CALL-EXERCISE PREVENTION FADE @@@@@@@@@@@@@@@@@@@@@@@");
if (LUD.doTracing) algo.Debug(" @@@@@@@@@@@@@@@@@@@ CALL ASK: " + algo.Securities[tradableCall].AskPrice + " Strike: " + bestSSQRColumn.callStrike + " Stock Price: " + stockPrice +" @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
if (LUD.doTracing) algo.Debug(" @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
if (LUD.doTracing) algo.Debug("------");
if (LUD.daysRemainingP <= 1) {
isRolled = algo.KillTheCollar(this, ref LUD, "ABORT ITM PUT ROLL TO PREVENT SUBSEQUENT CALL ASSIGNMENT");
}
LUD.SSQRMatrix.Clear();
bestSSQRColumn = new SSQRColumn();
return isRolled;
}
if (LUD.doTracing) algo.Debug($" ************** BEGIN ITM PUT ROLL FOR {LUD.uSymbol} ****************");
//if (!newRollDate.Equals(oldRollDate)) {
if (algo.symbolDataBySymbol[LUD.uSymbol].isRollable == true && (this.currSellPnL > 0 | this.uQty * bestSSQRColumn.netIncome > Math.Abs(this.currSellPnL))) { // Roll solely if we can sell the current collar profitably
//if (currSellPnL > 0 ) { // Roll solely if we can sell the current collar profitably
if (algo.RollTheCollar(algo, ref LUD, this, ref bestSSQRColumn, "ROLL -- ITM PUT NEAR EXPIRATION")) {
isRolled = true;
if (LUD.doTracing) algo.Debug($" ************** ROLLED ITM PUTS COMPLETED FOR {LUD.uSymbol} ****************");
var orderedSSQRMatrix = LUD.SSQRMatrix.OrderBy(p => p.CCOR); // 2021-03-21 -- changed from OrderedByDescending
algo.IterateOrderedSSQRMatrix(orderedSSQRMatrix);
//didTheTrade = false;
} else {
if (LUD.daysRemainingP <= 1) {
isRolled = algo.KillTheCollar(this, ref LUD, "ITM PUT ROLL FAILED");
}
}
LUD.SSQRMatrix.Clear();
bestSSQRColumn = new SSQRColumn();
} else { // un profitable roll
if (LUD.daysRemainingP <= 1) {
if (LUD.doTracing) algo.Debug($" ************** UNPROFITABLE ITM PUT ROLL FOR {LUD.uSymbol} ON LAST DAY -- ATTEMPT KILL");
isRolled = algo.KillTheCollar(this, ref LUD, "KILL- LOSS IN 1st TPR IN ITM PUT ROLL" );
}
LUD.SSQRMatrix.Clear();
bestSSQRColumn = new SSQRColumn();
if (LUD.doTracing) algo.Debug($" TT END CHECK IMPLICIT PUT ASSIGNMENT FOR {LUD.uSymbol} OOOOOOOOO");
if (LUD.doTracing) algo.Debug("-----");
}
return isRolled; // exit OnData and try again until last day
} else { // bad threshhold on ITM PUT ROLL -- EXERCISE IT
if (LUD.daysRemainingP <= 1) {
if (LUD.doTracing) algo.Debug($" ************** BAD SSQR THRESHOLD IN ITM PUT ROLL FOR {LUD.uSymbol} ON LAST DAY -- ATTEMPT KILL");
isRolled = algo.KillTheCollar(this, ref LUD, "KILL ON LAST DAY OF ITM PUT ");
}
LUD.SSQRMatrix.Clear();
bestSSQRColumn = new SSQRColumn();
if (LUD.doTracing) algo.Debug($" ************** END ITM PUT CALC FOR {LUD.uSymbol} ****************");
if (LUD.doTracing) algo.Debug("---------");
return isRolled; // roll around and try again
}
return isRolled;
} // end CheckPutRoll
//*************************************************************************************************
//************** CheckOTMRoll *******************************************************
//*************************************************************************************************
public bool CheckOTMRoll(CollarAlgorithm algo , ref LookupData LUD) {
bool isRolled = false;
// risk of options expiration WITHOUT EXERCISE
if (LUD.doTracing) algo.Debug($" ************** BEGIN OTM OPTIONS CALC FOR {LUD.uSymbol} ****************");
Slice slD = algo.CurrentSlice;
decimal stockPrice = algo.Securities[LUD.uSymbol].Price;
//bestSSQRColumn = GetBestSSQR(data, LUD.uSymbol, nextExDate);
SSQRColumn bestSSQRColumn = algo.GetBestCollar(algo, ref LUD);
if (LUD.haltProcessing)
{
algo.Debug(" Logging OTM OPTIONS CALC ");
}
if (LUD.SSQRMatrix.Count == 0) {
if (LUD.daysRemainingC <= 1 | LUD.daysRemainingP <= 1) {
isRolled = algo.KillTheCollar(this, ref LUD, "ABORT OTM ROLL -- NO POT COLLARS FOR " + LUD.uSymbol );
LUD.SSQRMatrix.Clear();
bestSSQRColumn = new SSQRColumn();
if (LUD.doTracing) algo.Debug($" ************** END OTM OPTIONS KILL FOR {LUD.uSymbol} ****************");
if (LUD.doTracing) algo.Debug("-");
return isRolled;
} else {
LUD.SSQRMatrix.Clear();
bestSSQRColumn = new SSQRColumn();
algo.Debug($" ************** END OTM OPTIONS CALC -- NO POTCOLS FOR {LUD.uSymbol} -- LOOP AND TRY AGAIN LATER ***");
return isRolled; // if no collars then return and loop around again
}
}
if (bestSSQRColumn == null || bestSSQRColumn.IsEmpty()) {
if (LUD.doTracing) algo.Debug($" ************** null bestSSQRColumn in OTM Expiry Approachment FOR {LUD.uSymbol} *************");
if (LUD.doTracing) algo.Debug($" ************** END OTM OPTIONS CALC FOR {LUD.uSymbol} ****************");
if (LUD.daysRemainingC <= 1 | LUD.daysRemainingP <= 1) {
isRolled = algo.KillTheCollar(this, ref LUD, "END OTM PROCESSING -- NO VIABLE SSQRS FOR " + LUD.uSymbol );
LUD.SSQRMatrix.Clear();
bestSSQRColumn = new SSQRColumn();
if (LUD.doTracing) algo.Debug($" ************** END OTM OPTIONS KILL FOR {LUD.uSymbol} LOOP AND TRY AGAIN LATER ****************");
if (LUD.doTracing) algo.Debug("-----");
return isRolled;
} else {
LUD.SSQRMatrix.Clear();
bestSSQRColumn = new SSQRColumn();
algo.Debug($" ************** END OTM OPTIONS CALC FOR {LUD.uSymbol} -- bestSSQRColumn NULL or EMPTY ***");
return isRolled; // exit OnData() and loop around and try again
}
} // no bestSSQRColumn
// IS IT NECESSARY TO SET THESE HERE
Symbol tradablePut = bestSSQRColumn.putSymbol;
Symbol tradableCall = bestSSQRColumn.callSymbol;
//goodThresh = bestSSQRColumn.CCOR >= CCORThresh;
bool goodThresh = true;
if (goodThresh) // roll the position forward
{
if (LUD.doTracing) algo.Debug($" ************** BEGIN OTM OPTIONS ROLL FOR {LUD.uSymbol} ****************");
if (algo.symbolDataBySymbol[LUD.uSymbol].isRollable == true && (this.currSellPnL > 0 | this.uQty * bestSSQRColumn.netIncome > Math.Abs(this.currSellPnL))){ // only roll the collar if the current record may be closed profitably-- otherwise seek exercise in kill
//if (currSellPnL > 0) {
if (algo.RollTheCollar(algo, ref LUD, this, ref bestSSQRColumn, "OTM OPTIONS EXPIRATION ROLL")) {
isRolled = true;
if (LUD.doTracing) algo.Debug($" ************** ROLLED OTM OPTIONS FOR {LUD.uSymbol} COMPLETED WITH SSQR: ****************");
if (LUD.doTracing) algo.Debug("-");
var orderedSSQRMatrix = LUD.SSQRMatrix.OrderBy(p => p.CCOR);
algo.IterateOrderedSSQRMatrix(orderedSSQRMatrix);
//didTheTrade = false;
LUD.SSQRMatrix.Clear();
bestSSQRColumn = new SSQRColumn();
if (LUD.doTracing) algo.Debug($" ************** END SUCCESSFUL OTM OPTIONS ROLL FOR {LUD.uSymbol} ****************");
if (LUD.doTracing) algo.Debug("-");
return isRolled;
} else {
if (LUD.daysRemainingC <= 1 | LUD.daysRemainingP <= 1) {
if (LUD.doTracing) algo.Debug($" ************** KILLING OTM OPTIONS COLLAR FOR {LUD.uSymbol} ON LAST DAY - FAILED ROLL ****************");
isRolled = algo.KillTheCollar(this, ref LUD, "END OTM PROCESSING -- FAILED ROLL FOR " + LUD.uSymbol );
LUD.SSQRMatrix.Clear();
bestSSQRColumn = new SSQRColumn();
if (LUD.doTracing) algo.Debug($" ************** END OTM OPTIONS KILL FOR {LUD.uSymbol} ON LAST DAY - FAILED ROLL ****************");
if (LUD.doTracing) algo.Debug("-");
return isRolled;
}
LUD.SSQRMatrix.Clear();
bestSSQRColumn = new SSQRColumn();
if (LUD.doTracing) algo.Debug($" ************** END OTM OPTIONS ROLL FOR {LUD.uSymbol} -- FAILED ROLL ****************");
if (LUD.doTracing) algo.Debug("-");
return isRolled;
}
} else if (LUD.daysRemainingC <= 1 | LUD.daysRemainingP <= 1) { // CANNOT EXECUTE ROLL PROFITABLY SO KILL THE COLLAR IF ON LAST DAY
isRolled = algo.KillTheCollar(this, ref LUD, "END OTM PROCESSING -- UNPROFITABLE ROLL FOR " + LUD.uSymbol + " ON THE LAST DAY" );
LUD.SSQRMatrix.Clear();
bestSSQRColumn = new SSQRColumn();
if (LUD.doTracing) algo.Debug($" ************** END OTM OPTIONS ROLL FOR {LUD.uSymbol} WITH KILL ****************");
if (LUD.doTracing) algo.Debug("-");
return isRolled;
}
if (LUD.doTracing) algo.Debug($" ************** END OTM OPTIONS ROLL PROCSSING FOR {LUD.uSymbol} ****************");
if (LUD.doTracing) algo.Debug("------------------------------------");
LUD.SSQRMatrix.Clear();
bestSSQRColumn = new SSQRColumn();
return isRolled;
} else if (LUD.daysRemainingC <= 1 | LUD.daysRemainingP <= 1) { // IF BADTHRESH
if (LUD.doTracing) algo.Debug($" ************** BEGIN OTM OPTIONS COLLAR KILL FOR {LUD.uSymbol} ****************");
// kill the collar
isRolled = algo.KillTheCollar(this, ref LUD, "BAD THRESH ON OTM OPTIONS ROLL");
LUD.SSQRMatrix.Clear();
bestSSQRColumn = new SSQRColumn();
if (LUD.doTracing) algo.Debug($" ************** END OTM OPTIONS ROLL WITH KILL ON BAD THRESH FOR {LUD.uSymbol} ****************");
if (LUD.doTracing) algo.Debug("-------");
return isRolled;
} // goodThresh on rolling OTM Options
LUD.SSQRMatrix.Clear();
bestSSQRColumn = new SSQRColumn();
if (LUD.doTracing) algo.Debug($" ************** END OTM OPTIONS ROLL PROCESSING FOR {LUD.uSymbol} ****************");
if (LUD.doTracing) algo.Debug("-");
return isRolled;
} /// END OTM OPTIONS ROLL
public void CloseTPR()
{
this.isOpen = false; // effectively closes the tpr. called in looping through tprsToClose after processing them.
}
public void OpenTPR()
{
this.isOpen = true; // effectively opens the tpr. called in looping through tprsToOpen after processing them.
}
private string GetCorrspndngPut()
{
int indexOfC = this.cSymbol.ToString().LastIndexOf("C");
char[] charArrayC = this.cSymbol.ToString().ToCharArray();
char[] charArrayP = charArrayC;
charArrayP[indexOfC] = 'P';
string putString = new string(charArrayP);
return putString;
}
} /// ***** END CLASS TradePerformanceRecord
public class OpenLimitOrder
{
public OrderTicket oTicket; // order ticket
public TradePerfRec tpr; // Trade performance record for transaction
public OptionRight oRight; // Option Right (OptionRight.Call or OptionRight.Put)
public bool isWingCall = false; // is this oLO a Wing Call
}
public string ConvertTradePerfRec(List<TradePerfRec> tPR)
{
string tPRString = "";
string jasonString = "";
jasonString = "{";
tPRString = ",^^^";
foreach (var field in typeof(TradePerfRec).GetFields())
{
tPRString = tPRString + ", " + field.Name;
}
Debug(tPRString);
var tPREnum = tPR.GetEnumerator();
/////// NOTE: Have to get the JASON formatted correctly. Need one long string. CHECK THIS
while (tPREnum.MoveNext())
{
TradePerfRec thisPerfRec = tPREnum.Current;
jasonString = "{";
tPRString = ",^^^";
tPRString = tPRString + ", " + thisPerfRec.uSymbol;
tPRString = tPRString + ", " + thisPerfRec.index;
tPRString = tPRString + ", " + thisPerfRec.isOpen;
tPRString = tPRString + ", " + thisPerfRec.isInitializer;
tPRString = tPRString + ", " + thisPerfRec.isSecondary;
tPRString = tPRString + ", " + thisPerfRec.isTheta;
tPRString = tPRString + ", " + thisPerfRec.tradeRecCount;
tPRString = tPRString + ", " + String.Format("{0:MM/dd/yy H:mm:ss}", thisPerfRec.startDate);
tPRString = tPRString + ", " + String.Format("{0:MM/dd/yy H:mm:ss}", thisPerfRec.endDate);
tPRString = tPRString + ", " + thisPerfRec.strtngCndtn;
tPRString = tPRString + ", " + thisPerfRec.reasonForClose;
tPRString = tPRString + ", " + String.Format("{0:MM/dd/yy H:mm:ss}", thisPerfRec.expDate);
tPRString = tPRString + ", " + String.Format("{0:MM/dd/yy H:mm:ss}", thisPerfRec.thetaExpiration);
tPRString = tPRString + ", " + thisPerfRec.pSymbol.Value;
tPRString = tPRString + ", " + thisPerfRec.cSymbol.Value;
tPRString = tPRString + ", " + thisPerfRec.wcSymbol.Value;
tPRString = tPRString + ", " + String.Format("{0:0.00}", thisPerfRec.pStrike);
tPRString = tPRString + ", " + String.Format("{0:0.00}", thisPerfRec.cStrike);
tPRString = tPRString + ", " + String.Format("{0:0.00}", thisPerfRec.wcStrike);
tPRString = tPRString + ", " + String.Format("{0:0.00}", thisPerfRec.pDelta);
tPRString = tPRString + ", " + String.Format("{0:0.00}", thisPerfRec.cDelta);
tPRString = tPRString + ", " + String.Format("{0:0.00}", thisPerfRec.wcDelta);
tPRString = tPRString + ", " + String.Format("{0:0.00}", thisPerfRec.pGamma);
tPRString = tPRString + ", " + String.Format("{0:0.00}", thisPerfRec.cGamma);
tPRString = tPRString + ", " + String.Format("{0:0.00}", thisPerfRec.wcGamma);
tPRString = tPRString + ", " + thisPerfRec.uQty;
tPRString = tPRString + ", " + thisPerfRec.pQty;
tPRString = tPRString + ", " + thisPerfRec.cQty;
tPRString = tPRString + ", " + thisPerfRec.wcQty;
tPRString = tPRString + ", " + String.Format("{0:0.00}", thisPerfRec.uStartPrice);
tPRString = tPRString + ", " + String.Format("{0:0.00}", thisPerfRec.pStartPrice);
tPRString = tPRString + ", " + String.Format("{0:0.00}", thisPerfRec.cStartPrice);
tPRString = tPRString + ", " + String.Format("{0:0.00}", thisPerfRec.wcStartPrice);
tPRString = tPRString + ", " + String.Format("{0:0.00}", thisPerfRec.uEndPrice);
tPRString = tPRString + ", " + String.Format("{0:0.00}", thisPerfRec.pEndPrice);
tPRString = tPRString + ", " + String.Format("{0:0.00}", thisPerfRec.cEndPrice);
tPRString = tPRString + ", " + String.Format("{0:0.00}", thisPerfRec.wcEndPrice);
tPRString = tPRString + ", " + thisPerfRec.numDividends;
tPRString = tPRString + ", " + String.Format("{0:0.00}", thisPerfRec.divIncome);
tPRString = tPRString + ", " + String.Format("{0:0.00}", thisPerfRec.betaValue);
tPRString = tPRString + ", " + String.Format("{0:0.00}", thisPerfRec.RORThresh);
tPRString = tPRString + ", " + String.Format("{0:0.00}", thisPerfRec.ROCThresh);
tPRString = tPRString + ", " + String.Format("{0:0.00}", thisPerfRec.CCORThresh);
tPRString = tPRString + ", " + String.Format("{0:0.00}", thisPerfRec.tradeCriteria);
tPRString = tPRString + ", " + String.Format("{0:0.00}", thisPerfRec.ROR);
tPRString = tPRString + ", " + String.Format("{0:0.00}", thisPerfRec.ROC);
tPRString = tPRString + ", " + String.Format("{0:0.00}", thisPerfRec.CCOR);
tPRString = tPRString + ", " + String.Format("{0:0.00}", thisPerfRec.stockADX);
tPRString = tPRString + ", " + String.Format("{0:0.00}", thisPerfRec.stockADXR);
tPRString = tPRString + ", " + String.Format("{0:0.00}", thisPerfRec.stockOBV);
tPRString = tPRString + ", " + String.Format("{0:0.00}", thisPerfRec.stockAD);
tPRString = tPRString + ", " + String.Format("{0:0.00}", thisPerfRec.stockADOSC);
tPRString = tPRString + ", " + String.Format("{0:0.00}", thisPerfRec.stockSTO);
tPRString = tPRString + ", " + String.Format("{0:0.00}", thisPerfRec.stockVariance);
tPRString = tPRString + ", " + String.Format("{0:0.00}", thisPerfRec.grossPnL);
tPRString = tPRString + ", " + String.Format("{0:0.00}", thisPerfRec.SSQRnetProfit);
/*foreach (var field in typeof(TradePerfRec).GetFields())
{
if (field is decimal) {
//tPRString = tPRString + "," + String.Format("{0:0.00}", field.GetValue(thisPerfRec));
tPRString = tPRString + "," + String.Format("{0:0.00}", field.GetValue(thisPerfRec));
}
else if (field is int) {
tPRString = tPRString + "," + String.Format("{0}", field.GetValue(thisPerfRec));
}
else if (field is DateTime) {
tPRString = tPRString + "," + String.Format("{0:MM/dd/yy H:mm:ss}", field.GetValue(thisPerfRec));
}
else if (field is bool) {
tPRString = tPRString + ", " + field.GetValue(thisPerfRec);
} else {
//Console.WriteLine("{0} = {1}", field.Name, field.GetValue(thisPerfRec));
tPRString = tPRString + ", " + field.GetValue(thisPerfRec).ToString();
}
jasonString = jasonString + "\"" + field.Name + "\":\"" + field.GetValue(thisPerfRec) + "\"";
} ^/
/*foreach (var field in typeof(TradePerfRec).GetFields())
{
if (field.GetType() == typeof(decimal)) {
//tPRString = tPRString + "," + String.Format("{0:0.00}", field.GetValue(thisPerfRec));
tPRString = tPRString + "," + String.Format("{0:0.00}", field);
}
else if (field.GetType() == typeof(DateTime)) {
tPRString = tPRString + "," + String.Format("{0:MM/dd/yy H:mm:ss}", field.GetValue(thisPerfRec));
}
else if (field.GetType() == typeof(Symbol)) {
tPRString = tPRString + ", " + field;
} else {
//Console.WriteLine("{0} = {1}", field.Name, field.GetValue(thisPerfRec));
tPRString = tPRString + ", " + field.GetValue(thisPerfRec);
}
jasonString = jasonString + "\"" + field.Name + "\":\"" + field.GetValue(thisPerfRec) + "\"";
} */
jasonString = jasonString + "}," + Environment.NewLine;
Debug(tPRString);
}
return jasonString;
}
}
}