package com.strategyquant.extend.MoneyManagementTypes;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.strategyquant.futurelib.backtester.SymbolsTable;
import com.strategyquant.lib.language.L;
import com.strategyquant.lib.results.SQOrder;
import com.strategyquant.lib.results.SQOrderList;
import com.strategyquant.lib.snippets.MoneyManagementSim.MoneyManagementType;
import com.strategyquant.lib.utils.SQUtils;

public class RiskFixedBalancePct extends MoneyManagementType {
	public static final Logger Log = LoggerFactory.getLogger("RiskFixedBalancePct");
	
	private double mmRisk = -1;
	private double mmMaxLots;

	private int mmLots;

	public RiskFixedBalancePct() {
		setName(L.t("Risk fixed % balance"));
		setNote(L.tHtml("<b>Risk fixed percentage of banance</b>"));
		
		addDoubleParameter("Risk", L.t("Risk in %"), 5d, 0.1d, 100d, 0.1d, L.t("How big percentage of your account will be risked in every trade?"));
		addDoubleParameter("Lots", L.t("Lots if no MM"), 1d, 0.01d, 1000000d, 0.1d, L.t("How many lots should be traded if we disable or cannot use Money Management - for example when computed trade size is 0"));
		addDoubleParameter("MaxLots", L.t("Maximum lots"), 5d, 0.01d, 1000000d, 0.1d, L.t("The biggest lot size allowed"));
		
		setFormatedName(L.t("Risk fixed % balance: {Risk}%"));
	}

	@Override
	public void init(SQOrderList originalOrderList, SymbolsTable symbolsTable) throws Exception {
		mmRisk = this.getDoubleParameterValue("Risk");
		mmLots = this.getIntParameterValue("Lots");
		mmMaxLots = this.getDoubleParameterValue("MaxLots");
	}

	@Override
	public double computeTradeSize(SQOrder order, double tickSize, double pointValue) throws Exception {
		if(mmRisk < 0) {
			throw new Exception("Money management wasn't properly initialized. Call init() method before computing trade size!");
		}
		
		double tradeSize = 0;
		double orderSL;
		
      tradeSize = (equity * mmRisk / 100 ) * 100 / 100000; 

		Log.info("trade size computed to: "+tradeSize);

		// round computed trade size to give decimal points and cap it by maximum lots
		tradeSize = SQUtils.roundDown(tradeSize, getDecimals());
		if(tradeSize <= 0 && order.Size != 0) {
			tradeSize = mmLots;
		}
		
		if(tradeSize > mmMaxLots) {
			tradeSize = mmMaxLots;
		}
		
		return tradeSize;
	}
}