ohlc-bar-matching-engine 1.0.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- ohlc_bar_matching_engine-1.0.0/LICENSE +21 -0
- ohlc_bar_matching_engine-1.0.0/PKG-INFO +85 -0
- ohlc_bar_matching_engine-1.0.0/README.md +60 -0
- ohlc_bar_matching_engine-1.0.0/pyproject.toml +41 -0
- ohlc_bar_matching_engine-1.0.0/src/ohlc_bar_matching_engine/__init__.py +131 -0
- ohlc_bar_matching_engine-1.0.0/src/ohlc_bar_matching_engine/py.typed +0 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 HoldWins (https://holdwins.com)
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: ohlc-bar-matching-engine
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Zero-dependency USDⓈ-M perpetual OHLC bar-replay matching engine: market/limit/stop orders, TP/SL, gap execution, and isolated/cross forced liquidation.
|
|
5
|
+
Keywords: backtesting,matching-engine,ohlc,candlestick-replay,perpetual-futures,paper-trading,crypto
|
|
6
|
+
Author: HoldWins
|
|
7
|
+
Author-email: HoldWins <ops@holdwins.com>
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: Intended Audience :: Financial and Insurance Industry
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
15
|
+
Classifier: Topic :: Office/Business :: Financial :: Investment
|
|
16
|
+
Classifier: Typing :: Typed
|
|
17
|
+
Requires-Python: >=3.9
|
|
18
|
+
Project-URL: Homepage, https://holdwins.com/en/kline/
|
|
19
|
+
Project-URL: Live Kline Trainer (EN), https://holdwins.com/en/kline/
|
|
20
|
+
Project-URL: K 线盘感训练器 (中文), https://holdwins.com/kline/
|
|
21
|
+
Project-URL: Candlestick Reading Guide, https://holdwins.com/guides/how-to-read-kline/
|
|
22
|
+
Project-URL: Documentation, https://dalangdalang934.github.io/ohlc-bar-matching-engine/
|
|
23
|
+
Project-URL: Repository, https://github.com/dalangdalang934/ohlc-bar-matching-engine
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
|
|
26
|
+
# ohlc-bar-matching-engine
|
|
27
|
+
|
|
28
|
+
Minimalist, zero-dependency **Python** & **JavaScript** intrabar matching engine (~100 LOC) for **historical OHLC candlestick replay** and paper-trading simulators: handles limit/stop orders, take-profit / stop-loss priority, opening price gaps (`prevClose → open`), and isolated/cross forced liquidation.
|
|
29
|
+
|
|
30
|
+
- **Play Live in Browser (English)**: [Historical Kline Candlesticks Trainer (`holdwins.com/en/kline/`)](https://holdwins.com/en/kline/)
|
|
31
|
+
- **在线盲盘实战训练(中文)**: [K 线盘感训练器 (`holdwins.com/kline/`)](https://holdwins.com/kline/)
|
|
32
|
+
|
|
33
|
+
---
|
|
34
|
+
|
|
35
|
+
## Python Installation & Quick Start
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
pip install ohlc-bar-matching-engine
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
```python
|
|
42
|
+
from ohlc_bar_matching_engine import create_account, fill, process_bar
|
|
43
|
+
|
|
44
|
+
acct = create_account(wallet=10000, leverage=10, mode="isolated")
|
|
45
|
+
fill(acct, side="buy", qty=0.1, price=100000)
|
|
46
|
+
acct["pos"]["tp"] = 105000
|
|
47
|
+
process_bar(acct, {"o": 100500, "l": 99800, "h": 105500, "c": 104000}, prev_close=100000)
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
---
|
|
51
|
+
|
|
52
|
+
## The Intrabar Ordering Problem
|
|
53
|
+
|
|
54
|
+
Historical candlestick APIs provide only `[open, high, low, close]` without tick timestamps. When a single candle spans both a long position's Take-Profit and Stop-Loss (or crosses multiple resting orders across an opening gap), a deterministic path and priority rule is required:
|
|
55
|
+
|
|
56
|
+
1. **Gap Segment (`prevClose → open`)**: Every resting trigger crossed between the prior close and the new open executes at `open` without advancing the cursor past subsequent resting orders in the same gap.
|
|
57
|
+
2. **Intrabar Path**:
|
|
58
|
+
- Bullish bar (`close >= open`): `open → low → high → close`
|
|
59
|
+
- Bearish bar (`close < open`): `open → high → low → close`
|
|
60
|
+
3. **Trigger Priority**: Distance-first along each segment; ties place Stop-Loss ahead of Liquidation so valid protective stops fire before forced liquidation.
|
|
61
|
+
|
|
62
|
+
## Quick Start
|
|
63
|
+
|
|
64
|
+
```js
|
|
65
|
+
import { createAccount, fill, processBar } from './src/engine.mjs';
|
|
66
|
+
|
|
67
|
+
const acct = createAccount({ wallet: 10000, leverage: 10, mode: 'isolated' });
|
|
68
|
+
fill(acct, { side: 'buy', qty: 0.1, price: 100000, liquidity: 'taker' });
|
|
69
|
+
acct.pos.tp = 103000;
|
|
70
|
+
acct.pos.sl = 96000;
|
|
71
|
+
|
|
72
|
+
processBar(acct, { o: 100000, h: 104200, l: 98500, c: 103500 }, 100000);
|
|
73
|
+
console.log(acct);
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
## Related Open Tools & Guides
|
|
77
|
+
|
|
78
|
+
- [Kline Candlesticks Trainer (EN)](https://holdwins.com/en/kline/) · [K 线盘感训练器(中文)](https://holdwins.com/kline/)
|
|
79
|
+
- [Crypto Volume Profile & Chip Distribution](https://holdwins.com/chip-distribution/)
|
|
80
|
+
- [Perpetual Futures Liquidation Calculator](https://holdwins.com/en/futures-calculator/) · [合约计算器](https://holdwins.com/futures-calculator/)
|
|
81
|
+
- [Stop-Loss & Take-Profit Guide](https://holdwins.com/en/guides/binance-stop-loss-take-profit/) · [止盈止损设置教程](https://holdwins.com/guides/binance-stop-loss-take-profit/)
|
|
82
|
+
|
|
83
|
+
## License
|
|
84
|
+
|
|
85
|
+
MIT © [HoldWins](https://holdwins.com)
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
# ohlc-bar-matching-engine
|
|
2
|
+
|
|
3
|
+
Minimalist, zero-dependency **Python** & **JavaScript** intrabar matching engine (~100 LOC) for **historical OHLC candlestick replay** and paper-trading simulators: handles limit/stop orders, take-profit / stop-loss priority, opening price gaps (`prevClose → open`), and isolated/cross forced liquidation.
|
|
4
|
+
|
|
5
|
+
- **Play Live in Browser (English)**: [Historical Kline Candlesticks Trainer (`holdwins.com/en/kline/`)](https://holdwins.com/en/kline/)
|
|
6
|
+
- **在线盲盘实战训练(中文)**: [K 线盘感训练器 (`holdwins.com/kline/`)](https://holdwins.com/kline/)
|
|
7
|
+
|
|
8
|
+
---
|
|
9
|
+
|
|
10
|
+
## Python Installation & Quick Start
|
|
11
|
+
|
|
12
|
+
```bash
|
|
13
|
+
pip install ohlc-bar-matching-engine
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
```python
|
|
17
|
+
from ohlc_bar_matching_engine import create_account, fill, process_bar
|
|
18
|
+
|
|
19
|
+
acct = create_account(wallet=10000, leverage=10, mode="isolated")
|
|
20
|
+
fill(acct, side="buy", qty=0.1, price=100000)
|
|
21
|
+
acct["pos"]["tp"] = 105000
|
|
22
|
+
process_bar(acct, {"o": 100500, "l": 99800, "h": 105500, "c": 104000}, prev_close=100000)
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
---
|
|
26
|
+
|
|
27
|
+
## The Intrabar Ordering Problem
|
|
28
|
+
|
|
29
|
+
Historical candlestick APIs provide only `[open, high, low, close]` without tick timestamps. When a single candle spans both a long position's Take-Profit and Stop-Loss (or crosses multiple resting orders across an opening gap), a deterministic path and priority rule is required:
|
|
30
|
+
|
|
31
|
+
1. **Gap Segment (`prevClose → open`)**: Every resting trigger crossed between the prior close and the new open executes at `open` without advancing the cursor past subsequent resting orders in the same gap.
|
|
32
|
+
2. **Intrabar Path**:
|
|
33
|
+
- Bullish bar (`close >= open`): `open → low → high → close`
|
|
34
|
+
- Bearish bar (`close < open`): `open → high → low → close`
|
|
35
|
+
3. **Trigger Priority**: Distance-first along each segment; ties place Stop-Loss ahead of Liquidation so valid protective stops fire before forced liquidation.
|
|
36
|
+
|
|
37
|
+
## Quick Start
|
|
38
|
+
|
|
39
|
+
```js
|
|
40
|
+
import { createAccount, fill, processBar } from './src/engine.mjs';
|
|
41
|
+
|
|
42
|
+
const acct = createAccount({ wallet: 10000, leverage: 10, mode: 'isolated' });
|
|
43
|
+
fill(acct, { side: 'buy', qty: 0.1, price: 100000, liquidity: 'taker' });
|
|
44
|
+
acct.pos.tp = 103000;
|
|
45
|
+
acct.pos.sl = 96000;
|
|
46
|
+
|
|
47
|
+
processBar(acct, { o: 100000, h: 104200, l: 98500, c: 103500 }, 100000);
|
|
48
|
+
console.log(acct);
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
## Related Open Tools & Guides
|
|
52
|
+
|
|
53
|
+
- [Kline Candlesticks Trainer (EN)](https://holdwins.com/en/kline/) · [K 线盘感训练器(中文)](https://holdwins.com/kline/)
|
|
54
|
+
- [Crypto Volume Profile & Chip Distribution](https://holdwins.com/chip-distribution/)
|
|
55
|
+
- [Perpetual Futures Liquidation Calculator](https://holdwins.com/en/futures-calculator/) · [合约计算器](https://holdwins.com/futures-calculator/)
|
|
56
|
+
- [Stop-Loss & Take-Profit Guide](https://holdwins.com/en/guides/binance-stop-loss-take-profit/) · [止盈止损设置教程](https://holdwins.com/guides/binance-stop-loss-take-profit/)
|
|
57
|
+
|
|
58
|
+
## License
|
|
59
|
+
|
|
60
|
+
MIT © [HoldWins](https://holdwins.com)
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "ohlc-bar-matching-engine"
|
|
3
|
+
version = "1.0.0"
|
|
4
|
+
description = "Zero-dependency USDⓈ-M perpetual OHLC bar-replay matching engine: market/limit/stop orders, TP/SL, gap execution, and isolated/cross forced liquidation."
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
requires-python = ">=3.9"
|
|
7
|
+
license = "MIT"
|
|
8
|
+
license-files = ["LICENSE"]
|
|
9
|
+
authors = [
|
|
10
|
+
{ name = "HoldWins", email = "ops@holdwins.com" }
|
|
11
|
+
]
|
|
12
|
+
keywords = [
|
|
13
|
+
"backtesting",
|
|
14
|
+
"matching-engine",
|
|
15
|
+
"ohlc",
|
|
16
|
+
"candlestick-replay",
|
|
17
|
+
"perpetual-futures",
|
|
18
|
+
"paper-trading",
|
|
19
|
+
"crypto"
|
|
20
|
+
]
|
|
21
|
+
classifiers = [
|
|
22
|
+
"Development Status :: 5 - Production/Stable",
|
|
23
|
+
"Intended Audience :: Developers",
|
|
24
|
+
"Intended Audience :: Financial and Insurance Industry",
|
|
25
|
+
"Programming Language :: Python :: 3",
|
|
26
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
27
|
+
"Topic :: Office/Business :: Financial :: Investment",
|
|
28
|
+
"Typing :: Typed"
|
|
29
|
+
]
|
|
30
|
+
|
|
31
|
+
[project.urls]
|
|
32
|
+
Homepage = "https://holdwins.com/en/kline/"
|
|
33
|
+
"Live Kline Trainer (EN)" = "https://holdwins.com/en/kline/"
|
|
34
|
+
"K 线盘感训练器 (中文)" = "https://holdwins.com/kline/"
|
|
35
|
+
"Candlestick Reading Guide" = "https://holdwins.com/guides/how-to-read-kline/"
|
|
36
|
+
Documentation = "https://dalangdalang934.github.io/ohlc-bar-matching-engine/"
|
|
37
|
+
Repository = "https://github.com/dalangdalang934/ohlc-bar-matching-engine"
|
|
38
|
+
|
|
39
|
+
[build-system]
|
|
40
|
+
requires = ["uv_build>=0.9.0,<0.12.0"]
|
|
41
|
+
build-backend = "uv_build"
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
"""Single-way USDⓈ-M OHLC bar-replay matching engine."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
FEE = {"maker": 0.0002, "taker": 0.0005}
|
|
8
|
+
MMR = 0.005
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _sign(side: str) -> int:
|
|
12
|
+
return 1 if side in ("long", "buy") else -1
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def create_account(*, wallet: float = 10000.0, leverage: float = 20.0, mode: str = "isolated") -> dict[str, Any]:
|
|
16
|
+
return {"wallet": float(wallet), "leverage": float(leverage), "mode": mode, "pos": None, "orders": [], "fills": []}
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def liq_price(acct: dict[str, Any]) -> float | None:
|
|
20
|
+
p = acct.get("pos")
|
|
21
|
+
if not p:
|
|
22
|
+
return None
|
|
23
|
+
margin = p["margin"] if acct["mode"] == "isolated" else acct["wallet"]
|
|
24
|
+
if p["side"] == "long":
|
|
25
|
+
px = (p["qty"] * p["entry"] - margin) / (p["qty"] * (1.0 - MMR))
|
|
26
|
+
else:
|
|
27
|
+
px = (p["qty"] * p["entry"] + margin) / (p["qty"] * (1.0 + MMR))
|
|
28
|
+
return px if px > 0 else None
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def fill(acct: dict[str, Any], *, side: str, qty: float, price: float, liquidity: str = "taker") -> None:
|
|
32
|
+
fee = qty * price * FEE[liquidity]
|
|
33
|
+
acct["wallet"] -= fee
|
|
34
|
+
left = float(qty)
|
|
35
|
+
p = acct.get("pos")
|
|
36
|
+
if p and _sign(side) != _sign(p["side"]):
|
|
37
|
+
closing = min(left, p["qty"])
|
|
38
|
+
acct["wallet"] += _sign(p["side"]) * (price - p["entry"]) * closing
|
|
39
|
+
if acct["mode"] == "isolated":
|
|
40
|
+
p["margin"] -= (p["margin"] * closing) / p["qty"]
|
|
41
|
+
p["qty"] -= closing
|
|
42
|
+
left -= closing
|
|
43
|
+
if p["qty"] < 1e-12:
|
|
44
|
+
acct["pos"] = None
|
|
45
|
+
if left > 1e-12:
|
|
46
|
+
if acct.get("pos") is None:
|
|
47
|
+
acct["pos"] = {
|
|
48
|
+
"side": "long" if _sign(side) > 0 else "short",
|
|
49
|
+
"qty": 0.0,
|
|
50
|
+
"entry": float(price),
|
|
51
|
+
"margin": 0.0,
|
|
52
|
+
"tp": None,
|
|
53
|
+
"sl": None,
|
|
54
|
+
}
|
|
55
|
+
q = acct["pos"]
|
|
56
|
+
q["entry"] = (q["entry"] * q["qty"] + price * left) / (q["qty"] + left)
|
|
57
|
+
q["qty"] += left
|
|
58
|
+
if acct["mode"] == "isolated":
|
|
59
|
+
q["margin"] += (left * price) / acct["leverage"]
|
|
60
|
+
acct["fills"].append({"side": side, "qty": qty, "price": price, "fee": fee})
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _triggers(acct: dict[str, Any]) -> list[dict[str, Any]]:
|
|
64
|
+
out: list[dict[str, Any]] = []
|
|
65
|
+
for o in acct["orders"]:
|
|
66
|
+
if o["type"] == "limit":
|
|
67
|
+
out.append({"level": o["price"], "dir": -1 if o["side"] == "buy" else 1, "kind": "limit", "order": o})
|
|
68
|
+
else:
|
|
69
|
+
out.append({"level": o["trigger"], "dir": 1 if o["side"] == "buy" else -1, "kind": "stop", "order": o})
|
|
70
|
+
p = acct.get("pos")
|
|
71
|
+
if p:
|
|
72
|
+
is_long = p["side"] == "long"
|
|
73
|
+
if p.get("sl") is not None:
|
|
74
|
+
out.append({"level": p["sl"], "dir": -1 if is_long else 1, "kind": "sl"})
|
|
75
|
+
lp = liq_price(acct)
|
|
76
|
+
if lp is not None:
|
|
77
|
+
out.append({"level": lp, "dir": -1 if is_long else 1, "kind": "liq"})
|
|
78
|
+
if p.get("tp") is not None:
|
|
79
|
+
out.append({"level": p["tp"], "dir": 1 if is_long else -1, "kind": "tp"})
|
|
80
|
+
return out
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _execute(acct: dict[str, Any], hit: dict[str, Any], price: float) -> None:
|
|
84
|
+
if hit["kind"] == "liq":
|
|
85
|
+
p = acct["pos"]
|
|
86
|
+
if acct["mode"] == "isolated":
|
|
87
|
+
acct["wallet"] -= p["margin"]
|
|
88
|
+
else:
|
|
89
|
+
acct["wallet"] = max(
|
|
90
|
+
0.0,
|
|
91
|
+
acct["wallet"] + _sign(p["side"]) * (hit["level"] - p["entry"]) * p["qty"] - p["qty"] * hit["level"] * MMR,
|
|
92
|
+
)
|
|
93
|
+
acct["fills"].append(
|
|
94
|
+
{"side": "sell" if p["side"] == "long" else "buy", "qty": p["qty"], "price": hit["level"], "fee": 0.0, "kind": "liquidation"}
|
|
95
|
+
)
|
|
96
|
+
acct["pos"] = None
|
|
97
|
+
acct["orders"] = []
|
|
98
|
+
return
|
|
99
|
+
if hit["kind"] in ("tp", "sl"):
|
|
100
|
+
p = acct["pos"]
|
|
101
|
+
fill(acct, side="sell" if p["side"] == "long" else "buy", qty=p["qty"], price=price, liquidity="taker")
|
|
102
|
+
return
|
|
103
|
+
acct["orders"] = [o for o in acct["orders"] if o is not hit["order"]]
|
|
104
|
+
fill(acct, side=hit["order"]["side"], qty=hit["order"]["qty"], price=price, liquidity="maker" if hit["kind"] == "limit" else "taker")
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def process_bar(acct: dict[str, Any], bar: dict[str, float], prev_close: float | None = None) -> None:
|
|
108
|
+
o, h, l, c = float(bar["o"]), float(bar["h"]), float(bar["l"]), float(bar["c"])
|
|
109
|
+
pc = o if prev_close is None else float(prev_close)
|
|
110
|
+
path = [o, l, h, c] if c >= o else [o, h, l, c]
|
|
111
|
+
segments = [(pc, o, True)] + [(path[i], path[i + 1], False) for i in range(3)]
|
|
112
|
+
for start, end, is_gap in segments:
|
|
113
|
+
if start == end:
|
|
114
|
+
continue
|
|
115
|
+
d = 1 if end > start else -1
|
|
116
|
+
at = start
|
|
117
|
+
for _ in range(100):
|
|
118
|
+
hits = [
|
|
119
|
+
t
|
|
120
|
+
for t in _triggers(acct)
|
|
121
|
+
if t["dir"] == d and ((at <= t["level"] <= end) if d > 0 else (end <= t["level"] <= at))
|
|
122
|
+
]
|
|
123
|
+
if not hits:
|
|
124
|
+
break
|
|
125
|
+
hits.sort(key=lambda t: d * t["level"])
|
|
126
|
+
_execute(acct, hits[0], end if is_gap else hits[0]["level"])
|
|
127
|
+
if not is_gap:
|
|
128
|
+
at = hits[0]["level"]
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
__all__ = ["FEE", "MMR", "create_account", "fill", "liq_price", "process_bar"]
|
|
File without changes
|