function [c,ceq] = krgNonLinearConstraint(x,C,tradeData,PortfolioDollars,mR,k,scenario,maxMI,maxTotalMI)
%KRGNONLINEARCONSTRAINT Example non linear constraint function used with KRGPORTFOLIOOPTIMIZATIONEXAMPLE.
%   [C,CEQ] = KRGNONLINEARCONSTRAINT(X,C,TRADEDATA,PORTFOLIODOLLARS,MR,K,SCENARIO,MAXMI,MAXTOTALMI)

%   Copyright 2016-2020 The MathWorks, Inc.

% Calculate Shares from weights, portfolio value, and stock price
% MI Cost is always positive and based on Positive Shares Quantities
% need to take absolute value
tradeData.Shares = abs(x * PortfolioDollars ./ tradeData.Price);

% 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;

switch scenario
  
  case 1
  
    % Scenario #1: Maximize Returns - Lambda*Risk
    c1 = MI - maxMI;
    c2 = x' * MI - maxTotalMI;
    
    c = [c1;c2];
    ceq = [];
    
    
  case 2

    % Scenario #2: Minimize Risk subject to Net Returns >= minReturn
    NetReturn = (tradeData.EstReturn - MI)' * x;
    
    % NetReturn Constraint:
    % 1) NetReturn>=minReturn
    %    -NetReturn+minReturn<=0
    c1 = -NetReturn + mR;
    
    % 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
    c2 = MI - maxMI;
    c3 = x' * MI - maxTotalMI;
   
    c = [c1;c2;c3];
    ceq = [];
    
  case 3
     
    % Scenario #3: Max NetReturn subject to Risk <= maxRisk
    maxVariance = mR^2;
    
    c1 = MI - maxMI;
    c2 = x' * MI - maxTotalMI;

    c = [c1;c2];
    ceq = x' * C * x - maxVariance;

end