Ternary Logic Library is Now Feature-Rich:

Basic ternary operations (AND, OR, NOT, XOR, Consensus)

Balanced ternary arithmetic (addition, subtraction, multiplication)

Advanced signal processing (smoothing, trend strength, majority filtering)

Conversion utilities (decimal ↔ ternary, string representation)

Market-specific functions (bias detection, trend analysis)
Why This Matters to Other MT5 Coders:

Cleaner Code: Ternary logic eliminates complex nested if-else statements

Better Decisions: Three-state logic matches market reality (up/down/neutral) better than binary

Visual Clarity: Indicators become self-documenting with clear ternary states

Performance: Reduced computational overhead compared to complex binary logic trees

Innovation: Most traders are still stuck in binary thinking - this is a competitive advantage
For MT5 developers who are looking to:

Simplify complex trading logic

Create more responsive indicators

Develop clearer trend analysis systems

Build more robust expert advisors
Code: Select all
//+-------------------------------------------------------\!/--------------------------------------------------------+
//| [Knowledge of the ancients] (ò ó) [TernaryLogic.mqh] |
//+-------------------------------------------------o0o---(_)---o0o--------------------------------------------------+
//+------------------------------------------------------------------+
//| TernaryLogic.mqh |
//| Advanced library for balanced ternary logic operations (-1, 0, +1)|
//| Inspired by Douglas W. Jones' Standard Ternary Logic |
//| Includes Wikipedia balanced ternary operations |
//| |
//| USAGE: |
//| #include <TernaryLogic.mqh> |
//| int signal = TernaryAND(TRIT_1, TRIT_T); // Returns TRIT_T |
//| |
//| WHY TERNARY? |
//| - Markets have 3 states: Bullish(1), Bearish(-1), Neutral(0) |
//| - Eliminates complex binary condition chains |
//| - More intuitive representation of market uncertainty |
//+------------------------------------------------------------------+
#ifndef TERNARY_LOGIC_MQH
#define TERNARY_LOGIC_MQH
// **TERNARY CONSTANTS** - Use these instead of magic numbers!
#define TRIT_T -1 // True/Negative/Bearish (Think: "T" for True negative)
#define TRIT_0 0 // Unknown/Neutral/Consolidation (The power of maybe!)
#define TRIT_1 1 // False/Positive/Bullish (Think: "1" for Positive)
// **SECTION 1: BASIC TERNARY OPERATORS**
// Use these for simple signal combination and logic gates
//------------------------------------------------------------------
int TernaryNOT(int a) {
// Inverts signal: Bullish<>Bearish, Neutral stays Neutral
// Perfect for trend reversal detection
return -a;
}
int TernaryAND(int a, int b) {
// Conservative: Returns weakest signal (pessimistic combination)
// Use when BOTH conditions must agree for confirmation
// Example: Trend AND Momentum must both be bullish
return MathMin(a, b);
}
int TernaryOR(int a, int b) {
// Aggressive: Returns strongest signal (optimistic combination)
// Use when EITHER condition is sufficient for action
// Example: Price action OR Volume signals breakout
return MathMax(a, b);
}
int TernaryXOR(int a, int b) {
// Returns signal only when inputs DIFFER (conflict detection)
// Perfect for divergence detection between indicators
if (a == b) return TRIT_0;
return (a == TRIT_0) ? b : a;
}
int TernaryConsensus(int a, int b) {
// Returns value only if inputs AGREE (Jones' ⊠ operator)
// Use for filtering noisy signals - only act on consensus
return (a == b) ? a : TRIT_0;
}
// **SECTION 2: BALANCED TERNARY ARITHMETIC**
// Use these for mathematical operations on ternary values
//------------------------------------------------------------------
int TernaryAdd(int a, int b) {
// Balanced ternary addition: a + b
// Use for accumulating signals or weighted combinations
if (a == TRIT_0) return b;
if (b == TRIT_0) return a;
if (a == b) return -a; // T+T = 1, 1+1 = T
return TRIT_0; // T+1 = 0, 1+T = 0
}
int TernarySubtract(int a, int b) {
// Balanced ternary subtraction: a - b
// Use for signal differentials or change detection
return TernaryAdd(a, TernaryNOT(b));
}
int TernaryMultiply(int a, int b) {
// Balanced ternary multiplication: a * b
// Use for signal amplification or damping
if (a == TRIT_0 || b == TRIT_0) return TRIT_0;
return (a == b) ? TRIT_1 : TRIT_T;
}
// **SECTION 3: TERNARY COMPARISON & LOGIC**
// Use these for decision-making and condition checking
//------------------------------------------------------------------
int TernaryCompare(int a, int b) {
// Returns: -1 if a < b, 0 if a == b, 1 if a > b
// Use for signal strength comparison or ranking
if (a < b) return TRIT_T;
if (a > b) return TRIT_1;
return TRIT_0;
}
bool TernaryEquals(int a, int b) {
// Returns true if signals are identical
// Use for confirmation between timeframes or indicators
return a == b;
}
bool TernaryGreater(int a, int b) {
// Returns true if a is more bullish than b
// Use for momentum comparison or strength assessment
return a > b;
}
// **SECTION 4: SIGNAL PROCESSING & ANALYSIS**
// Use these for cleaning and analyzing ternary signal streams
//------------------------------------------------------------------
int TernaryMajority(int a, int b, int c) {
// Returns the majority value (median) of three trits
// PERFECT for filtering noisy signals - requires 2/3 agreement
// Example: Use across 3 timeframes or 3 different indicators
if ((a == b) || (a == c)) return a;
if (b == c) return b;
return TRIT_0; // No majority found = uncertainty
}
int TernarySmooth(int &signalSeries[], int period) {
// Smooth ternary signal using moving majority
// Use to reduce noise and identify persistent trends
int size = ArraySize(signalSeries);
if (size < period) return TRIT_0;
int window[];
ArrayResize(window, period);
ArrayCopy(window, signalSeries, 0, size - period, period);
return TernaryMajority(window[0], window[1], window[2]);
}
int TernaryTrendStrength(int &signalSeries[], int lookback) {
// Measure trend strength based on signal consistency
// Returns: Strong trend signal, Weak trend (0), or Counter-trend
// Use to qualify signals - only trade strong, consistent moves
int size = ArraySize(signalSeries);
if (size < lookback) return TRIT_0;
int consistentCount = 0;
int firstSignal = signalSeries[size - lookback];
for (int i = size - lookback + 1; i < size; i++) {
if (signalSeries[i] == firstSignal) {
consistentCount++;
}
}
// Convert consistency to ternary strength
double ratio = (double)consistentCount / (lookback - 1);
if (ratio >= 0.67) return firstSignal; // Strong trend
if (ratio >= 0.34) return TRIT_0; // Weak trend
return TernaryNOT(firstSignal); // Counter-trend
}
// **SECTION 5: MARKET-SPECIFIC APPLICATIONS**
// Ready-to-use functions for trading applications
//------------------------------------------------------------------
int GetTernaryBias(double &HighBuffer[], double &LowBuffer[], int rates_total, int MaxBars) {
// Detect market bias from zigzag/swing data
// Returns: 1 (Bullish), -1 (Bearish), 0 (Neutral)
// Use for directional bias in trading systems
if (rates_total <= 0 || ArraySize(HighBuffer) < rates_total || ArraySize(LowBuffer) < rates_total)
return TRIT_0;
if (HighBuffer[0] != 0) return TRIT_1;
if (LowBuffer[0] != 0) return TRIT_T;
int maxCheck = MathMin(rates_total, MaxBars);
for (int i = 1; i < maxCheck; i++) {
if (HighBuffer[i] != 0) return TRIT_1;
else if (LowBuffer[i] != 0) return TRIT_T;
}
return TRIT_0;
}
int GetTernaryBiasAdvanced(double &HighBuffer[], double &LowBuffer[], int rates_total, int MaxBars) {
// Enhanced bias detection with ternary smoothing
// More robust but slightly slower than basic version
// Use for higher timeframe analysis or smoother signals
if (rates_total <= 0 || ArraySize(HighBuffer) < rates_total || ArraySize(LowBuffer) < rates_total)
return TRIT_0;
int ternarySignals[];
ArrayResize(ternarySignals, MathMin(rates_total, MaxBars));
// Convert price action to ternary signals
for (int i = 0; i < ArraySize(ternarySignals); i++) {
if (HighBuffer[i] != 0) {
ternarySignals[i] = TRIT_1; // Bullish swing
} else if (LowBuffer[i] != 0) {
ternarySignals[i] = TRIT_T; // Bearish swing
} else {
ternarySignals[i] = TRIT_0; // No swing
}
}
return TernarySmooth(ternarySignals, 3); // Smoothed majority
}
// **SECTION 6: UTILITY & CONVERSION FUNCTIONS**
// Use these for data transformation and debugging
//------------------------------------------------------------------
int ConvertToTernary(int oldSignal) {
// Convert from 0,1,2 system to -1,0,1 system
// Use for migrating existing indicators to ternary logic
switch (oldSignal) {
case 0: return TRIT_0;
case 1: return TRIT_1;
case 2: return TRIT_T;
default: return TRIT_0;
}
}
string TritToString(int trit) {
// Convert trit to human-readable symbol
// Use for debugging, logging, or display purposes
switch(trit) {
case TRIT_T: return "T";
case TRIT_0: return "0";
case TRIT_1: return "1";
default: return "?";
}
}
bool IsTernaryValid(int a) {
// Validate that a value is a proper trit
// Use for input validation and error checking
return (a == TRIT_T || a == TRIT_0 || a == TRIT_1);
}
// **SECTION 7: ADVANCED ENCODING/DECODING**
// For mathematical applications and number representation
//------------------------------------------------------------------
string EncodeTernaryNumber(int decimalValue) {
// Encode decimal number as balanced ternary string
// Advanced: Use for compact number representation
if (decimalValue == 0) return "0";
string result = "";
int value = MathAbs(decimalValue);
bool negative = (decimalValue < 0);
while (value > 0) {
int remainder = value % 3;
value = value / 3;
if (remainder == 0) {
result = "0" + result;
} else if (remainder == 1) {
result = "1" + result;
} else {
result = "T" + result;
value++; // Carry over
}
}
if (negative) {
string negated = "";
for (int i = 0; i < StringLen(result); i++) {
string ch = StringSubstr(result, i, 1);
if (ch == "1") negated += "T";
else if (ch == "T") negated += "1";
else negated += "0";
}
return negated;
}
return result;
}
#endif
//+------------------------------------------------------------------+
/*
Lightbulb Moments for Fellow Coders:
"Oh, THAT's how you avoid nested if-else hell!" - Ternary logic simplifies complex decision trees
"So THAT's how you quantify market uncertainty!" - The TRIT_0 state captures "maybe" perfectly
"Now I see how to filter noisy signals!" - TernaryMajority requires consensus before acting
"This makes multi-timeframe analysis intuitive!" - Combine signals from different timeframes cleanly
"Finally, a way to measure trend strength properly!" - TernaryTrendStrength quantifies conviction
*/
Here is the latest Library file along with a few updated Ternary Logic Indicators to try out...
Enjoy!
best,
Xard777