I am wondering if a state machine is a good pattern for this case.
Say I have the following Triggers:
enum Trigger
{
None,
RSIGt70,
RSILt30,
TrendUp,
TrendDown
}
And I have the following States
enum State
{
Flat,
ShortUnit1,
ShortUnit2,
LongUnit1,
LongUnit2
}
var position= new StateMachine<State, Trigger>(State.Flat);
position.Configure(State.Flat)
.Permit(Trigger.RSIGt70, State.Flat);
.Permit(Trigger.TrendingUp, State.Flat);
.Permit(Trigger.RSIGt70, State.ShortUnit1);
.Permit(Trigger.TrendingUp, State.ShortUnit1);
I am trying to get away from if statements and replace trading logic with a state machine. Not sure it works because it may be a confluence of triggers that transitions from one state to another. The questions is, how do State Machines deal with this situation? Are they rich enough or do I have to use a standard Turing Machine, i.e., if
statements with memory?
The problem is that two+ (in this case) conditions have to be true in order to transition from flat to one of the Long or Short positions.
So what I am saying is e.g., if both RSI > 70 and TrendingUp, then transition into a short position. Or if TrendingUp and RSI > 70, then transition into a short position. Since it doesn't matter which order the two conditions occurred. Vice versa for the other possible conditions. But if only one condition is true, then no position is triggered. But if I am in a state, how do I know if I came from None
which doesn't trigger a position, or from the other conditions that does trigger a position?
If the system becomes more complicated, I am trying to avoid error prone if/else statements. Not sure if this can be handled with a FSM since it depends on the history of how the current state came to be through time.
Theoretically, the finite automaton model is capable of modeling your situation. Whether it's practical or not for you compared to if
statements is up to you.
Basically, what you're describing is a machine where the triggers are subsets of your set of triggers. Therefore, you will need to use immutable collections of Trigger
, rather than just Trigger
, to specify transitions in your machine. For instance, to model the rule "transition from state one to two if at least two of triggers A, B, and C occur", you would need to define three transitions:
So, is it possible? It should be, provided that there's some collection type that StateMachine
will accept as a trigger type. Is it better than the alternative? Your call.
Note also - this could result in a nondeterministic machine, which may not be supported (not sure of the details of StateMachine). The good news is that you can always convert a nondeterministic machine into a deterministic one, so if you find yourself in that situation, just look up the details and rework your machine.