//
// Binomial futures option pricing model: computational engine 
//

public class FutOp {

  int nper;
  double tinc,disc,up,down,prcup,prcdn;
  double val[];

  public FutOp() {}

 
  public void newPars(double ttm,int npers,double r,double sigma) { 
    nper = npers;
    tinc = ttm/(double) nper;
    disc = Math.exp(-r * tinc);
    up = 1.0 + sigma * Math.sqrt(tinc);
    down = 1.0 - sigma * Math.sqrt(tinc);
    prcup = 0.5*disc;
    prcdn = 0.5*disc;
    val = new double[npers+1];}

  public ValHedge eurcall(double f0,double X) {
    int i,j;
    double futprice;
    ValHedge x1 = new ValHedge();
// initialize terminal payoffs
// i is the number of up moves over the whole life
    for(i=0;i<=nper;i++) {
      futprice = f0 * Math.pow(up,(double) i)
        * Math.pow(down,(double) (nper-i));
      val[i] = Math.max(futprice - X,0.0);}
// compute prices back through the tree
// j+1 is the number of periods from the end
// i is the number of up moves from the start
    for(j=0;j<nper-1;j++) {
      for(i=0;i<nper-j;i++) {
        val[i] = prcdn * val[i] + prcup * val[i+1];}}
    x1.value = prcdn * val[0] + prcup * val[1];
    x1.delta = (val[1]-val[0]) / (f0*(up-down));
    return(x1);}}
