AYILON · Automated Trading System
Trading Bot
Logic Guide
Complete documentation of how the AYILON bot analyzes markets, enters positions, manages risk, and exits trades.
01System Overview2
02Market Analysis — S/R Level Detection2
03Level Grading — S / A / B Tiers3
04Volume Zone Analysis4
05Trading Strategies4
06Position Sizing — Fixed Fractional6
07Entry Safety Rules6
08Take Profit — Partial Close Strategy6
09Stop Loss — Equity-Based Protection7
10Daily Loss Limit7
11Full Trade Lifecycle (Example)8
12Default Parameters9
13Demo Mode9
Exchange OKX (Perpetual Swaps)
Infrastructure Cloudflare Workers
Execution Frequency Every minute (cron)
Version 2.0
01
System Overview

AYILON is a fully automated perpetual swap trading bot running on Cloudflare Workers. Every minute, a scheduled cron job wakes the bot, fetches live market data, runs the analysis pipeline, and places orders via the OKX API if conditions are met.

1
Cron Trigger (every minute)
Cloudflare Workers scheduled event fires. Bot reads config from KV store and checks if running = true.
2
Daily Loss Gate
If today's realized loss already exceeds the user-set limit, bot halts immediately and sends alert.
3
S/R Level Detection
Fetches 100 × 1H candles and 100 × 4H candles. Detects support/resistance levels with recency-weighted touch counting.
4
Level Grading + Volume Confirmation
Grades each level S/A/B based on timeframe confluence. Adds volume profile zones that overlap with S/R levels (±1%).
5
Entry Signal Check (5m candles)
Checks if current price is touching a level, 3-candle momentum confirms direction, and SL distance is 3–6%.
6
Order Placement
If all conditions pass, places a market order via OKX API. Records entry in KV state.
7
SL / TP Monitoring (every cron)
On every tick: checks if price has hit TP (→ 50% partial close, SL to break-even) or SL (→ full close).
02
Market Analysis — S/R Level Detection

The bot fetches 100 candles each from the 1H and 4H timeframes simultaneously. It scans every high and low price across these candles to identify support and resistance levels.

Touch Counting Algorithm

For each candidate price level, the bot counts how many candles touched it. A candle "touches" a level if its high or low is within a ±0.3% tolerance band of that level.

Recency Weighting
A level's required touch count depends on how recent those touches are. This reflects the real-world observation that recent price reactions carry more weight than old ones.
Age of touches Required touches to be valid Reasoning
Within last 20 candles 2 touches Market recently respected this level — likely still active
Older than 20 candles 3 touches Needs more confirmation since it hasn't been tested recently
Older than 100 candles Ignored Too stale — market structure has likely changed

Level Deduplication

After collecting all valid levels, nearby duplicates are merged. Any two levels within 0.5% of each other are considered the same zone. The top 4 supports (below price) and top 4 resistances (above price) are kept per timeframe.

Final Level Pool

After grading and merging 1H + 4H levels, the final set is capped at 5 supports + 5 resistances, sorted by proximity to current price.

03
Level Grading — S / A / B Tiers

Every detected level is assigned a grade based on how many timeframes confirm it and how strong the touch history is. The grade is logged with each trade so performance by tier can be tracked over time.

S급 (S Tier)
S
Level appears on both 1H and 4H within 0.5% tolerance. Highest confluence. Strongest signal.
A급 (A Tier)
A
4H level with 4+ touches, OR any level with at least 1 recent touch (within 20 candles).
B급 (B Tier)
B
1H-only level, older touches, minimum 2 confirmations. Lower confidence — still traded, logged separately.

Grading Logic

ConditionGradeAction
Found on 1H and 4H (within 0.5%) S Trade — highest priority
4H only, 4+ total touches A Trade
Any level with ≥1 touch in last 20 candles A Trade
1H only, old touches, exactly 2 touches B Trade — lower confidence
Log Format
Each trade log shows the grade: LONG #1/3 @ 105000 | [S급] L:104800 | SL:101200 | TP:108500 | sz:0.0042
04
Volume Zone Analysis

On top of price-based S/R, the bot builds a volume profile from 4H candles to find high-volume price clusters where the market has historically spent significant time and energy.

How It Works

  1. The full 4H price range (100 candles) is divided into 50 equal buckets.
  2. Each candle's volume is distributed proportionally across the buckets it spans.
  3. Buckets with volume ≥ 2× the average are flagged as high-volume zones.
  4. Each zone is classified as support (below current price) or resistance (above).
Noise Filter — Critical Rule
Volume zones are only included if they fall within ±1% of an existing S/R level. This prevents the bot from chasing isolated volume spikes that have no price structure backing them.

After filtering, up to 3 volume-confirmed supports + 3 resistances are merged into the main level pool. These volume-backed S/R levels carry extra weight in the final signal decision.

05
Trading Strategies

AYILON supports 10 trading strategies. Your subscription plan determines which are available. All strategies share the same DCA entry logic, position sizing, and risk management framework described in sections 06–13.

#StrategyDirectionKey SignalRiskPlan
1RSI Oversold DCA LongLong OnlyRSI ≤ 30LowBasic+
2MA Support DCALong OnlyMA alignment + price touches MALowBasic+
3S/R BounceLong / Short5m price touches S/R level + momentumMediumBasic+
4MA Crossover + RSILong / Short10/34 MA cross + RSI 65↑ / 35↓MediumMid+
5Bollinger Band Mean ReversionLong / ShortPrice touches lower/upper BB bandMediumMid+
6Breakout + VolumeLong BiasPrice breaks resistance + volume ≥ 2× avgMediumMid+
7MA Ribbon LongLong Only6 MAs aligned bullish + recent N-bar low holdsLowMid+
8MACD DivergenceLong / ShortPrice vs MACD divergence confirmedHighPremium
9Funding Rate ContrarianLong / ShortFunding rate ≥ +0.10% → short; ≤ −0.05% → longHighPremium
10ATR Trend FollowingLong BiasADX > 25 + price pulls back 1 ATR in uptrendMediumPremium

Strategy 1 — RSI Oversold DCA Long

Enters a long position when the 14-period RSI on the user-selected timeframe drops to or below 30 (oversold). DCA entries are placed at N-equal intervals between the first entry price and the swing low (SL). Take profit targets the nearest resistance level above entry. Short side (RSI ≥ 70) is disabled — momentum can sustain above 70 for extended periods in bull markets.

Strategy 2 — MA Support DCA

Requires at least 3 of 6 moving averages (10, 20, 50, 100, 200 SMA + 34 EMA) to be in bullish alignment (price above all selected MAs). Enters long when the 5m candle wicks down to the nearest MA and closes above it — a pullback-to-MA bounce. Long only; no short entries.

Strategy 3 — S/R Bounce (Default)

The built-in default strategy. Detects support and resistance levels from 1H/4H candles using swing highs/lows and volume profile. Enters long when the 5m price touches a support level with a bullish bounce candle. Enters short when a bearish impulse candle with above-average volume is followed by a 50% retracement to resistance. SL = swing low (long) / swing high (short) of the 3 preceding 5m candles.

Entry Conditions — All 3 Required
Price within ±0.4% of an S/R level  |  Momentum direction confirms (bounce for long, rejection for short)  |  SL distance 1–7% from entry (filters noise and overly wide stops)

Strategy 4 — MA Crossover + RSI Confirmation

Long: 10 EMA crosses above 34 EMA (golden cross) AND RSI ≥ 65 on the signal candle. Short: 10 EMA crosses below 34 EMA (death cross) AND RSI ≤ 35. DCA entries are spaced between the signal candle price and the swing low/high of the preceding 3 candles on the 5m chart. Note: RSI condition is checked at the candle that closes the crossover — if RSI has not yet reached the threshold, the bot waits for confirmation on the next candle.

Strategy 5 — Bollinger Band Mean Reversion

Uses a 20-period BB with 2 standard deviations. Enters long when the 5m candle closes below the lower band and the next candle closes back inside the band (re-entry confirmation). Enters short on the mirror condition at the upper band. Trend filter: long entries are skipped when the daily trend is strongly bearish (price below 200 SMA).

Strategy 6 — Breakout + Volume Confirmation

Identifies the 20-period resistance level on the 1H chart. Enters long when a 5m candle closes above this level with volume ≥ 2× the 20-period average volume. The broken resistance becomes the first DCA reference price. SL = candle low of the breakout bar. Long-biased; short breakdowns available on Premium with an additional RSI filter.

Strategy 7 — MA Ribbon Long

Requires 6 MAs (10, 20, 34, 50, 100, 200) to be in full bullish alignment (each MA above the next longer one). Enters long when price touches the shortest MA (10) in the ribbon and the last 3 candles on 5m show a pullback. This strategy only fires in confirmed strong uptrends. Long only.

Strategy 8 — MACD Divergence

Detects bullish divergence (price makes lower low, MACD histogram makes higher low) for long entries, and bearish divergence for shorts. Divergence is confirmed over the last 10 candles on the user-selected timeframe. Requires an RSI filter (RSI > 40 for longs, RSI < 60 for shorts) to avoid divergence trades in strongly trending markets.

High Risk
Divergence can persist for many candles before resolving. Use conservative DCA counts (2–3 entries) and smaller position sizes with this strategy.

Strategy 9 — Funding Rate Contrarian

Perpetual swap funding rates reveal market sentiment. When the funding rate exceeds +0.10% per 8h (the market is heavily long), the bot fades the crowd with a short entry. When it drops below −0.05% (heavily short), it enters long. This strategy is checked once per funding interval and does not use 5m signal detection.

High Risk
Funding rates alone do not determine direction. Extreme funding can continue for days in trending markets. Combine with a trend filter or use small position sizes.

Strategy 10 — ATR Trend Following

Requires ADX > 25 (strong trend confirmed) on the 1H chart and price to be in an uptrend (above 50 SMA). Enters long when price pulls back by exactly 1 ATR from the recent high and starts recovering. SL = entry minus 1.5 ATR. Long-biased; short entries require ADX > 30 and price below 50 SMA.

06
Position Sizing — Fixed Fractional

AYILON uses a Fixed Fractional position sizing model. You define what percentage of your equity to risk per trade, and the bot calculates contract size accordingly. This keeps risk consistent regardless of account balance changes.

Risk Per Trade
2%
Default. Amount of equity you are willing to lose if the SL hits on entry #1.
Daily Loss Limit
2%
Bot pauses for the day once cumulative realized + floating loss reaches this level.
DCA Entries
3
User-configured. Each entry is equally spaced between first entry price and SL.

DCA Entry Spacing — N-Equal-Parts

Instead of a fixed price interval between DCA entries, AYILON divides the zone between the first entry price and the stop loss into N equal parts. This guarantees all entries stay within the valid trade zone regardless of how far or close the SL is.

entry_gap = (first_entry_price − SL_price) ÷ numEntries
entry[i] = first_entry_price − (entry_gap × i)

Example (Long, 3 entries): First entry at 100,000, SL (swing low) at 97,000. Gap = 1,000. Entries: 100,000 → 99,000 → 98,000. SL: 97,000.

Entry Sizing Modes

ModeHow it worksBest for
Equal Each entry gets identical capital: riskBudget / numEntries Default — safe and predictable
Martingale Each subsequent entry multiplies by the configured factor: base × factor^(n−1) Aggressive average improvement — significantly higher risk
Martingale Warning
At 2× multiplier and 3 entries, total capital used is 7× the first entry size. At 4 entries it is 15×. Ensure your account has sufficient balance to cover all planned entries, or the final DCA order may fail to fill.
Risk Cap
Regardless of settings, no single entry will exceed 40% of equity. If the calculated size exceeds this cap, the bot reduces it and logs a warning.
07
Entry Safety Rules

Rule 1 — No Direction Flip

If the bot already holds an open position in one direction (e.g., LONG), it will never open a SHORT until that position is fully closed. This prevents being caught on both sides of the market simultaneously.

Rule 2 — Maximum Entry Count

The bot tracks how many entries have been placed in the current setup. Once the user-configured numEntries limit is reached (default: 3), no further entries are allowed for this setup.

Rule 3 — DCA Zone Containment

All DCA entries are pre-calculated at signal time and must fall between the first entry price and the stop loss level. The bot will not place an entry at or beyond the SL price. If the current market price is already below a scheduled entry level when that cron tick fires, that entry is skipped.

entry[i] = first_entry − ((first_entry − SL) ÷ numEntries) × i
Why This Matters
Spacing entries across the zone between the first entry and SL keeps all DCA purchases within the structured trade idea. If the SL triggers, the max loss is bounded regardless of how many entries were filled. Entries never chase price below the invalidation level.
08
Take Profit — Half-Position Close Strategy
Key Concept — "반 익절" explained
"50%"는 수익률이 아닙니다 — 포지션 수량의 절반을 청산하는 것입니다.

예: 0.01 BTC 롱 → 다음 저항선 도달 → 0.005 BTC 청산 (나머지 0.005 BTC는 계속 보유).
TP 트리거는 "50% 수익"이 아니라 다음 S/R 레벨 도달입니다.
이동폭은 현물(spot) 기준이며 보통 3~8%. 5배 레버리지 적용 시 실제 포지션 수익률은 15~40%입니다.

TP Level Selection

TP is the nearest structural level in the trade direction — not a fixed profit percentage.

What Happens on TP Hit

1
Close half the position size (반 익절)
Bot places a market order to close exactly half the total size held. e.g. 0.01 BTC → sell 0.005 BTC at the TP level. Profit is locked in on this half.
2
SL Moves to Average Entry (본절)
Stop loss is moved to the weighted average entry price across all entries. If price pulls back to this level, the remaining half closes at break-even — no loss.
3
Remaining Half Rides Free
No fixed TP for the second half. It stays open until the break-even SL is hit, capturing any further move beyond the first level.
The Logic
Enter at support with a tight SL (3–6%). Price bounces to the next resistance → close half, lock profit. If it pulls back to your average entry → close the rest at break-even (zero loss). If it keeps going → ride the second half for free. Worst case: small profit on the first half, zero on the second.
Break-even SL = (Σ entry_price × entry_size) / Σ entry_size
09
Stop Loss — Equity-Based Protection

The bot uses an equity-based loss mechanism rather than a traditional price-level stop order. Instead of setting a fixed SL price at entry, the bot continuously monitors the combined impact of today's realized losses and current floating losses against your configured loss limit.

How the Check Works

On every cron tick, after all N entries are filled, the bot calculates:

total_loss_pct = daily_realized_loss_pct + floating_loss_pct

If total_loss_pct ≥ loss_limit → close all open positions immediately and cancel any pending TP algo orders.

Why Equity-Based (Not Price-Based)

With multi-entry DCA, the average entry price shifts with each new entry. A price-based SL set at entry #1's 5m candle low becomes irrelevant when entry #3 is placed at a significantly lower price. An equity-based loss limit is cleaner: it accounts for all entries together, plus any losses already realized earlier today.

What Happens When Stop Triggers

1
Close All Positions
Bot calls OKX close-position API for the full open position. Market order executes at current price.
2
Cancel TP Algo
Any pending OKX algo TP order is cancelled via the algo order cancel API.
3
Update Daily Loss Tracker
Realized loss from this position is added to today's daily loss counter in KV store. Position state is cleared.
4
Re-entry Allowed on Next Signal
No cooldown period. When the next valid S/R signal appears, the bot can enter a new trade immediately — provided the daily loss gate (Section 10) has not been triggered.

Key Timing Rule

The stop check is only active after all N entries are filled. Before the full position is built, checking the loss limit would be premature — the position is still being averaged in and a partial floating loss during entry is normal.

No Re-entry Cooldown
After a stop trigger, the bot immediately resumes looking for new signals. The equity-based stop is a position protection tool — not a trading pause. The only thing that pauses trading entirely is the daily loss gate in Section 10.
10
Daily Loss Limit

The daily loss limit is a circuit breaker that stops the bot from trading after a bad day, preventing a series of losses from compounding into a catastrophic drawdown.

SettingDefaultDescription
EnabledYesActive by default — strongly recommended to keep on
Limit5%Bot pauses if today's realized loss reaches 5% of equity
ResetDailyLoss counter resets at midnight UTC each day

What Happens When Limit Is Hit

  1. Bot sets running = false in config
  2. Alert banner appears on the dashboard
  3. Notification sent via email (and Telegram if configured)
  4. No further orders placed until manually resumed

How to Resume

From the dashboard, you can either:

11
Full Trade Lifecycle (Example)

Walk-through of a complete LONG trade on BTC-USDT-SWAP with default settings:

SettingValue
Equity$10,000 USDT
Max Position Size12% → $1,200 total
Leverage
Entries3 (equal: $400 each)
BTC price at entry$100,000
1
Analysis finds [S급] support at $100,000
Level exists on both 1H and 4H. Volume profile confirms high volume at this zone. Grade: S.
2
5m momentum: 3 consecutive falling candles → LONG signal
Prev 5m candle low = $97,100. SL distance = 2.9% → too tight, bot skips this tick.
3
Next cron: prev candle low = $96,800 → SL distance = 3.2% ✓
All 3 conditions pass. Entry #1 placed: LONG $400 (0.002 BTC × 5× = $2,000 notional). SL set at $96,800. TP = nearest resistance at $105,000.
4
Price dips to $99,500 → Entry #2 triggered
Still within ±2% of first entry ($100,000). Signal re-triggers at support. Entry #2: $400 more. Avg entry ≈ $99,750.
5
Price recovers, hits TP at $105,000 → Partial close
50% of total position closed at $105,000. Profit on first half: ~$260. SL moved to break-even ($99,750).
6
Price pushes to $108,000 then pulls back to $99,750
SL (break-even) hit. Remaining 50% closed at $99,750. Net on second half: ~$0 (minus fees). Total trade: +~$260 profit.
12
Default Parameters Reference
ParameterDefaultRangeNotes
Max Position Size12%1–100%Half-Kelly default
Max Leverage1–100×Warning triggers above 20×
Number of Entries32–10Kelly warning above 40% total
Entry SizingEqualEqual / MartingaleEqual recommended
Daily Loss Limit5%0.1–10%Enabled by default
S/R tolerance (detection)0.3%FixedTouch band for level confirmation
S/R tolerance (dedup)0.5%FixedMerge nearby duplicate levels
Entry touch tolerance0.4%FixedDistance from level for entry
SL distance range3–6%FixedBelow 3% or above 6% = skip
Fractional entry range±2%FixedMax drift from first entry for #2/#3
Recency window20 candlesFixed2 touches sufficient within this range
Max S/R age100 candlesFixedOlder levels ignored
Volume profile buckets50FixedGranularity of volume zones
Volume zone threshold2× avgFixedMin volume to count as a zone
Vol zone ↔ S/R overlap±1%FixedZone must be near S/R to be used
Partial close on TP50%FixedSL moves to break-even after
13
Demo Mode

Demo Mode routes all API calls to OKX's paper trading environment. All analysis logic, order placement, and SL/TP monitoring run identically — but no real money is used.

How It Works

When Demo Mode is enabled, the bot adds the x-simulated-trading: 1 header to every OKX API request. OKX's server routes these requests to their simulated trading system automatically.

Important — Separate API Keys Required
OKX Demo Trading uses a different set of API keys from your live account. You must log into OKX, navigate to "Demo Trading", and create a new API key there. The demo API key will not work on the live API, and vice versa.
Live ModeDemo Mode
API HeaderStandard OKX headers+ x-simulated-trading: 1
API KeysLive account keysOKX Demo account keys
FundsReal USDTVirtual balance
Bot logicIdenticalIdentical
Dashboard badgeDEMO shown

Recommended Usage

Run Demo Mode for at least 2–4 weeks before switching to live trading. This lets you verify that the bot's entry and exit behavior matches your expectations across different market conditions without financial risk.

AYILON — Automated Trading System oracletrading-01o.pages.dev