I wish to simulate price action using mtrandom() and chart display.
However, each time focus of chart eg. select a bar for underlying symbol while scrolling, mtrandom() recalculates new values for whole array.
I’d like to generate random array only once and use now fixed values as I scroll across chart. Currently the chart constantly updates.
Tried semaphore and other set once code sections.
// --- contants ---
pi = 3.14159265;
TWOPI = 6.28318530718;
// --- parameters ---
lb = 63;
slb = 63;
// --- variables ---
bi = BarIndex();
fvb = FirstVisibleValue( bi );
lvb = LastVisibleValue( bi );
n = lvb - fvb - 1;
// --- functions ---
function RandGauss_Get() {
z = cos( TWOPI * mtRandom() );
z = z * sqrt( -2 * log( 1 - mtRandom() ) );
return z;
}
/******************************************************/
// --- simulate data with Geometric Brownian motion ---
data = C;
mu = MA(data, lb)*252/lb; // annual mean (252 lookback)
SDD = StDev(data, slb, False); // annual SD
SD = ( SDD - LLV(SDD,slb) ) / ( HHV(SDD,slb) - LLV(SDD,slb) + 1e-31 );// need annual SD fractional percent
SD = SD*sqrt(252/slb);
// inputs
St[fvb] = C[fvb]; // initial value number
mu0 = mu[fvb];
SD0 = SD[fvb];
sSD = SD0^2;
dt = 1/252; // annual to daily conversion factor
sdt = sqrt(dt);
// protected section here
norm[fvb] = 0;
if( StaticVarCompareExchange( "semaphore", 1, 0 ) == 0 ) // obtain semaphore
{
for(i=fvb+1; i<BarCount; i++) { norm[i] = RandGauss_Get(); }
// semaphore isn't reset since this is run once
}
// loop soln: S0 uses previous calculated St
part1[fvb] = part2[fvb] =0;
for(i=fvb+1; i<BarCount; i++) {
// St = St * exp((mu-0.5*SD^2)*dt + SD*sdt*norm );
part1[i] = (mu[i] - 0.5*SD[i]^2)*dt;
part2[i] = SD[i] * sdt * norm[i];
St[i] = St[i-1] * exp( part1[i] + part2[i] );
}
Plot( St, "St", colorAqua, styleNoTitle );
Thanks in advance
FE