Machine Learning for Option Trading

Code
#include <contract.h>

// Initialize global variables for storing price and volatility data
vars PriceClose, VolatilityEMA, BollingerBands, StdDevVolatility;

// Parameter optimization
var BarPeriod, LookBack, FuzzyRange, emaPeriod, StopLoss, TakeProfit, Lots, threshold, momentumThreshold;

void init() {
  assetList("AssetsIB");
  BarPeriod = optimize(60, 30, 120, 10);
  LookBack = optimize(100, 50, 200, 10);
  FuzzyRange = optimize(0.05, 0.01, 0.1, 0.01);
  emaPeriod = optimize(20, 10, 50, 5);
  
  PriceClose = series(priceClose());
  calculateEMAVolatility(emaPeriod); // Initialize volatility calculation
  
  // Initialize additional volatility measures
  BollingerBands = series(BBands(priceClose(), 20, 2));
  StdDevVolatility = series(StdDev(priceClose(), 20));
  
  // Risk management parameters
  StopLoss = optimize(50, 10, 100, 10) * ATR(20);
  TakeProfit = optimize(100, 50, 200, 10) * ATR(20);
  
  // Position sizing
  Lots = optimize(1, 0.1, 2, 0.1) * (1 / VolatilityEMA[0]);
}

void calculateEMAVolatility(int period) {
  vars ATRValues = series(ATR(period));
  VolatilityEMA = series(EMA(ATRValues, period));
}

// Cumulative Normal Distribution Function for use in Black-Scholes Model
var CNDF(var x) {
  int neg = (x < 0.0) ? 1 : 0;
  if (neg) x = -x;
  
  var k = (1.0 / ( 1.0 + 0.2316419 * x));
  var y = (((1.330274429 * k - 1.821255978) * k + 1.781477937) *
           k - 0.356563782) * k + 0.319381530;
  y = 1.0 - 0.398942280401 * exp(-0.5 * x * x) * y;
  
  return (1.0 - neg) * y + neg * (1.0 - y);
}

// Black-Scholes Option Pricing Model
var BlackScholes(char *CallPutFlag, var S, var X, var T, var r, var v) {
  var d1, d2;
  d1 = (log(S / X) + (r + 0.5 * v * v) * T) / (v * sqrt(T));
  d2 = d1 - v * sqrt(T);
  
  if (CallPutFlag[0] == 'c' || CallPutFlag[0] == 'C') {
    return S * CNDF(d1) - X * exp(-r * T) * CNDF(d2);
  } else {
    return X * exp(-r * T) * CNDF(-d2) - S * CNDF(-d1);
  }
}

bool enhancedFuzzyEntryCondition() {
  return risingF(PriceClose) > 0.5 && VolatilityEMA[0] < 0.2 && RSI(PriceClose, 14) < 30 && additionalFilters();
}

bool enhancedFuzzyExitCondition() {
  return fallingF(PriceClose) > 0.5 || VolatilityEMA[0] > 0.3;
}

bool additionalFilters() {
  return MarketVolatility() > threshold && momentum > momentumThreshold;
}

void tradeOptions() {
  CONTRACT* CallContract;
  CONTRACT* PutContract;
  var strikePrice = round(priceClose(0), 100); // Example for rounding to nearest hundred
  var expirationDays = 30; // Targeting options 30 days to expiration

  if (enhancedFuzzyEntryCondition()) {
    // Prepare to trade a call option
    CallContract = contractFind("Call", strikePrice, wdate() + expirationDays * 86400);
    if(CallContract) {
      // Buy the call option
      combo(CallContract, 1, 0, 0, 0, 0, 0, 0);
      enterLong(comboLeg(1));
    }
  } else if (enhancedFuzzyExitCondition()) {
    // Prepare to trade a put option
    PutContract = contractFind("Put", strikePrice, wdate() + expirationDays * 86400);
    if(PutContract) {
      // Buy the put option
      combo(0, 0, PutContract, 1, 0, 0, 0, 0);
      enterLong(comboLeg(2));
    }
  }
}

void run() {
  if (is(INITRUN)) {
    init();
    set(TESTNOW | TRAINMODE);
  }
  
  while(asset(loop("Assets"))) {
    if (is(EXITRUN)) continue;
    tradeOptions(); // Execute the option trading logic based on market conditions

    // Debugging and logging
    if (is(LOGFILE)) {
      log("Entering trade: PriceClose = %.2f, VolatilityEMA = %.2f", PriceClose[0], VolatilityEMA[0]);
    }
  }
  
  // Machine learning integration
  if(is(TRAINMODE)) {
    trainModel(PriceClose, LookBack);
  } else {
    var prediction = predictModel(PriceClose, LookBack);
    if(prediction > threshold) {
      enterLong();
    } else if(prediction < -threshold) {
      enterShort();
    }
  }
}

Last edited by TipmyPip; 07/06/24 15:24.