Alarm Logic
Alarm Logic: Deep Dive
Overview
The Crypto Price Alarm system implements three distinct alarm types, each designed for different trading strategies and monitoring needs. All alarms operate on the same core principle: continuous polling with condition checking.
The Three Alarm Types
1. Target Price Alert
Use Case: Notify when price reaches a specific value
Configuration:
- Target price (in quote currency)
- Direction:
any,fromBelow,fromAbove
Examples:
- BTCUSDT @ $55,000 from below (breakout alert)
- ETHBTC @ 0.055 from above (breakdown alert)
- SOLUSDC @ $100 any direction (proximity alert)
2. % Change from Max/Min
Use Case: Track percentage moves from extremes
Configuration:
- Percentage threshold (e.g., 5%)
- Change type:
downFromMaxorupFromMin
Examples:
- Alert when BTC drops 10% from its recorded high
- Alert when ETH rises 15% from its recorded low
3. % Move in Timeframe
Use Case: Detect significant price movement within a time window
Configuration:
- Percentage threshold (e.g., 3%)
- Direction:
any,up,down - Time value + unit: minutes, hours, days, or “since start”
Examples:
- 5% move (any direction) in 15 minutes (volatility alert)
- 10% up in 2 hours (pump detector)
- 20% down in 3 days (crash alert)
- 8% move since start (session tracker - auto-resets)
Implementation Architecture
Alarm Checking Flow
Alarm State Machine
Alarm Type 1: Target Price
Logic Implementation
Direction Modes Explained
any direction:
- Triggers when price reaches target from either direction
- Use for: Price proximity alerts
fromBelow direction:
- Triggers only when price crosses target going upward
- Use for: Breakout alerts, resistance breaks
- Example: Alert me when BTC breaks $60k resistance
fromAbove direction:
- Triggers only when price crosses target going downward
- Use for: Breakdown alerts, support breaks
- Example: Alert me if BTC falls below $50k support
Visual Representation
Edge Cases
Rapid price oscillation:
Gap in price data:
Alarm Type 2: % Change from Max/Min
Logic Implementation
Max/Min Tracking
Initialization:
Update on every price fetch:
Percentage Calculation Examples
Down from Max:
Up from Min:
Use Cases by Strategy
Profit Protection (downFromMax):
- Set 5% drop alarm to lock in gains
- Monitor pullbacks from local highs
- Stop-loss alternative
Bounce Detection (upFromMin):
- Alert on recovery from local lows
- Identify potential reversal points
- Buy opportunity notification
Persistence Behavior
Max/Min Prices Persist Across Restarts
Important: Max and min prices are saved and persist across browser/app restarts.
JavaScript App:
- Stored in browser’s LocalStorage
- Survives page refresh and browser restart
- Tied to your browser (doesn’t sync across devices)
Python App:
- Stored in
data/crypto_data_binance.jsonon server - Survives server restarts
- Shared across all connected clients
To reset max/min values: Remove the trading pair and re-add it. The max/min will restart from the current price.
Example: If you added BTCUSDT when BTC was $45,000, and it later reached $65,000 (new max), that $65,000 max persists even if you close and reopen the app. Your “10% down from max” alarm will still use $65,000 as the reference.
Resetting max/min:
Alarm Type 3: % Move in Timeframe
Logic Implementation
Time Unit Conversion
Timeframe Types
Fixed Timeframes (minutes, hours, days)
15-minute window:
2-hour window:
“Since Start” Timeframe
Special behavior:
- Compares to price when alarm was created
- Auto-resets after triggering (unique to this alarm type)
- Continuous monitoring for recurring moves
Lifecycle:
Direction Modes
any direction:
up direction:
down direction:
Price History Requirements
24-Hour Price History Requirement
Timeframe alarms require historical price data to function.
How it works:
- Price data collected every 15 seconds (one data point per update)
- Maximum retention: 24 hours (5,760 data points total)
- Older data automatically purged to save memory
Important implications:
Fresh start: When you first add a pair, there’s no history yet
- A “2-hour timeframe” alarm won’t work until 2 hours of data collected
- A “1-day timeframe” alarm won’t work until 24 hours have passed
Insufficient history: If you try to set a 4-hour alarm but only have 1 hour of history, the alarm will remain silent until enough data accumulates
App/browser restart:
- JavaScript app: History persists in LocalStorage
- Python app: History persists in JSON file
- Both: History survives restarts, no need to wait again
“Since start” alarms: These work immediately (they use the alarm creation time as the reference, not historical data)
Recommendation: For best results, let the app run for a few hours before setting long timeframe alarms.
Storage efficiency:
Insufficient history handling:
Examples with Calculations
Example 1: 5% in 30 minutes
Example 2: 10% any direction in 2 hours
Example 3: 3% down in 1 day
Cross-Alarm Coordination
Multiple Alarms on Same Pair
Alarms are independent - each checks conditions separately:
Alarm Priority
No priority system - all alarms have equal weight:
- Multiple alarms can trigger simultaneously
- Modal shows first triggered alarm
- User dismisses one by one
Triggered State Management
Performance Optimizations
Efficient Alarm Checking
Price History Pruning
Memory Considerations
Per pair:
- Current price: 8 bytes
- Max/min prices: 16 bytes
- Price history (24h): ~46KB (5760 points × 8 bytes)
- Alarms: ~200 bytes each
For 10 pairs with 5 alarms each:
- Total memory: ~500KB
Testing Strategies
Unit Testing Alarm Logic
Integration Testing
Manual Testing Scenarios
- Rapid triggering test: Set very low thresholds and verify single trigger
- Direction test: Verify
fromBelowdoesn’t trigger when price comes from above - History test: Create timeframe alarm, wait for sufficient data
- Reset test: Verify “since start” alarms reset after trigger
Common Pitfalls & Solutions
Pitfall 1: Alarm Triggers Multiple Times
Problem: Alarm fires on every price check
Solution: Use triggered flag
Pitfall 2: Insufficient Price History
Problem: Timeframe alarm fails silently
Solution: Validate history length
Pitfall 3: Floating-Point Precision
Problem: Percentage calculations drift
Solution: Use threshold comparison
Practical Alarm Examples
Real-World Trading Strategies
Copy These Proven Alarm Configurations
These examples are based on actual trading strategies. Adjust thresholds based on your risk tolerance and market conditions.
For BTCUSDT (Stablecoin Pair)
Breakout Detection:
- Type: Target Price
- Target: $60,000
- Direction: From Below
- Use Case: Alert when Bitcoin breaks through resistance
Momentum Confirmation:
- Type: % Move in Timeframe
- Percentage: 3%
- Direction: Up
- Timeframe: 30 minutes
- Use Case: Catch strong upward moves early
Stop Loss Protection:
- Type: % Change from Max/Min
- Percentage: 10%
- Change Type: Down from Max
- Use Case: Protect profits when price drops from peak
Crash Detection:
- Type: % Move in Timeframe
- Percentage: 15%
- Direction: Down
- Timeframe: 1 day
- Use Case: Alert on significant daily drops
Short-term Volatility:
- Type: % Move in Timeframe
- Percentage: 5%
- Direction: Any
- Timeframe: 2 hours
- Use Case: Detect unusual price action
Session Tracker:
- Type: % Move in Timeframe
- Percentage: 8%
- Direction: Any
- Timeframe: Since Start
- Use Case: Get alerted on every 8% move (auto-resets)
For ETHBTC (Crypto-to-Crypto Pair)
Breaking Resistance:
- Type: Target Price
- Target: 0.06
- Direction: From Below
- Use Case: ETH gaining strength vs BTC
Support Level:
- Type: Target Price
- Target: 0.05
- Direction: From Above
- Use Case: ETH weakening vs BTC
Ratio Recovery:
- Type: % Change from Max/Min
- Percentage: 5%
- Change Type: Up from Min
- Use Case: ETH bottoming out vs BTC
Ratio Weakness:
- Type: % Change from Max/Min
- Percentage: 5%
- Change Type: Down from Max
- Use Case: ETH losing ground vs BTC
Quick Ratio Spike:
- Type: % Move in Timeframe
- Percentage: 2%
- Direction: Any
- Timeframe: 15 minutes
- Use Case: Catch rapid ratio changes
Trending Move:
- Type: % Move in Timeframe
- Percentage: 10%
- Direction: Up
- Timeframe: 4 hours
- Use Case: Identify ETH outperformance trends
Swing Trading:
- Type: % Move in Timeframe
- Percentage: 5%
- Direction: Any
- Timeframe: Since Start
- Use Case: Continuous swing alerts (resets on trigger)
Multi-Alarm Strategy Example
Conservative BTC Monitoring Setup (3 alarms):
Target Price: $55,000 from below
- Purpose: Breakout confirmation
% Change from Max: 10% down
- Purpose: Stop-loss trigger
% Move in Timeframe: 5% in 30 minutes (any direction)
- Purpose: High volatility warning
Rationale: This combination covers breakouts (bullish), risk management (bearish), and volatility detection (neutral).
Tips for Setting Effective Alarms
Alarm Best Practices
Don’t over-alarm: Too many alarms = alarm fatigue. Start with 2-3 per pair.
Account for volatility:
- High volatility assets (small caps): Use wider thresholds (5-10%)
- Low volatility assets (BTC/ETH): Narrower thresholds work (2-5%)
Timeframe selection:
- Day trading: 15-minute to 2-hour timeframes
- Swing trading: 4-hour to 1-day timeframes
- Long-term: Use % from max/min instead of timeframes
Test before relying: Use the “Test Alarm” button to verify audio works
Direction matters:
- Use “from below” for breakouts
- Use “from above” for breakdowns
- Use “any” for proximity alerts
“Since start” alarms: Great for continuous monitoring, but expect frequent triggers in volatile markets
Next Steps
- Explore API Integration for price fetching details
- See Implementations for language-specific alarm code
- Check DevOps for testing and deployment strategies