This script implements a basic trend-following trading strategy on the EUR/USD pair using 15-minute bars, enhanced with a custom linear regression slope calculation for precise trend detection. The price series is analyzed using a 20-period simple moving average and a 14-period RSI, which is normalized between 0 and 1 for threshold-based decision-making. Instead of relying on Zorro’s built-in slope()—which uses an undocumented, fixed internal period—the script defines a custom slopeN() function, allowing dynamic control over the regression window (in this case, 10 bars). This flexibility enables fine-tuning and optimization, which is crucial for adapting to varying market conditions. The strategy enters a long position when the price crosses above the moving average and the RSI indicates the market is not overbought. Risk controls are introduced using the ATR to calculate stop levels and clamp the trade volume, ensuring trades remain within defined bounds. The approach demonstrates how integrating custom statistical functions in lite-C enhances Zorro's built-in capabilities for more adaptable and data-driven trading logic.


Code
var slopeN(vars Data, int Period)
{
	var SX = 0, SY = 0, SXY = 0, SXX = 0;
	int i;
	for(i = 0; i < Period; i++) {
		SX += i;
		SY += Data[i];
		SXY += i*Data[i];
		SXX += i*i;
	}
	var Nom = Period*SXY - SX*SY;
	var Denom = Period*SXX - SX*SX;
	if(Denom == 0.) return 0.;
	return Nom / Denom;
}

function run() 
{
	set(PARAMETERS);
	BarPeriod = 15;
	StartDate = 20220101;
	asset("EUR/USD");

	vars Price = series(priceClose());
	var sma = SMA(Price, 20);
	var rsi = RSI(Price, 14);

	var slopeVal = slopeN(Price, 10);

	var trend = sign(slopeVal);
	var risk = slider(1, 5000, 1000, 10000, "Risk", "Risk setting");
	var atr = ATR(14);
	var stopLevel = clamp(atr*2, 10, 50);
	var normRSI = clamp(rsi/100, 0, 1);
	var tradeVol = clamp(10000 / fix0(atr), 1, 5);

	if(crossOver(Price, sma) && normRSI < 0.7)
		enterLong();

	plot("RSI", normRSI, NEW, RED);
}