From Data-Feed to Swap - A Hands-On Guide to Building an Automated Trading Flow in Twazi

Learn step by step how to stitch eleven tiny "Lego blocks" into a fully automated PancakeSwap trader, and remember each block forever.

Back

Why read this?
By the end of this article, you’ll have a running workflow that starts with free CoinGecko data, decides when to trade, and ends with a signed PancakeSwap transaction—all inside Twazi’s visual builder.


🧭 Map First, Then Build

Human brains remember stories and chunks better than raw lists,
so we'll weave this build into a mini-story:

A cautious robot wakes up every 5 minutes, skims the market news,
checks its wallet, decides what to do, and—only when odds are good—
pushes the Swap button.

We’ll chunk that story into four bold phases:

PhaseCognitive TagBlocks
Sense👀 Input1 CoinGecko → 2 Pair Selector → 3 Pre-Processor
Know🧠 Decide4 Position → 5 Strategy → 6 Signal
Guard🛡 Risk7 Risk → 8 Router
Act⚙️ Execute9 Quote → 10 BuildTx → 11 Sign

1 → 3 | Sense the Market

1. CoinGecko Token Market Chart

Drag “HTTP Request” → paste the /coins/{id}/market_chart URL.
Save the raw JSON in the output.

Why we need it
Your robot must wake up with fresh data—this free feed is perfect.

2. Pair Selector (BSC)

Asset Token (buy):  BNB  
Quote Token (spend): USDT
Why we need it
Humans remember “BNB/USDT,” routers need 0x addresses—this node bridges the two.

3. Market Data Pre-Processor

Transforms CoinGecko’s timestamp arrays into a compact analytics bundle: log-returns, rolling volatility, volume differentials, and the most recent quote.
By converging every raw feed into a single, immutable “feature frame,” we guarantee that subsequent modules work from an identical, schema-stable data object.

Connect JSON output from step 1. The node emits:

1.returns

2.volatility

3.volume deltas

Brain-hack: We bundled 3 raw arrays into one frame, so your agent working memory is clean for what’s next.


4 → 6 | Know Where You Stand

4. Load Position State (On-Chain)

Queries BNB Chain for wallet balances, router allowance, and the latest swap involving the wallet.
This snapshot converts conjecture into fact, each trading decision is grounded in the wallet’s actual exposure at execution time.

Returns:

{
  "address": "0x840…e7E7",
  "balances": {
    "WBNB": { "balance": "...", "symbol": "WBNB" },
    "USDT": { "balance": "...", "symbol": "USDT" }
  }
}
Why we need it
A strategy that ignores its wallet is blind, this block tells us exactly what we already hold.

5. Box Strategy Selector

Evaluates the feature frame (and, optionally, sentiment flags) to classify the current regime as break-out (Darvas), range-bound, or no-edge.
The selector commits to a playbook before on-chain costs accrue, ensuring the workflow expends gas only when a statistically valid edge is present.

Inputs: Feature Frame + (optional) sentimentScore

Labels the regime: "darvas", "range", "hold"

Why we need it
Markets behave differently in breakouts vs. ranges labeling the regime lets us pick the right playbook.

6. Signal Generator (Spot DEX)

Fuses the regime label with wallet state, translating them into a precise trade directive—BUY, SELL, or HOLD—complete with quantity, price ceiling/floor, and stop level.
All discretionary variables (allocation %, risk %, slippage) are resolved here, giving later blocks fixed parameters to verify rather than invent.

Inputs: Strategy, Position, Pair Config Output:

{
  "action": "BUY",
  "size": "200000000000000000",
  "priceLimit": 69094,
  "stopLoss": 66820
}
Why we need it
Transforms an abstract “darvas long” idea into a concrete BUY/SELL size, price limit, and stop-loss.

7 → 8 | Guard the Downside

7. Box Risk Management

Applies hard, deterministic guards: maximum position size, maximum capital at risk (using the stop-loss distance), open-trade limit, and gas-value threshold.
If a guard is breached, the module either scales the order down or nullifies it, embedding an auditable reason code into the trade plan.

Max Position (%) = 0.25  
Max Risk (%)     = 0.02  
Gas Limit (quote)= 5

If any rule breaks, action becomes "HOLD".

Why we need it
Caps size, risk, and gas so one bad tick or one gas spike can’t torch the account.

8. Condition Router

A low-latency branch that inspects the sanctioned plan:
HOLD → workflow terminates early; BUY or SELL → execution path proceeds.
This micro-router prevents dead-weight RPC calls when there is no trade to place.

BUY/SELL → PROCEED  
HOLD     → HOLD
Why we need it
No sense quoting or signing when the plan is HOLD—this fork saves RPC calls and time.

9 → 11 | Act on-chain

9. Quote & Slippage

Requests a live AMM quote via getAmountsOut, converts it to an effective price, and compares that price to the plan’s limit.
If the market has drifted beyond tolerance, the block outputs “SKIP,” halting execution moments before gas would be spent.

Why we need it
Confirms the live AMM price is still inside our limit before we pay any gas.

10. PancakeSwap BuildTx

Encodes the swap into router calldata—swapTokensForExactTokens for buys, swapExactTokensForTokens for sells—fixing amounts, path, recipient, and deadline.
Because signing is deferred to the next block, this builder remains fully deterministic and replayable, simplifying both unit tests and post-trade forensic checks.

Generates calldata without signing:

{ "to": "0x10ED…", "data": "0x38ed17…", "chainId": 56 }
Why we need it
Crafts the exact calldata in a testable, deterministic way—no private key required yet.

11. Sign & Send Tx

https://bscscan.com/tx/0x4e9f…c07
Why we need it
Final gate: checks allowance, signs, and pushes the swap on-chain; without it, nothing ever settles..

Memory cue
Ending with a link creates a concrete anchor in memory.


🏁 Final Diagram

flowchart TD HTTP[HTTP Input] --> Pre[[Pre-Processor]] Pair[Pair Info] --> Generator[Signal Generator] Pre --> Selector[Pair Selector] Selector --> Generator Position[On-Chain Position] --> Generator Generator --> Risk[Box Risk Management] Risk --> Router[Condition Router] Router -- HOLD --> Logger[Log & Hold] Router -- PROCEED --> Quote[Quote & Slippage] Quote --> Build[PancakeSwap BuildTx] Build --> Sign[Sign & Send Tx] Sign --> Monitor((Receipt)) style HTTP fill:#fef3c7,stroke:#000,stroke-width:2 style Pair fill:#fef3c7,stroke:#000,stroke-width:2 style Pre fill:#86efac,stroke:#000,stroke-width:2 style Selector fill:#86efac,stroke:#000,stroke-width:2 style Position fill:#86efac,stroke:#000,stroke-width:2 style Generator fill:#a5b4fc,stroke:#000,stroke-width:2 style Risk fill:#fca5a5,stroke:#000,stroke-width:2 style Router fill:#67e8f9,stroke:#000,stroke-width:2 style Logger fill:#fef3c7,stroke:#000,stroke-width:2 style Quote fill:#fef3c7,stroke:#000,stroke-width:2 style Build fill:#86efac,stroke:#000,stroke-width:2 style Sign fill:#a5b4fc,stroke:#000,stroke-width:2 style Monitor fill:#fca5a5,stroke:#000,stroke-width:2

🔁 Spaced Repetition
Come back tomorrow, skim this again—recall will double.


Next Experiments

  • 🧠 Swap Router v3 – swap addresses, reuse BuildTx
  • 🤖 Sentiment LLM – feed scores into Feature Frame
  • 🧵 Perp DEX – Short plans + funding rule extensions

Final 60-second Review

  1. Sense → chart, pair, feature.
  2. Know → wallet, regime, plan.
  3. Guard → rules, route.
  4. Act → calldata, approve, swap.

✨ Say the 4-verb mantra weekly—burn it into your dev brain. Happy automating! 🚀

Written by

mukaeb

At

Tue Jun 10 2025