How is the higherLevelEMA variable calculated? - java

I've written a simple strategy in PineScript. It goes long when the higherLevelEMA is greater than the lowerLevelEMA and goes short when the higherLevelEMA is lesser than the lowerLevelEMA. This appears to be a working strategy on timeframes like the 15 minute chart. However, while the lowerLevelEMA is pretty straight forward. I am lost as to how the higherLevelEMA is actually being calculated to result in such positive results. I would like to figure out the specifics so I can recreate it in Java. Here is the short PineScript code:
/#version=2
strategy("EMA Crossover", overlay=true)
higherLevelClose = security(tickerid, "300", close)
higherLevelEMA = ema(higherLevelClose, 16)
lowerLevelEMA = ema(close, 21)
longCondition = crossover(higherLevelEMA, lowerLevelEMA)
if (longCondition)
strategy.entry("My Long Entry Id", strategy.long)
shortcondition = crossunder(higherLevelEMA, lowerLevelEMA)
if (shortcondition)
strategy.entry("My Short Entry Id", strategy.short)
plot(higherLevelEMA)
plot(lowerLevelEMA)
I tried to show the strategy I am working on and explained how I am having difficulty with understanding the calculation of a variable.

Related

JFugue 5 note problems

I'm trying to use JFugue 5.0.9 in my Java project to create *.midi files with it. While implementing JFugue's midi capabilities into my project that uses frequencies of a 24 tune makam piano, I realized it has some tune issues.
For example this code:
ChordProgression cp = new ChordProgression("I-III-IV-iv").setKey("E");
System.out.println(cp);
Player player = new Player();
player.play(cp);
should print
E4MAJ G#4MAJ A4MAJ A4MIN
on console as it's said here.
But prints
E4MAJ E4MAJ E4MAJ A4MIN
in my project. Yes, first three chords are same for some reason. They sound same also, of course.
Also, while using microtones like "m390", it doesn't sound exactly in that frequency.
In another file, in the main method I wrote this:
Player player = new Player();
player.play("A4 m440 m400 m390 m380 m370 m360");
I know that A4 and m440 are the same but as it's said here, A5 and m440 should sound same. But in my project A4 and m440 sound same but it's not exactly 440Hz. When I realized something goes wrong, I decided to use a tuning app and here are the frequencies it calculated respectively:
221.5 221.5 197.5 186.6 186.6 186.6 176.2
As you can see, it plays something very near A3 instead of a clear A4. But this is not all. It also sounds exactly same for m390, m380 and m370.
What exactly is wrong here? Any help would be appreciated.
A little note: I'm pretty sure it has nothing to do with my project. I tryed running the codes above in a brand new project, the same problems occured. And there's no problem with my system because my main project and any other softwares like SunVox, they all sound very good actually.
OK, I had a look at the source codes of JFugue 5.0.9 and here is what I got in ChordProgression.java:
/**
* Only converts Roman numerals I through VII, because that's all we need in music theory...
* VIII would be the octave and equal I!
*/
private int romanNumeralToIndex(String romanNumeral) {
String s = romanNumeral.toLowerCase();
if (s.startsWith("vii")) { return 6; }
else if (s.startsWith("vi")) { return 5; }
else if (s.startsWith("v")) { return 4; }
else if (s.startsWith("iv")) { return 3; }
else if (s.startsWith("iii")) { return 2; }
else if (s.startsWith("ii")) { return 1; }
else if (s.startsWith("i")) { return 0; }
else { return 0; }
}
A little laziness... :D One of the problems lies right here. If you use toLowerCase() method without specifying a locale, it causes some problems in runtime. In Turkish alphabet which I'm using right now lower case of I is "ı", not "i". So, the program converts my chords from "I-II-III" to "i-i-i" because as you can see there is no if statement for lower case I of Turkish alphabet (ı) and this leads it to return 0 as in the case of "i".
To solve this issue, we have to either delete lower case conversion and write all if statements for also upper case I's or set default locale to "en" to make sure it converts (upper case)I's to (lower case)i's. So, this should be used in the source:
Locale.setDefault(new Locale("en"));
Fortunately, JFugue is an open source software published under Apache 2.0.
This still doesn't explain why tunes sound wrong but now at least we know that these are totally different problems. Or maybe it seems so... I don't know. I will edit this answer if I ever find out an explanation or a solution for the rest.
Edit
Finally I figured out the problem with microtones by accident. I decided to look at microtone calculation functions in the source one more time.
In MicrotonePreprocessor class (which is in org.staccato package) there is a function named convertFrequencyToStaccato(). What this function does is convert frequency to midi note number and pitch bend value. At the 107th line, that code rounds semitone, octave and pitch values if calculated pitch value is very close to the next note:
// If we're close enough to the next note, just use the next note.
if (pitches >= 16380)
{
pitches = 0;
semitone += 1;
if (semitone == 12)
{
octave += 1;
semitone = 0;
}
}
The line where pitch is reset should be changed as:
pitches = 8192;
Because, you know, neutral pitch value is 8192. 0 (zero) is minimum pitch value and 16384 is maximum pitch value. At first, I thought the same way as the developer: "After 16384, it should be 0. That is okay. No problem here.". Then I said "What if I change pitch-reset value from 0 to 8192?". It worked. This was a beautiful perception error we both had. :D I'm really having a lot of laugh now.
This fixes the microtone issue. I can hear perfect intervals now! I feel happy and satisfied.
Edit2
I just wanted to share my further changes which results in better microtonal tunning:
if (pitches >= 12288)
{
int diff = 16384-pitches;
int applieddiff = 8192-diff;
pitches = applieddiff;
semitone += 1;
if (semitone == 12)
{
octave += 1;
semitone = 0;
}
}
This also helps use semitone (black) keys on a midi-board instead of only tone (white) keys with high pitch values. So, if you send the data to another software, it will detect all keys seperately. For example, there were no G and G# before, only G and G-with-high-pitch. These caused keys to stop eachother when note-on messages are sent simultaneously.

I'm working on Euler 12 , the code i have seems to workes properly but too slow , very very slow. How can i modify it to run faster?

Like i sad , i am working on Euler problem 12 https://projecteuler.net/problem=12 , i believe that this program will give the correct answer but is too slow , i tried to wait it out but even after 9min it still cant finish it. How can i modify it to run faster ?
package highlydivisibletriangularnumber_ep12;
public class HighlyDivisibleTriangularNumber_EP12 {
public static void findTriangular(int triangularNum){
triangularValue = triangularNum * (triangularNum + 1)/2;
}
static long triangularValue = 0l;
public static void main(String[] args) {
long n = 1l;
int counter = 0;
int i = 1;
while(true){
findTriangular(i);
while(n<=triangularValue){
if(triangularValue%n==0){
counter++;
}
n++;
}
if(counter>500){
break;
}else{
counter = 0;
}
n=1;
i++;
}
System.out.println(triangularValue);
}
}
Just two simple tricks:
When x%n == 0, then also x%m == 0 with m = x/n. This way you need to consider only n <= Math.ceil(sqrt(x)), which is a huge speed up. With each divisor smaller than the square root, you get another one for free. Beware of the case of equality. The speed gain is huge.
As your x is a product of two numbers i and i+1, you can generate all its divisors as product of the divisors of i and i+1. What makes it more complicated is the fact that in general, the same product can be created using different factors. Can it happen here? Do you need to generate products or can you just count them? Again, the speed gain is huge.
You could use prime factorization, but I'm sure, these tricks alone are sufficient.
It appears to me that your algorithm is a bit too brute-force, and due to this, will consume an enormous amount of cpu time regardless of how you might rearrange it.
What is needed is an algorithm that implements a formula that calculates at least part of the solution, instead of brute-forcing the whole thing.
If you get stuck, you can use your favorite search engine to find a number of solutions, with varying degrees of efficiency.

"Query-loop" to get the appropriate value out of the DB

So I will have to explain what I'm looking for and I will use an example very general to this so this could help others with the same problem:
Lets assume I'm working at the police station and I'm creating a DB with a table called "Policestations" and the Police of my country has 3 policestations.
Those stations wan't to be as efficient as possible therefore they will pick those incidents if they fullfill some parameters for our example here those 3 policestations:
policeStation:1010
offender:GuyA
place:GB (iso-code)
delict:murder
policeStation:2020
offender:GuyA
place: * (* = "for not relevant")
delict:murder
policeStation:3030
offender:GuyB
place:*
delict:*
So now, I have a method that looks like that (could someone edit this the code thing doesnt work when I add that into it):
public String responsiblePoliceStation(String offender, String place, String delict) {
Query q = em.createQuery("SELECT a.Policestation FROM PoliceStations a WHERE a.offender = :offender AND a.place = :place AND a.delict = :delict );
q.setParameter("offender", offender);
q.setParameter("place", place);
q.setParameter("delict", delict);
String policestation = (String) q.getSingleResult();
return policestation;
}
so now I can call that method for example with that:
PSPRouteService psp = new PSPRouteService();
String pS = psp.responsiblePoliceStation("GuyA", "GB", "murder");
`
and this will work fine, I will get as response that the policeStation with String 1010 has to "solve" this incident.... but as I intended in the header I want a loop so for example thats assume I have that incident:
offender: GuyA
place: Brazil
delict: murder
then this wouldnt work because I dont know how to implement that, if some parameter doesn't fit in then just compare it with the next row and look if the next Policestation is more tolerant and doesn't care for example whether the incident took place.
So I want kinda a query-loop where I compare the given Parameter with my DB and if something doesnt fit I just skip to the next row compare that and if that doesnt fit I keep going to the next and as you see above the third policeStation is more tolerant they dont care, what happend and where they just take the incident if the offender was GuyB...... so any ideas and tipps how to implement that?

What is the meaning of "history" inside BackgroundSubtractorMOG2?

I'm on OpenCV for java (but that's not relevant I guess). I'm using the BackgroundSubtractorMOG2 class which is (poorly) referenced here. I have read and understood the Zivkovic paper about the algorithm which you can find here.
BackgroundSubtractorMOG2 takes in its constructor a parameter called history. What is it, and how does it influence the result? Could you point me to its reference inside the paper, for example?
From the class source code, line 106, it is said that alpha = 1/history. That would mean that history is namely the T parameter inside the paper, i.e. (more or less) the number of frames that constitute the training set.
However it doesn't seem so. Changing the value in the constructor, from 10 to 500 or beyond, has no effect on the final result. This is what I'm calling:
Mat result = new Mat();
int history = 10; //or 50, or 500, or whatever
BackgroundSubtractorMOG2 sub = new BackgroundSubtractorMOG2(history, 16, false);
for (....) {
sub.apply(frame[i], result);
}
imshow(result); //let's see last frame
It doesn't matter what history I set, be it 5, 10, 500, 1000 - the result is always the same. Whereas, if I change the alpha value (the learning rate) through apply(), I can see its real influence:
Mat result = new Mat();
float alpha = 0.1; //learning rate, 1/T (1/history?)
BackgroundSubtractorMOG2 sub = new BackgroundSubtractorMOG2(whatever, 16, false);
for (...) {
sub.apply(frame[i], result, alpha);
}
imshow(result);
If I change alpha here, result changes a lot, which is understandable. So, two conjectures:
history is not really 1/alpha as the source code states. But then: what is it? how does it affect the algorithm?
history is really 1/alpha, but there's a bug in the java wrapper that makes the history value you set in the constructor useless.
Could you help me?
(Tagging c++ also as this is mainly a question about an OpenCV class and the whole OpenCV java framework is just a wrapper around c++).
It seems clear that alpha = 1 / history (except for some transitory instants). In void BackgroundSubtractorMOG2Impl::apply method:
learningRate = learningRate >= 0 && nframes > 1 ? learningRate : 1./std::min( 2*nframes, history );
You can test if the BackgroundSubtractorMOG2 object is using the history value that you pass in the constructor using the getHistory() method.

Java: Unique 10 digit ID

I need to generate a unique 10 digit ID in Java. These are the restrictions for this ID:
Only Numeric
Maximum 10 digits
Possible to create up to 10 different IDs per second
Has to be unique (even if the application re-starts)
Not possible to save a number in the Database
As fast as possible NOT to add much lattency to the system
The best solution I found so far is the following:
private static int inc = 0;
private static long getId(){
long id = Long.parseLong(String.valueOf(System.currentTimeMillis())
.substring(1,10)
.concat(String.valueOf(inc)));
inc = (inc+1)%10;
return id;
}
This solution has the following problems:
If for any reason there is a need to create more than 10 IDs per seccond, this solution won't work.
In about 32 years this ID could be repeated (This is probably acceptable)
Any other solution to create this ID?
Any other problem I haven't thought of with mine?
Thanks for your help,
This is a small enhancement to yours but should be resilient.
Essentially, we use the current time in milliseconds unless it hasn't ticked since the last id, in which case we just return last + 1.
private static final long LIMIT = 10000000000L;
private static long last = 0;
public static long getID() {
// 10 digits.
long id = System.currentTimeMillis() % LIMIT;
if ( id <= last ) {
id = (last + 1) % LIMIT;
}
return last = id;
}
As it is it should manage up to 1000 per second with a comparatively short cycle rate. To extend the cycle rate (but shorten the resolution) you could use (System.currentTimeMillis() / 10) % 10000000000L or (System.currentTimeMillis() / 100) % 10000000000L.
This may be a crazy idea but its an idea :).
First generate UUID and get a string representation of it with
java.util.UUID.randomUUID().toString()
Second convert generated string to byte array (byte[])
Then convert it to long buffer: java.nio.ByteBuffer.wrap( byte
digest[] ).asLongBuffer().get()
Truncate to 10 digits
Not sure about uniqueness of that approach tho, I know that you can rely on uniqueness of UUIDs but haven't checked how unique are they converted and truncated to 10 digits long number.
Example was taken from JavaRanch, maybe there is more.
Edit: As you are limited to 10 digits maybe simple random generator would be enough for you, have a look into that quesion/answers on SO: Java: random long number in 0 <= x < n range
private static AtomicReference<Long> currentTime = new AtomicReference<>(System.currentTimeMillis());
public static Long nextId() {
return currentTime.accumulateAndGet(System.currentTimeMillis(), (prev, next) -> next > prev ? next : prev + 1) % 10000000000L;
}
What means that it has to be unique? Even across more currently running instances? It break your implementation.
If it must be unique across universe, the best solution is to use UUID as it's mathematically proven identifier generator as it generates unique value per universe. Less accurate number brings you collisions.
When there is only one concurrent instance, you can take current time in millis and solve 10ms problem using incrementation. If you sacrifice proper number of last positions in the number you can get many number within one milliseconds. I would than define the precision - I mean how much unique numbers do you need per seconds. You will solve the issue without any persistence using this approach.

Categories