function [c,ceq] = krgLiquidityConstraint(x,w,C,TradeData,PortfolioTargetValue,PortRiskBounds,lbShares,ubShares,maxMI,maxTotalMI,k)
%KRGLIQUIDITYCONSTRAINT Example constraint function used by KRGLIQUIDITYOPTIMIZATIONEXAMPLE.   
%   [C,CEQ] = KRGLIQUIDITYCONSTRAINT(X,W,C,TRADEDATA,PORTFOLIOTARGETVALUE,PORTRISKBOUNDS,LBSHARES,UBSHARES,MAXMI,MAXTOTALMI,K)

%   Copyright 2016-2020 The MathWorks, Inc.

% Risk constraint
minRiskPct = PortRiskBounds(1);
maxRiskPct = PortRiskBounds(2);

% Upper bounds on risk
c1 = x' * C * x - (w' * C * w * (maxRiskPct^2));

% Lower bounds on risk (this is often 0)
c2 = -x' * C * x + w' * C * w * (minRiskPct^2);

% Upper and lower bounds on Shares in new portfolio
TargetShares = x * PortfolioTargetValue ./ TradeData.Price;
SharesToTrade = TradeData.Shares - TargetShares;
s1 = SharesToTrade - ubShares;
s2 = -SharesToTrade + lbShares;

% Calculate Shares from SharesToTrade
TradeData.Shares = abs(SharesToTrade);

% ADV factor in TradeTime is different than tradetime2pov calc.
TradeData.TradeTime = TradeData.TradeTime .* TradeData.ADV;
TradeData.POV = krg.tradetime2pov(TradeData.TradeTime,TradeData.Shares);

% marketImpact calculation, convert from bp to decimal
MI = marketImpact(k,TradeData)/10000;

% MI Constraints
% This constraint should only be used if the user enters an MI constraint
% 1)  MI<=maxMI %MI constraint on each individual stock
% 2)  x'*MI<=maxPortMI  %MI constraint on the total portfolio
m1 = MI - maxMI;
m2 = abs(x)' * MI - maxTotalMI;

% Inequality non linear constraints
c = [s1;s2;c1;c2;m1;m2];
ceq = [];