<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Bài 17 — Liquidity sweep]]></title><description><![CDATA[<p dir="auto">Theo SMC, phía trên các đỉnh cũ có nhiều lệnh dừng lỗ của phe short và lệnh chờ mua breakout; phía dưới các đáy cũ thì ngược lại. Những vùng tập trung lệnh đó gọi là <strong>liquidity pool</strong>. Một <strong>sweep</strong> (hay liquidity grab) xảy ra khi giá đâm qua pool, kích hoạt các lệnh đó, rồi rút ngay về: dấu hiệu bên lớn đã dùng thanh khoản để vào lệnh ngược chiều. Bài này định nghĩa vận hành cho pool và sweep, phân biệt sweep với phá vỡ thật, và hoàn thiện module cuối cùng trước khi ghép chiến lược ở Bài 18.</p>
<h3><strong>Mục tiêu</strong></h3>
<ul>
<li>Xác định liquidity pool từ swing đã xác nhận, kể cả equal highs/lows.</li>
<li>Định nghĩa sweep và phân biệt với breakout.</li>
<li>Dùng đỉnh/đáy ngày hôm trước (PDH/PDL) làm pool qua @informative.</li>
<li>Tạo module smc_liquidity.py và chiến lược LiquiditySweepDemo.</li>
</ul>
<h3><strong>Định nghĩa vận hành</strong></h3>
<table class="table table-bordered table-striped">
<thead>
<tr>
<th style="text-align:left">Khái niệm</th>
<th style="text-align:left">Định nghĩa</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:left">Pool phía trên (buy-side liquidity)</td>
<td style="text-align:left">Swing high đã xác nhận (Bài 14), chưa bị giá vượt qua</td>
</tr>
<tr>
<td style="text-align:left">Pool phía dưới (sell-side liquidity)</td>
<td style="text-align:left">Swing low đã xác nhận, chưa bị giá thủng</td>
</tr>
<tr>
<td style="text-align:left">Equal highs (EQH)</td>
<td style="text-align:left">Hai swing high trở lên cách nhau không quá eq_k × ATR; gộp thành một pool, đếm số lần</td>
</tr>
<tr>
<td style="text-align:left"><strong>Sweep phía trên</strong></td>
<td style="text-align:left">Một nến có high vượt pool, nhưng <strong>đóng cửa dưới</strong> mức pool</td>
</tr>
<tr>
<td style="text-align:left">Breakout phía trên</td>
<td style="text-align:left">Nến có high vượt pool và <strong>đóng cửa trên</strong> mức pool</td>
</tr>
<tr>
<td style="text-align:left">Sweep / breakout phía dưới</td>
<td style="text-align:left">Đối xứng</td>
</tr>
</tbody>
</table>
<p dir="auto">Cả sweep lẫn breakout đều "tiêu thụ" pool: sau đó pool không còn hiệu lực. Điểm phân biệt duy nhất là giá đóng cửa, và nó chỉ được biết khi nến đóng, nên sweep được ghi tại đúng nến đó mà không có lookahead.</p>
<p dir="auto">Vì sao equal highs quan trọng: hai đỉnh gần bằng nhau là nơi rất nhiều người đặt stop "ngay trên đỉnh", nên lượng thanh khoản tập trung lớn hơn một đỉnh đơn. Module giữ số lần (count) để bạn so sánh hai loại bằng tag.</p>
<p dir="auto"><strong>Giới hạn của định nghĩa một nến.</strong> Nhiều cú sweep kéo dài vài nến: nến đầu đóng trên đỉnh, nến sau mới rút về. Định nghĩa ở đây gọi đó là breakout. Bài tập 4 mở rộng thành "rút về trong M nến".</p>
<h3><strong>Module smc_liquidity.py</strong></h3>
<p dir="auto">Lưu thành user_data/strategies/smc_liquidity.py:</p>
<p dir="auto">"""Liquidity pool và sweep. Dùng cho Bài 17-18."""<br />
import numpy as np<br />
import pandas as pd<br />
from numba import njit</p>
<p dir="auto">@njit(cache=True)<br />
def _liquidity(high, low, close, sh_event, sl_event, atr, eq_k, max_pools, max_age):<br />
n = len(close)<br />
p_lvl = np.full(max_pools, np.nan)<br />
p_side = np.zeros(max_pools, dtype=np.int8)    # 1: pool trên, -1: pool dưới<br />
p_cnt = np.zeros(max_pools, dtype=np.int64)<br />
p_born = np.zeros(max_pools, dtype=np.int64)<br />
p_on = np.zeros(max_pools, dtype=np.bool_)<br />
nxt = 0</p>
<pre><code>sw\_hi \= np.zeros(n, dtype=np.bool\_)  
sw\_hi\_lvl \= np.full(n, np.nan)  
sw\_hi\_ext \= np.full(n, np.nan)  
sw\_hi\_cnt \= np.zeros(n, dtype=np.int64)  
sw\_lo \= np.zeros(n, dtype=np.bool\_)  
sw\_lo\_lvl \= np.full(n, np.nan)  
sw\_lo\_ext \= np.full(n, np.nan)  
sw\_lo\_cnt \= np.zeros(n, dtype=np.int64)  
liq\_above \= np.full(n, np.nan)  
liq\_below \= np.full(n, np.nan)

for i in range(n):  
    \# 1\) Pool có trước nến i: bị quét hay bị phá?  
    for z in range(max\_pools):  
        if not p\_on\[z\]:  
            continue  
        if i \- p\_born\[z\] \&gt; max\_age:  
            p\_on\[z\] \= False  
            continue  
        if p\_side\[z\] \== 1 and high\[i\] \&gt; p\_lvl\[z\]:  
            p\_on\[z\] \= False  
            if close\[i\] \&lt; p\_lvl\[z\]:                      \# sweep, không phải breakout  
                if (not sw\_hi\[i\]) or p\_lvl\[z\] \&gt; sw\_hi\_lvl\[i\]:  
                    sw\_hi\[i\] \= True  
                    sw\_hi\_lvl\[i\] \= p\_lvl\[z\]  
                    sw\_hi\_ext\[i\] \= high\[i\]  
                    sw\_hi\_cnt\[i\] \= p\_cnt\[z\]  
        elif p\_side\[z\] \== \-1 and low\[i\] \&lt; p\_lvl\[z\]:  
            p\_on\[z\] \= False  
            if close\[i\] \&gt; p\_lvl\[z\]:  
                if (not sw\_lo\[i\]) or p\_lvl\[z\] \&lt; sw\_lo\_lvl\[i\]:  
                    sw\_lo\[i\] \= True  
                    sw\_lo\_lvl\[i\] \= p\_lvl\[z\]  
                    sw\_lo\_ext\[i\] \= low\[i\]  
                    sw\_lo\_cnt\[i\] \= p\_cnt\[z\]

    \# 2\) Pool còn hiệu lực gần giá nhất  
    for z in range(max\_pools):  
        if not p\_on\[z\]:  
            continue  
        if p\_side\[z\] \== 1 and (np.isnan(liq\_above\[i\]) or p\_lvl\[z\] \&lt; liq\_above\[i\]):  
            liq\_above\[i\] \= p\_lvl\[z\]  
        elif p\_side\[z\] \== \-1 and (np.isnan(liq\_below\[i\]) or p\_lvl\[z\] \&gt; liq\_below\[i\]):  
            liq\_below\[i\] \= p\_lvl\[z\]

    \# 3\) Thêm pool từ swing được xác nhận tại nến i (gộp nếu gần pool cũ)  
    for side in (1, \-1):  
        lvl \= sh\_event\[i\] if side \== 1 else sl\_event\[i\]  
        if np.isnan(lvl):  
            continue  
        merged \= False  
        if not np.isnan(atr\[i\]):  
            for z in range(max\_pools):  
                if p\_on\[z\] and p\_side\[z\] \== side and abs(p\_lvl\[z\] \- lvl) \&lt;= eq\_k \* atr\[i\]:  
                    p\_lvl\[z\] \= max(p\_lvl\[z\], lvl) if side \== 1 else min(p\_lvl\[z\], lvl)  
                    p\_cnt\[z\] \+= 1  
                    p\_born\[z\] \= i  
                    merged \= True  
                    break  
        if not merged:  
            p\_lvl\[nxt\] \= lvl  
            p\_side\[nxt\] \= side  
            p\_cnt\[nxt\] \= 1  
            p\_born\[nxt\] \= i  
            p\_on\[nxt\] \= True  
            nxt \= (nxt \+ 1\) % max\_pools

return (sw\_hi, sw\_hi\_lvl, sw\_hi\_ext, sw\_hi\_cnt,  
        sw\_lo, sw\_lo\_lvl, sw\_lo\_ext, sw\_lo\_cnt, liq\_above, liq\_below)
</code></pre>
<p dir="auto">def liquidity_pools(df: pd.DataFrame, sw: pd.DataFrame, atr: pd.Series,<br />
eq_k: float = 0.1, max_pools: int = 30, max_age: int = 300) -&gt; pd.DataFrame:<br />
"""sw là kết quả của smc_swings.fractal_swings trên cùng df."""<br />
sh_event = sw["last_sh"].where(sw["sh_confirmed"])<br />
sl_event = sw["last_sl"].where(sw["sl_confirmed"])<br />
res = _liquidity(<br />
df["high"].to_numpy(np.float64),<br />
df["low"].to_numpy(np.float64),<br />
df["close"].to_numpy(np.float64),<br />
sh_event.to_numpy(np.float64),<br />
sl_event.to_numpy(np.float64),<br />
<a href="http://atr.to" rel="nofollow ugc">atr.to</a>_numpy(np.float64),<br />
float(eq_k), int(max_pools), int(max_age),<br />
)<br />
names = ["sweep_high", "sweep_high_level", "sweep_high_ext", "sweep_high_count",<br />
"sweep_low", "sweep_low_level", "sweep_low_ext", "sweep_low_count",<br />
"liq_above", "liq_below"]<br />
return pd.DataFrame(dict(zip(names, res)), index=df.index)</p>
<table class="table table-bordered table-striped">
<thead>
<tr>
<th style="text-align:left">Cột</th>
<th style="text-align:left">Ý nghĩa</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:left">sweep_high, sweep_low</td>
<td style="text-align:left">Nến này quét pool trên / dưới</td>
</tr>
<tr>
<td style="text-align:left">sweep_*_level</td>
<td style="text-align:left">Mức pool bị quét (khi một nến quét nhiều pool, lấy pool xa nhất)</td>
</tr>
<tr>
<td style="text-align:left">sweep_*_ext</td>
<td style="text-align:left">Râu nến quét (high hoặc low): mức đặt stoploss ở Bài 18</td>
</tr>
<tr>
<td style="text-align:left">sweep_*_count</td>
<td style="text-align:left">Số swing gộp trong pool; từ 2 trở lên là equal highs/lows</td>
</tr>
<tr>
<td style="text-align:left">liq_above, liq_below</td>
<td style="text-align:left">Pool còn hiệu lực gần giá nhất phía trên / dưới: mục tiêu chốt lời tự nhiên</td>
</tr>
</tbody>
</table>
<p dir="auto">Các điểm đảm bảo không lookahead giống các module trước: pool chỉ được thêm tại nến xác nhận swing, và chỉ được xét từ nến <strong>sau</strong> đó; sweep được ghi tại nến đóng cửa quay về. Một swing high được xác nhận tại nến t không thể bị quét ngay tại t, vì high[t] nằm trong cửa sổ mà swing đó là đỉnh.</p>
<h3><strong>PDH/PDL làm pool</strong></h3>
<p dir="auto">Đỉnh và đáy của ngày hôm trước là pool được theo dõi rộng rãi. Với @informative("1d"), cột high_1d tại mỗi nến 1h là đỉnh của <strong>ngày đã đóng gần nhất</strong>, nhờ cơ chế dịch thời gian ở Bài 11. Không cần tự tính:</p>
<p dir="auto">@informative("1d")<br />
def populate_indicators_1d(self, dataframe: DataFrame, metadata: dict) -&gt; DataFrame:<br />
return dataframe          # chỉ cần high_1d, low_1d, close_1d</p>
<p dir="auto"># trong populate_indicators:<br />
dataframe["sweep_pdh"] = (dataframe["high"] &gt; dataframe["high_1d"]) &amp; (dataframe["close"] &lt; dataframe["high_1d"])<br />
dataframe["sweep_pdl"] = (dataframe["low"] &lt; dataframe["low_1d"]) &amp; (dataframe["close"] &gt; dataframe["low_1d"])<br />
Cách viết này có thể báo sweep nhiều lần trong cùng một ngày; bài tập 3 sửa thành chỉ lần đầu. Cần tải dữ liệu khung 1d.</p>
<h3><strong>Chiến lược minh họa: LiquiditySweepDemo</strong></h3>
<p dir="auto">Vào lệnh đảo chiều ngay sau sweep, để đo xem bản thân sweep có giá trị không. Tag phân biệt pool đơn và equal highs/lows.</p>
<p dir="auto">Lưu thành user_data/strategies/LiquiditySweepDemo.py:</p>
<p dir="auto">import pandas as pd<br />
from pandas import DataFrame<br />
import talib.abstract as ta</p>
<p dir="auto">from freqtrade.strategy import IStrategy</p>
<p dir="auto">from smc_liquidity import liquidity_pools<br />
from smc_swings import fractal_swings</p>
<p dir="auto">class LiquiditySweepDemo(IStrategy):<br />
"""Bài 17: vào lệnh ngược chiều ngay sau sweep; so sánh pool đơn và equal."""</p>
<pre><code>INTERFACE\_VERSION \= 3  
timeframe \= "1h"  
can\_short \= True  
startup\_candle\_count \= 400

minimal\_roi \= {"0": 0.04, "720": 0.0}   \# chốt 4%; sau 12 giờ thoát khi không lỗ  
stoploss \= \-0.04  
process\_only\_new\_candles \= True

swing\_n \= 3  
eq\_k \= 0.1

def populate\_indicators(self, dataframe: DataFrame, metadata: dict) \-\&gt; DataFrame:  
    dataframe\["atr"\] \= ta.ATR(dataframe, timeperiod=14)  
    sw \= fractal\_swings(dataframe, n=self.swing\_n)  
    liq \= liquidity\_pools(dataframe, sw, dataframe\["atr"\], eq\_k=self.eq\_k)  
    return pd.concat(\[dataframe, sw, liq\], axis=1)

def populate\_entry\_trend(self, dataframe: DataFrame, metadata: dict) \-\&gt; DataFrame:  
    has\_volume \= dataframe\["volume"\] \&gt; 0  
    lo, hi \= dataframe\["sweep\_low"\], dataframe\["sweep\_high"\]  
    lo\_eq \= dataframe\["sweep\_low\_count"\] \&gt;= 2  
    hi\_eq \= dataframe\["sweep\_high\_count"\] \&gt;= 2

    dataframe.loc\[lo &amp; \~lo\_eq &amp; has\_volume, \["enter\_long", "enter\_tag"\]\] \= (1, "sweep\_low")  
    dataframe.loc\[lo &amp; lo\_eq &amp; has\_volume, \["enter\_long", "enter\_tag"\]\] \= (1, "sweep\_eql")  
    dataframe.loc\[hi &amp; \~hi\_eq &amp; has\_volume, \["enter\_short", "enter\_tag"\]\] \= (1, "sweep\_high")  
    dataframe.loc\[hi &amp; hi\_eq &amp; has\_volume, \["enter\_short", "enter\_tag"\]\] \= (1, "sweep\_eqh")  
    return dataframe

def populate\_exit\_trend(self, dataframe: DataFrame, metadata: dict) \-\&gt; DataFrame:  
    dataframe.loc\[dataframe\["sweep\_high"\], \["exit\_long", "exit\_tag"\]\] \= (1, "opposite\_sweep")  
    dataframe.loc\[dataframe\["sweep\_low"\], \["exit\_short", "exit\_tag"\]\] \= (1, "opposite\_sweep")  
    return dataframe  
</code></pre>
<p dir="auto">Nến vừa quét cả hai phía (râu dài hai đầu) sẽ có cả enter_long và enter_short; theo quy tắc xung đột ở Bài 5, cả hai bị bỏ qua. Đó là hành vi mong muốn: nến như vậy không cho thông tin về chiều.</p>
<p dir="auto">Chạy:</p>
<p dir="auto">freqtrade lookahead-analysis -c user_data/config.json -s LiquiditySweepDemo \<br />
--timerange 20240101-20251231</p>
<p dir="auto">freqtrade backtesting -c user_data/config.json -s LiquiditySweepDemo \<br />
--timerange 20240101-20251231 --timeframe-detail 15m --export signals --cache none</p>
<p dir="auto">freqtrade backtesting-analysis -c user_data/config.json --analysis-groups 0 1 \<br />
--indicator-list sweep_low_level sweep_low_ext sweep_high_level sweep_high_ext atr<br />
Câu hỏi chính: tag sweep_eql/sweep_eqh có tốt hơn pool đơn không? Và sweep "trần" như thế này có lợi thế nào sau phí không? Câu trả lời thường là lợi thế rất mỏng, và đó là lý do Bài 18 cần thêm xác nhận.</p>
<h3><strong>Lỗi thường gặp</strong></h3>
<table class="table table-bordered table-striped">
<thead>
<tr>
<th style="text-align:left">Triệu chứng</th>
<th style="text-align:left">Nguyên nhân</th>
<th style="text-align:left">Cách xử lý</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:left">Rất ít sweep</td>
<td style="text-align:left">swing_n lớn nên ít pool, hoặc max_age nhỏ</td>
<td style="text-align:left">Giảm swing_n; tăng max_age</td>
</tr>
<tr>
<td style="text-align:left">Không bao giờ có equal highs</td>
<td style="text-align:left">eq_k quá nhỏ so với biến động</td>
<td style="text-align:left">Tăng eq_k (0.1 đến 0.3)</td>
</tr>
<tr>
<td style="text-align:left">Gần như mọi đỉnh đều thành equal</td>
<td style="text-align:left">eq_k quá lớn</td>
<td style="text-align:left">Giảm eq_k</td>
</tr>
<tr>
<td style="text-align:left">Sweep PDH báo nhiều lần trong ngày</td>
<td style="text-align:left">Điều kiện đơn giản không nhớ trạng thái</td>
<td style="text-align:left">Chỉ lấy lần đầu (bài tập 3)</td>
</tr>
<tr>
<td style="text-align:left">Kết quả đổi theo ngày bắt đầu</td>
<td style="text-align:left">max_pools đầy, pool cũ bị ghi đè</td>
<td style="text-align:left">Tăng max_pools; kiểm tra recursive-analysis</td>
</tr>
</tbody>
</table>
]]></description><link>https://freqtrade-viet.com/topic/18/bài-17-liquidity-sweep</link><generator>RSS for Node</generator><lastBuildDate>Sun, 06 Dec 2026 01:52:44 GMT</lastBuildDate><atom:link href="https://freqtrade-viet.com/topic/18.rss" rel="self" type="application/rss+xml"/><pubDate>Wed, 21 Oct 2026 03:57:24 GMT</pubDate><ttl>60</ttl></channel></rss>