# objective function
eval_f0 <- function(x0, x1, x2, x3, x4, x5){
  x1 <- matrix(x0[1:nrow(trd)], ncol = 1)
  return( t(x1)%*%x1)
}
# constraint function
eval_inque <- function(x0, x1, x2, x3, x4, x5) {
  x2 <- matrix(x0[nrow(trd)+1:nrow(trd)*2], ncol = 1)
  x3 <- matrix(x0[nrow(trd)*2+1:nrow(trd)*2+24], ncol = 1)
  x4 <- matrix(x0[nrow(trd)*2+25:nrow(trd)*3+25], ncol = 1)
  x5 <- matrix(x0[nrow(trd)*3+25:nrow(trd)*4+25], ncol = 1)
  return(rbind(c(-1*x2),
               c((trd%*%x3-x4%*%Price+x1)-x5),
               c(-1*x5),
               c(x2-1)))
}
# constraint function
eval_que <- function(x0, x1, x2, x3, x4, x5) {
  x2 <- matrix(x0[nrow(trd)+1:nrow(trd)*2], ncol = 1)
  x3 <- matrix(x0[nrow(trd)*2+1:nrow(trd)*2+24], ncol = 1)
  x4 <- matrix(x0[nrow(trd)*2+25:nrow(trd)*3+25], ncol = 1)
  x5 <- matrix(x0[nrow(trd)*3+25:nrow(trd)*4+25], ncol = 1)
  return(rbind(c(x2-Market),
               c(t(x2%*%(x5-(trd%*%x3-x4%*%Price+x1)))),
               c(t(x5)%*%(1-x2))))
}


res1 <- nloptr( x0=rep(1, nrow(trd)*4+nrow(trd)),
                eval_f = eval_f0,
                eval_g_ineq = eval_inque,
                eval_g_eq = eval_que,
                lb = rep(0, nrow(trd)*4+nrow(trd)),
                ub = rep(Inf, nrow(trd)*4+nrow(trd)),
                opts = list("algorithm"="NLOPT_LD_SLSQP"),
                x1 = matrix(nrow(trd), ncol = 1),
                x2 = matrix(nrow(trd), ncol = 1),
                x3 = matrix(23, ncol = 1),
                x4 = matrix(nrow(trd), ncol = 1),
                x5 = matrix(nrow(trd), ncol = 1)
                )