How To Avoid Many If During Programming For Calgo
Hello everybody,
today I want to write few words about how to avoid nested ifs if you program for cAlgo.
Recently I've got following request ( code is modified in order to protect privacy of customers idea ):
buy in following case:
- price is above moving average 20
- price is above moving average 30
- stochastic is above 40
- each of indciators from 1 - 3 can be turned on/off
As example consider following case:
if( movingAverage30On && MarketSeries.Low[1] > longMa.Result[1]) { if(movingAverage20On && MarketSeries.Low[1] > shortMa.Result[1]) { if(stochasticOn && _stochastic.PercentD[1] > 40) { //Buy } } } if(movingAverage20On && MarketSeries.Low[1] > shortMa.Result[1]) { if( movingAverage30On && MarketSeries.Low[1] > longMa.Result[1]) { if(stochasticOn && _stochastic.PercentD[1] > 40) { //Buy } } }
And that is pretty confusing. The more indicators you want to make on/off, the bigger tree you have to make. In my case it was around 10 different trees. 10 trees is of course not forest, but still pretty decent way to loose way. So I had to think how to modify my solution to become more flexible and readable.
So I've applied ternary logic for my situation. As usually if people hear about ternary logic in C#, they think about bool something = a ==b ? oneResult : anotherResult;
But I mean little bit different solution. In C# bool can have two values: true and false. But bool ? or Nullable<bool> can have three values: null, true, false.
So, in order to use this cool feature which appeared in C# 2.0 or from visual studio 2005, I've made the following logic.
In cAlgo robot can make three decisions with regard to opening positions: buy, sell, abstain.
For simplicity sake I'll describe my solution from standpoint of buy ( sell is mirorly different ).
cAlgo robot can make two decisions: buy, not buy.
Indicator can have two positions: on/off.
So, for each indicator I've wrote functions similar to this:
bool? IsBuyConditionForStochastic() { if (OnStochastic)// OnStochastic stands for Is stochastic in true or in false { bool isBuyStochastic = _stochastic.PercentD[1] > 40; return isBuyStochastic; } return null; }
and following code for method, which decides to buy or not buy:
bool IsBuySituation()
{
bool result = false;
.
.
.
if (IsBuyConditionForStochastic().HasValue) { result = result && IsBuyConditionForStochastic().Value; if (!result) { return result; } }
.
.
.
return result;
}
So, let's assume that user decided to turn stochastic to on position. Then following logic will be applied:
- OnStochastic will receive value true
- Method IsBuyConditionForStochastic will return true or false
- result variable will receive value from function IsBuyConditionForStochastic
- that value will be returned if it is false, or will be used in analogical way for taking into account other parameters
Hope it will help somebody with organizing his code and avoid forest of ifs