quantvn 0.2.1__tar.gz → 0.4.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.
Files changed (60) hide show
  1. {quantvn-0.2.1/quantvn.egg-info → quantvn-0.4.0}/PKG-INFO +106 -1
  2. {quantvn-0.2.1 → quantvn-0.4.0}/README.md +105 -0
  3. quantvn-0.4.0/quantvn/crypto/data/__init__.py +5 -0
  4. quantvn-0.4.0/quantvn/crypto/data/derivatives.py +202 -0
  5. quantvn-0.4.0/quantvn/crypto/data/download.py +52 -0
  6. quantvn-0.4.0/quantvn/fx/__init__.py +4 -0
  7. quantvn-0.4.0/quantvn/fx/data.py +103 -0
  8. quantvn-0.4.0/quantvn/marketdata.py +148 -0
  9. {quantvn-0.2.1 → quantvn-0.4.0}/quantvn/paper/single_asset.py +53 -3
  10. quantvn-0.4.0/quantvn/us/data/__init__.py +5 -0
  11. quantvn-0.4.0/quantvn/us/data/stocks.py +87 -0
  12. {quantvn-0.2.1 → quantvn-0.4.0/quantvn.egg-info}/PKG-INFO +106 -1
  13. {quantvn-0.2.1 → quantvn-0.4.0}/quantvn.egg-info/SOURCES.txt +4 -0
  14. {quantvn-0.2.1 → quantvn-0.4.0}/setup.py +1 -1
  15. quantvn-0.4.0/tests/test_markets.py +244 -0
  16. {quantvn-0.2.1 → quantvn-0.4.0}/tests/test_paper.py +18 -0
  17. quantvn-0.2.1/quantvn/crypto/data/__init__.py +0 -7
  18. quantvn-0.2.1/quantvn/crypto/data/derivatives.py +0 -85
  19. quantvn-0.2.1/quantvn/crypto/data/download.py +0 -56
  20. quantvn-0.2.1/quantvn/us/data/__init__.py +0 -5
  21. quantvn-0.2.1/quantvn/us/data/stocks.py +0 -60
  22. {quantvn-0.2.1 → quantvn-0.4.0}/LICENSE +0 -0
  23. {quantvn-0.2.1 → quantvn-0.4.0}/MANIFEST.in +0 -0
  24. {quantvn-0.2.1 → quantvn-0.4.0}/quantvn/__init__.py +0 -0
  25. {quantvn-0.2.1 → quantvn-0.4.0}/quantvn/crypto/__init__.py +0 -0
  26. {quantvn-0.2.1 → quantvn-0.4.0}/quantvn/crypto/metrics/__init__.py +0 -0
  27. {quantvn-0.2.1 → quantvn-0.4.0}/quantvn/crypto/metrics/backtest.py +0 -0
  28. {quantvn-0.2.1 → quantvn-0.4.0}/quantvn/crypto/metrics/metrics.py +0 -0
  29. {quantvn-0.2.1 → quantvn-0.4.0}/quantvn/metrics/__init__.py +0 -0
  30. {quantvn-0.2.1 → quantvn-0.4.0}/quantvn/metrics/_fills.py +0 -0
  31. {quantvn-0.2.1 → quantvn-0.4.0}/quantvn/metrics/portfolio.py +0 -0
  32. {quantvn-0.2.1 → quantvn-0.4.0}/quantvn/metrics/single_asset.py +0 -0
  33. {quantvn-0.2.1 → quantvn-0.4.0}/quantvn/metrics/st.py +0 -0
  34. {quantvn-0.2.1 → quantvn-0.4.0}/quantvn/paper/__init__.py +0 -0
  35. {quantvn-0.2.1 → quantvn-0.4.0}/quantvn/paper/client.py +0 -0
  36. {quantvn-0.2.1 → quantvn-0.4.0}/quantvn/paper/portfolio.py +0 -0
  37. {quantvn-0.2.1 → quantvn-0.4.0}/quantvn/strategy/__init__.py +0 -0
  38. {quantvn-0.2.1 → quantvn-0.4.0}/quantvn/strategy/frames.py +0 -0
  39. {quantvn-0.2.1 → quantvn-0.4.0}/quantvn/strategy/harness.py +0 -0
  40. {quantvn-0.2.1 → quantvn-0.4.0}/quantvn/strategy/script.py +0 -0
  41. {quantvn-0.2.1 → quantvn-0.4.0}/quantvn/us/__init__.py +0 -0
  42. {quantvn-0.2.1 → quantvn-0.4.0}/quantvn/us/metrics/__init__.py +0 -0
  43. {quantvn-0.2.1 → quantvn-0.4.0}/quantvn/us/metrics/backtest.py +0 -0
  44. {quantvn-0.2.1 → quantvn-0.4.0}/quantvn/vn/__init__.py +0 -0
  45. {quantvn-0.2.1 → quantvn-0.4.0}/quantvn/vn/data/__init__.py +0 -0
  46. {quantvn-0.2.1 → quantvn-0.4.0}/quantvn/vn/data/const.py +0 -0
  47. {quantvn-0.2.1 → quantvn-0.4.0}/quantvn/vn/data/core.py +0 -0
  48. {quantvn-0.2.1 → quantvn-0.4.0}/quantvn/vn/data/derivatives.py +0 -0
  49. {quantvn-0.2.1 → quantvn-0.4.0}/quantvn/vn/data/macro.py +0 -0
  50. {quantvn-0.2.1 → quantvn-0.4.0}/quantvn/vn/data/stocks.py +0 -0
  51. {quantvn-0.2.1 → quantvn-0.4.0}/quantvn/vn/data/utils.py +0 -0
  52. {quantvn-0.2.1 → quantvn-0.4.0}/quantvn/vn/metrics/__init__.py +0 -0
  53. {quantvn-0.2.1 → quantvn-0.4.0}/quantvn/vn/metrics/backtest.py +0 -0
  54. {quantvn-0.2.1 → quantvn-0.4.0}/quantvn/vn/metrics/metrics.py +0 -0
  55. {quantvn-0.2.1 → quantvn-0.4.0}/quantvn.egg-info/dependency_links.txt +0 -0
  56. {quantvn-0.2.1 → quantvn-0.4.0}/quantvn.egg-info/requires.txt +0 -0
  57. {quantvn-0.2.1 → quantvn-0.4.0}/quantvn.egg-info/top_level.txt +0 -0
  58. {quantvn-0.2.1 → quantvn-0.4.0}/setup.cfg +0 -0
  59. {quantvn-0.2.1 → quantvn-0.4.0}/tests/test_backtests.py +0 -0
  60. {quantvn-0.2.1 → quantvn-0.4.0}/tests/test_strategy.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: quantvn
3
- Version: 0.2.1
3
+ Version: 0.4.0
4
4
  Summary: QuantVN API Library for Financial Data Analysis
5
5
  Author: quantvn
6
6
  Classifier: Development Status :: 3 - Alpha
@@ -950,6 +950,98 @@ print(tr.record("bot-dau-tien")["fills"]) # các lần khớp: thời điể
950
950
  - `tr.publish(ten_bot)` công khai thành tích. Việc công khai là vĩnh viễn: về sau có thể đánh dấu rút lại, nhưng bản ghi vẫn xem được.
951
951
  - Khi máy chủ từ chối, thư viện báo `paper.TrackRecordError` với `code` như `rate_limited`, `position_out_of_range`, `bot_limit_reached`.
952
952
 
953
+ ### 6. Thị trường Mỹ và Crypto (từ bản 0.3.0)
954
+
955
+ Dữ liệu cổ phiếu/ETF Mỹ và crypto lấy từ **API dữ liệu thị trường của QuantVN**, kho giá QuantVN dùng cho paper trading: nến 1 phút, gắn nhãn theo **giờ mở cửa** của nến, chỉ gồm nến đã đóng. Không cần API key; có key (`client(apikey=...)`) thì hạn mức cao hơn.
956
+
957
+ | Bộ dữ liệu | Nội dung | Nguồn | Cập nhật |
958
+ |---|---|---|---|
959
+ | `crypto_spot` | ~40 cặp USDT spot của Binance, từ ngày niêm yết | Kho lưu trữ chính thức của Binance (data.binance.vision, có checksum) + REST API | 10 phút |
960
+ | `crypto_perp` | Hợp đồng vĩnh cửu USD-M của các cặp đó | như trên | 10 phút |
961
+ | `crypto_funding` | Funding rate từng kỳ | Binance | 10 phút |
962
+ | `us_stock` | S&P 500 + ~40 ETF, nến 1 phút phiên chính (09:30–16:00 New York) | Yahoo Finance: chỉ có 30 ngày gần nhất, kho dài thêm mỗi ngày | mỗi giờ |
963
+ | `us_stock_1d` | Nến ngày toàn bộ lịch sử, có `adj_close` | Yahoo Finance | mỗi ngày |
964
+ | `forex` | 28 cặp tiền của USD, EUR, GBP, JPY, CHF, AUD, CAD, NZD, cùng XAUUSD, XAGUSD; nến 1 phút từ 2000–2009 tùy mã | HistData (giá bid, công bố theo tháng); các tuần chưa công bố lấy giá giữa từ TradingView FX_IDC, phần cũ hơn 3,5 ngày lấy từ Yahoo (nến thô hơn) | 10 phút |
965
+
966
+ #### 6.1. Crypto
967
+
968
+ ```python
969
+ from quantvn.crypto.data import get_crypto_hist, get_funding_rates, list_crypto_symbols
970
+
971
+ list_crypto_symbols("spot")[:5] # các cặp có trong kho
972
+ btc = get_crypto_hist("BTCUSDT", "1h", start="2025-01-01", end="2026-01-01")
973
+ perp = get_crypto_hist("BTCUSDT", "1m", start="2026-11-01", market="perp")
974
+ fund = get_funding_rates("BTCUSDT", start="2026-01-01") # Datetime, rate, mark_price
975
+ ```
976
+
977
+ - Gọi như bản cũ, `get_crypto_hist("BTCUSDT")` (không có `start`/`end`), vẫn trả về giai đoạn 2019-07 đến 2022-12 như trước.
978
+ - Khung `1m 5m 15m 30m 1h 4h 1d` lấy từ API QuantVN; các khung khác (`3m`, `2h`, `1w`, ...) hoặc khi API không trả lời thì thư viện tải thẳng từ Binance (`source="binance"` để luôn dùng Binance).
979
+ - `Datetime` mặc định theo giờ Việt Nam như trước; `tz=None` cho UTC.
980
+
981
+ #### 6.2. Cổ phiếu Mỹ
982
+
983
+ ```python
984
+ from quantvn.us.data import get_us_hist, list_us_symbols
985
+
986
+ aapl = get_us_hist("AAPL", "1m", start="2026-11-01") # giờ New York
987
+ spy_daily = get_us_hist("SPY", "1d", start="2000-01-01")
988
+ ```
989
+
990
+ Gọi như bản cũ, `get_us_hist("AAPL")` (nến 1 phút, không có khoảng thời gian) vẫn đọc dịch vụ dữ liệu cũ và cần API key.
991
+
992
+ #### 6.3. Paper trading Mỹ và Crypto
993
+
994
+ `paper.simulate` có thêm hai thị trường, cùng quy tắc với dịch vụ Track Record:
995
+
996
+ | Thị trường | Vị thế | Phí mỗi chiều | Ghi chú |
997
+ |---|---|---|---|
998
+ | `CRYPTO` | 0 đến 1 | 10 bp | spot |
999
+ | `CRYPTO_PERP` | -1 đến 1 | 5 bp | trả/nhận funding ở mỗi kỳ funding |
1000
+ | `US_STOCK` | -1 đến 1 | 1 bp | |
1001
+
1002
+ ```python
1003
+ from quantvn import paper
1004
+ from quantvn.crypto.data import get_crypto_hist, get_funding_rates
1005
+
1006
+ df = get_crypto_hist("ETHUSDT", "1m", start="2026-10-01", end="2026-11-01", market="perp", tz=None)
1007
+ df["position"] = ... # tỷ trọng vốn, quyết định tại giá đóng cửa từng nến
1008
+ fund = get_funding_rates("ETHUSDT", start="2026-10-01", end="2026-11-01")
1009
+ print(paper.simulate(df, market="CRYPTO_PERP", funding=fund))
1010
+ ```
1011
+
1012
+ Funding: một kỳ funding tại thời điểm t được tính ở nến đầu tiên mở cửa từ t trở đi, trên tỷ trọng đang giữ **trước** lệnh khớp ở nến đó: vốn nhân với `1 - tỷ trọng x rate` (vị thế mua trả khi rate dương, vị thế bán nhận). Kết quả của `simulate` trùng với engine của Track Record (chênh lệch tương đối dưới 1e-13 trên 200 kịch bản ngẫu nhiên). Gửi vị thế lên Track Record vẫn qua `TrackRecord.send` (mục 5.5); thị trường nào đang nhận vị thế xem ở `TrackRecord.assets()`.
1013
+
1014
+ #### 6.4. API trực tiếp
1015
+
1016
+ ```python
1017
+ from quantvn import marketdata
1018
+ marketdata.datasets() # độ phủ và hạn mức hiện tại
1019
+ marketdata.bars("crypto_spot", "SOLUSDT", "2026-11-01", "2026-11-02", interval="15m") # ts = ms UTC
1020
+ ```
1021
+
1022
+ Hạn mức (mặc định): không có key 30 yêu cầu/phút và 5 triệu dòng/ngày; có key 120 yêu cầu/phút và 50 triệu dòng/ngày; tối đa 600.000 dòng mỗi yêu cầu (thư viện tự chia nhỏ). Vượt hạn mức: HTTP 429, thư viện tự chờ và thử lại. Đổi địa chỉ API bằng biến môi trường `QUANTVN_DATA_URL`.
1023
+
1024
+ #### 6.5. Forex
1025
+
1026
+ ```python
1027
+ from quantvn import paper
1028
+ from quantvn.fx import data as fx
1029
+
1030
+ fx.list_symbols() # 30 mã: EURUSD, USDJPY, ..., XAUUSD, XAGUSD
1031
+ df = fx.get_hist("EURUSD", "15m", start="2026-10-01", end="2026-11-01") # Datetime theo UTC, volume rỗng
1032
+ df["position"] = ... # tỷ trọng vốn, -1 đến 1
1033
+ swap = fx.swap_schedule("EURUSD", "2026-10-01", "2026-11-01", rates={"EUR": 2.65, "USD": 4.0})
1034
+ print(paper.simulate(df, market="FOREX", symbol="EURUSD", funding=swap))
1035
+ ```
1036
+
1037
+ Chi phí giống Track Record (thị trường `FOREX`, mở từ 16/11/2026):
1038
+
1039
+ - **Phí:** 0,35 bp mỗi chiều, bằng hoa hồng tài khoản ECN (3,5 USD cho 100.000 đơn vị).
1040
+ - **Chênh lệch giá mua/bán:** mỗi lệnh khớp trả thêm nửa spread của cặp đó, đo trên dữ liệu tick HistData 2019 và 2023 (`fx.HALF_SPREAD_BP`): 0,15 bp với EURUSD, 0,25 bp với USDJPY, đến 1,7 bp với NZDCHF và 7,45 bp với XAGUSD. Truyền `symbol=` để `simulate` tính khoản này.
1041
+ - **Swap qua đêm:** giữ vị thế qua 17:00 New York thì trả hoặc nhận chênh lệch lãi suất hai đồng tiền, `(r_quote - r_base) / 365` mỗi ngày với vị thế mua; phiên thứ Tư tính 3 ngày. Track Record dùng lãi suất điều hành của ngân hàng trung ương; `swap_schedule` nhận lãi suất bạn đưa vào (phần trăm/năm). Vàng, bạc không có lãi suất, nên mua XAUUSD phải trả lãi suất USD.
1042
+
1043
+ Nến `1d` của API là ngày UTC, không phải ngày forex kết thúc lúc 17:00 New York. Giá trước tháng HistData công bố gần nhất là giá bid, sau đó là giá giữa, nên tại điểm nối có thể lệch khoảng nửa spread.
1044
+
953
1045
  ---
954
1046
 
955
1047
  ## Ví dụ thực tế
@@ -1014,6 +1106,19 @@ Dự án này được phát hành theo giấy phép **MIT License**. Xem file [
1014
1106
 
1015
1107
  ## Changelog
1016
1108
 
1109
+ ### Version 0.4.0
1110
+
1111
+ - Thêm `quantvn.fx`: `get_hist`, `list_symbols`, `swap_schedule`, `HALF_SPREAD_BP` cho 28 cặp tiền chính, XAUUSD và XAGUSD (bộ dữ liệu `forex` của API dữ liệu thị trường, mục 6.5)
1112
+ - `paper.simulate`: thêm thị trường `FOREX` (phí 0,35 bp, nửa spread từng cặp qua `symbol=`, swap qua `funding=`), trùng với Track Record
1113
+
1114
+ ### Version 0.3.0
1115
+
1116
+ - Thêm `quantvn.marketdata`: client của API dữ liệu thị trường QuantVN (cổ phiếu/ETF Mỹ, crypto spot và vĩnh cửu Binance, funding rate) có hạn mức theo key/địa chỉ (mục 6)
1117
+ - `get_crypto_hist`: thêm `start`, `end`, `market="perp"`, `tz`, `source`; tải dữ liệu sau 2022; đọc đúng thời gian micro giây trong kho Binance từ 2025. Gọi không có `start`/`end` cho kết quả như cũ
1118
+ - Thêm `get_funding_rates`, `list_crypto_symbols`, `list_us_symbols`
1119
+ - `get_us_hist`: thêm khung `5m 15m 30m 1h 1d`, `start`, `end`, `tz`. Gọi như cũ vẫn dùng dịch vụ cũ
1120
+ - `paper.simulate`: thêm thị trường `CRYPTO_PERP` (có funding, tham số `funding`) và `US_STOCK`, trùng với Track Record
1121
+
1017
1122
  ### Version 0.2.1
1018
1123
 
1019
1124
  - Chi phí của `Backtest_Derivates` và `Backtest_Stock` trùng với website QuantVN: phí HNX, thuế thu nhập cá nhân và phí quản lý vị thế VSDC cho phái sinh; phí 0,1% và thuế bán 0,1% cho cổ phiếu, bán được từ 13:00 ngày T+2 (mục 4.0). Cùng một chiến lược cho cùng một kết quả trong thư viện và khi bấm "Run test"
@@ -916,6 +916,98 @@ print(tr.record("bot-dau-tien")["fills"]) # các lần khớp: thời điể
916
916
  - `tr.publish(ten_bot)` công khai thành tích. Việc công khai là vĩnh viễn: về sau có thể đánh dấu rút lại, nhưng bản ghi vẫn xem được.
917
917
  - Khi máy chủ từ chối, thư viện báo `paper.TrackRecordError` với `code` như `rate_limited`, `position_out_of_range`, `bot_limit_reached`.
918
918
 
919
+ ### 6. Thị trường Mỹ và Crypto (từ bản 0.3.0)
920
+
921
+ Dữ liệu cổ phiếu/ETF Mỹ và crypto lấy từ **API dữ liệu thị trường của QuantVN**, kho giá QuantVN dùng cho paper trading: nến 1 phút, gắn nhãn theo **giờ mở cửa** của nến, chỉ gồm nến đã đóng. Không cần API key; có key (`client(apikey=...)`) thì hạn mức cao hơn.
922
+
923
+ | Bộ dữ liệu | Nội dung | Nguồn | Cập nhật |
924
+ |---|---|---|---|
925
+ | `crypto_spot` | ~40 cặp USDT spot của Binance, từ ngày niêm yết | Kho lưu trữ chính thức của Binance (data.binance.vision, có checksum) + REST API | 10 phút |
926
+ | `crypto_perp` | Hợp đồng vĩnh cửu USD-M của các cặp đó | như trên | 10 phút |
927
+ | `crypto_funding` | Funding rate từng kỳ | Binance | 10 phút |
928
+ | `us_stock` | S&P 500 + ~40 ETF, nến 1 phút phiên chính (09:30–16:00 New York) | Yahoo Finance: chỉ có 30 ngày gần nhất, kho dài thêm mỗi ngày | mỗi giờ |
929
+ | `us_stock_1d` | Nến ngày toàn bộ lịch sử, có `adj_close` | Yahoo Finance | mỗi ngày |
930
+ | `forex` | 28 cặp tiền của USD, EUR, GBP, JPY, CHF, AUD, CAD, NZD, cùng XAUUSD, XAGUSD; nến 1 phút từ 2000–2009 tùy mã | HistData (giá bid, công bố theo tháng); các tuần chưa công bố lấy giá giữa từ TradingView FX_IDC, phần cũ hơn 3,5 ngày lấy từ Yahoo (nến thô hơn) | 10 phút |
931
+
932
+ #### 6.1. Crypto
933
+
934
+ ```python
935
+ from quantvn.crypto.data import get_crypto_hist, get_funding_rates, list_crypto_symbols
936
+
937
+ list_crypto_symbols("spot")[:5] # các cặp có trong kho
938
+ btc = get_crypto_hist("BTCUSDT", "1h", start="2025-01-01", end="2026-01-01")
939
+ perp = get_crypto_hist("BTCUSDT", "1m", start="2026-11-01", market="perp")
940
+ fund = get_funding_rates("BTCUSDT", start="2026-01-01") # Datetime, rate, mark_price
941
+ ```
942
+
943
+ - Gọi như bản cũ, `get_crypto_hist("BTCUSDT")` (không có `start`/`end`), vẫn trả về giai đoạn 2019-07 đến 2022-12 như trước.
944
+ - Khung `1m 5m 15m 30m 1h 4h 1d` lấy từ API QuantVN; các khung khác (`3m`, `2h`, `1w`, ...) hoặc khi API không trả lời thì thư viện tải thẳng từ Binance (`source="binance"` để luôn dùng Binance).
945
+ - `Datetime` mặc định theo giờ Việt Nam như trước; `tz=None` cho UTC.
946
+
947
+ #### 6.2. Cổ phiếu Mỹ
948
+
949
+ ```python
950
+ from quantvn.us.data import get_us_hist, list_us_symbols
951
+
952
+ aapl = get_us_hist("AAPL", "1m", start="2026-11-01") # giờ New York
953
+ spy_daily = get_us_hist("SPY", "1d", start="2000-01-01")
954
+ ```
955
+
956
+ Gọi như bản cũ, `get_us_hist("AAPL")` (nến 1 phút, không có khoảng thời gian) vẫn đọc dịch vụ dữ liệu cũ và cần API key.
957
+
958
+ #### 6.3. Paper trading Mỹ và Crypto
959
+
960
+ `paper.simulate` có thêm hai thị trường, cùng quy tắc với dịch vụ Track Record:
961
+
962
+ | Thị trường | Vị thế | Phí mỗi chiều | Ghi chú |
963
+ |---|---|---|---|
964
+ | `CRYPTO` | 0 đến 1 | 10 bp | spot |
965
+ | `CRYPTO_PERP` | -1 đến 1 | 5 bp | trả/nhận funding ở mỗi kỳ funding |
966
+ | `US_STOCK` | -1 đến 1 | 1 bp | |
967
+
968
+ ```python
969
+ from quantvn import paper
970
+ from quantvn.crypto.data import get_crypto_hist, get_funding_rates
971
+
972
+ df = get_crypto_hist("ETHUSDT", "1m", start="2026-10-01", end="2026-11-01", market="perp", tz=None)
973
+ df["position"] = ... # tỷ trọng vốn, quyết định tại giá đóng cửa từng nến
974
+ fund = get_funding_rates("ETHUSDT", start="2026-10-01", end="2026-11-01")
975
+ print(paper.simulate(df, market="CRYPTO_PERP", funding=fund))
976
+ ```
977
+
978
+ Funding: một kỳ funding tại thời điểm t được tính ở nến đầu tiên mở cửa từ t trở đi, trên tỷ trọng đang giữ **trước** lệnh khớp ở nến đó: vốn nhân với `1 - tỷ trọng x rate` (vị thế mua trả khi rate dương, vị thế bán nhận). Kết quả của `simulate` trùng với engine của Track Record (chênh lệch tương đối dưới 1e-13 trên 200 kịch bản ngẫu nhiên). Gửi vị thế lên Track Record vẫn qua `TrackRecord.send` (mục 5.5); thị trường nào đang nhận vị thế xem ở `TrackRecord.assets()`.
979
+
980
+ #### 6.4. API trực tiếp
981
+
982
+ ```python
983
+ from quantvn import marketdata
984
+ marketdata.datasets() # độ phủ và hạn mức hiện tại
985
+ marketdata.bars("crypto_spot", "SOLUSDT", "2026-11-01", "2026-11-02", interval="15m") # ts = ms UTC
986
+ ```
987
+
988
+ Hạn mức (mặc định): không có key 30 yêu cầu/phút và 5 triệu dòng/ngày; có key 120 yêu cầu/phút và 50 triệu dòng/ngày; tối đa 600.000 dòng mỗi yêu cầu (thư viện tự chia nhỏ). Vượt hạn mức: HTTP 429, thư viện tự chờ và thử lại. Đổi địa chỉ API bằng biến môi trường `QUANTVN_DATA_URL`.
989
+
990
+ #### 6.5. Forex
991
+
992
+ ```python
993
+ from quantvn import paper
994
+ from quantvn.fx import data as fx
995
+
996
+ fx.list_symbols() # 30 mã: EURUSD, USDJPY, ..., XAUUSD, XAGUSD
997
+ df = fx.get_hist("EURUSD", "15m", start="2026-10-01", end="2026-11-01") # Datetime theo UTC, volume rỗng
998
+ df["position"] = ... # tỷ trọng vốn, -1 đến 1
999
+ swap = fx.swap_schedule("EURUSD", "2026-10-01", "2026-11-01", rates={"EUR": 2.65, "USD": 4.0})
1000
+ print(paper.simulate(df, market="FOREX", symbol="EURUSD", funding=swap))
1001
+ ```
1002
+
1003
+ Chi phí giống Track Record (thị trường `FOREX`, mở từ 16/11/2026):
1004
+
1005
+ - **Phí:** 0,35 bp mỗi chiều, bằng hoa hồng tài khoản ECN (3,5 USD cho 100.000 đơn vị).
1006
+ - **Chênh lệch giá mua/bán:** mỗi lệnh khớp trả thêm nửa spread của cặp đó, đo trên dữ liệu tick HistData 2019 và 2023 (`fx.HALF_SPREAD_BP`): 0,15 bp với EURUSD, 0,25 bp với USDJPY, đến 1,7 bp với NZDCHF và 7,45 bp với XAGUSD. Truyền `symbol=` để `simulate` tính khoản này.
1007
+ - **Swap qua đêm:** giữ vị thế qua 17:00 New York thì trả hoặc nhận chênh lệch lãi suất hai đồng tiền, `(r_quote - r_base) / 365` mỗi ngày với vị thế mua; phiên thứ Tư tính 3 ngày. Track Record dùng lãi suất điều hành của ngân hàng trung ương; `swap_schedule` nhận lãi suất bạn đưa vào (phần trăm/năm). Vàng, bạc không có lãi suất, nên mua XAUUSD phải trả lãi suất USD.
1008
+
1009
+ Nến `1d` của API là ngày UTC, không phải ngày forex kết thúc lúc 17:00 New York. Giá trước tháng HistData công bố gần nhất là giá bid, sau đó là giá giữa, nên tại điểm nối có thể lệch khoảng nửa spread.
1010
+
919
1011
  ---
920
1012
 
921
1013
  ## Ví dụ thực tế
@@ -980,6 +1072,19 @@ Dự án này được phát hành theo giấy phép **MIT License**. Xem file [
980
1072
 
981
1073
  ## Changelog
982
1074
 
1075
+ ### Version 0.4.0
1076
+
1077
+ - Thêm `quantvn.fx`: `get_hist`, `list_symbols`, `swap_schedule`, `HALF_SPREAD_BP` cho 28 cặp tiền chính, XAUUSD và XAGUSD (bộ dữ liệu `forex` của API dữ liệu thị trường, mục 6.5)
1078
+ - `paper.simulate`: thêm thị trường `FOREX` (phí 0,35 bp, nửa spread từng cặp qua `symbol=`, swap qua `funding=`), trùng với Track Record
1079
+
1080
+ ### Version 0.3.0
1081
+
1082
+ - Thêm `quantvn.marketdata`: client của API dữ liệu thị trường QuantVN (cổ phiếu/ETF Mỹ, crypto spot và vĩnh cửu Binance, funding rate) có hạn mức theo key/địa chỉ (mục 6)
1083
+ - `get_crypto_hist`: thêm `start`, `end`, `market="perp"`, `tz`, `source`; tải dữ liệu sau 2022; đọc đúng thời gian micro giây trong kho Binance từ 2025. Gọi không có `start`/`end` cho kết quả như cũ
1084
+ - Thêm `get_funding_rates`, `list_crypto_symbols`, `list_us_symbols`
1085
+ - `get_us_hist`: thêm khung `5m 15m 30m 1h 1d`, `start`, `end`, `tz`. Gọi như cũ vẫn dùng dịch vụ cũ
1086
+ - `paper.simulate`: thêm thị trường `CRYPTO_PERP` (có funding, tham số `funding`) và `US_STOCK`, trùng với Track Record
1087
+
983
1088
  ### Version 0.2.1
984
1089
 
985
1090
  - Chi phí của `Backtest_Derivates` và `Backtest_Stock` trùng với website QuantVN: phí HNX, thuế thu nhập cá nhân và phí quản lý vị thế VSDC cho phái sinh; phí 0,1% và thuế bán 0,1% cho cổ phiếu, bán được từ 13:00 ngày T+2 (mục 4.0). Cùng một chiến lược cho cùng một kết quả trong thư viện và khi bấm "Run test"
@@ -0,0 +1,5 @@
1
+ from __future__ import annotations
2
+
3
+ from .derivatives import get_funding_rates, get_hist as get_crypto_hist, list_symbols as list_crypto_symbols
4
+
5
+ __all__ = ["get_crypto_hist", "get_funding_rates", "list_crypto_symbols"]
@@ -0,0 +1,202 @@
1
+ """Crypto prices: Binance spot and USD-M perpetual futures, and perpetual funding rates.
2
+
3
+ Data come from the QuantVN market-data API (the store QuantVN uses for paper trading, refreshed every 10
4
+ minutes) or, when it cannot be reached or the interval is one it does not serve, straight from Binance's
5
+ public archive and REST API. Both give Binance's own record of its market.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import time
10
+ from concurrent.futures import ThreadPoolExecutor, as_completed
11
+ from datetime import datetime, timedelta, timezone
12
+ from pathlib import Path
13
+ from typing import Optional, Union
14
+
15
+ import pandas as pd
16
+ import requests
17
+
18
+ from quantvn import marketdata
19
+ from quantvn.crypto.data.download import VALID_INTERVALS, download_monthly, extract_csv
20
+
21
+ __all__ = ["get_hist", "get_funding_rates", "list_symbols"]
22
+
23
+ VN_TZ = timezone(timedelta(hours=7))
24
+ COLUMNS = ["Datetime", "Date", "time", "Open", "High", "Low", "Close", "volume"]
25
+ # The window get_hist returned before 0.3, and still returns when no start or end is given.
26
+ LEGACY_START = datetime(2019, 7, 1, tzinfo=VN_TZ)
27
+ LEGACY_END = datetime(2022, 12, 31, 23, 59, 59, tzinfo=VN_TZ)
28
+ _MARKETS = {"spot": "crypto_spot", "perp": "crypto_perp"}
29
+ _REST = {"spot": "https://api.binance.com/api/v3/klines", "perp": "https://fapi.binance.com/fapi/v1/klines"}
30
+ _INTERVAL_MS = {"1m": 60_000, "3m": 180_000, "5m": 300_000, "15m": 900_000, "30m": 1_800_000, "1h": 3_600_000,
31
+ "2h": 7_200_000, "4h": 14_400_000, "6h": 21_600_000, "8h": 28_800_000, "12h": 43_200_000,
32
+ "1d": 86_400_000, "3d": 259_200_000, "1w": 604_800_000}
33
+
34
+
35
+ def get_hist(
36
+ symbol: str,
37
+ interval: str = "1m",
38
+ cache_dir: Optional[Union[str, Path]] = None,
39
+ start=None,
40
+ end=None,
41
+ market: str = "spot",
42
+ tz: Optional[str] = "Asia/Ho_Chi_Minh",
43
+ source: str = "auto",
44
+ ) -> pd.DataFrame:
45
+ """Historical OHLCV bars of a Binance pair.
46
+
47
+ Args:
48
+ symbol: Binance symbol, e.g. "BTCUSDT".
49
+ interval: 1m 3m 5m 15m 30m 1h 2h 4h 6h 8h 12h 1d 3d 1w 1M.
50
+ cache_dir: where monthly archives are kept when they are downloaded from Binance (default ~/.cache/quantvn).
51
+ start, end: the window (dates, datetimes or epoch ms; end exclusive; without a time zone = UTC).
52
+ When both are omitted the window is 2019-07-01 to 2022-12-31 (Vietnam time), as before 0.3.
53
+ When only end is omitted it is now.
54
+ market: "spot" or "perp" (USD-M perpetual futures, last price).
55
+ tz: time zone of the Datetime column (default Vietnam time, as before; None = UTC).
56
+ source: "auto" (QuantVN API, falling back to Binance), "quantvn" or "binance".
57
+
58
+ Returns:
59
+ DataFrame [Datetime, Date, time, Open, High, Low, Close, volume]; Datetime is the bar's OPEN time.
60
+ Only bars that have closed are returned.
61
+ """
62
+ if interval not in VALID_INTERVALS:
63
+ raise ValueError(f"Invalid interval {interval!r}. Choose one of: {', '.join(sorted(VALID_INTERVALS))}")
64
+ if market not in _MARKETS:
65
+ raise ValueError("market must be 'spot' or 'perp'")
66
+ if source not in ("auto", "quantvn", "binance"):
67
+ raise ValueError("source must be 'auto', 'quantvn' or 'binance'")
68
+ symbol = symbol.upper().strip()
69
+ now = int(time.time() * 1000)
70
+ if start is None and end is None:
71
+ start_ms, end_ms = int(LEGACY_START.timestamp() * 1000), int(LEGACY_END.timestamp() * 1000) + 1000
72
+ else:
73
+ end_ms = marketdata.to_ms(end, now)
74
+ start_ms = marketdata.to_ms(start, int(LEGACY_START.timestamp() * 1000))
75
+ if start_ms >= end_ms:
76
+ raise ValueError("start must be before end")
77
+
78
+ if source != "binance" and interval in marketdata.INTERVALS:
79
+ try:
80
+ df = marketdata.bars(_MARKETS[market], symbol, start_ms, end_ms, interval)
81
+ newest = df.attrs.get("newest")
82
+ want = min(end_ms, now)
83
+ # the store may not reach the end of the window yet (a symbol still downloading, a late refresh):
84
+ # take the rest from Binance, from the first minute the store does not have
85
+ if source == "auto" and newest is not None and newest + 60_000 < want - 15 * 60_000:
86
+ step = marketdata.INTERVALS[interval] * 60_000
87
+ rest_from = max(start_ms, (newest + 60_000 + step - 1) // step * step)
88
+ if rest_from < want:
89
+ rest = _from_binance(symbol, interval, rest_from, want, market, cache_dir, None)
90
+ head = marketdata.to_candles(df, None)
91
+ head = head[head["Datetime"] < pd.Timestamp(rest_from, unit="ms", tz="UTC")]
92
+ both = pd.concat([x for x in (head, rest) if len(x)], ignore_index=True) if len(head) or len(rest) else head
93
+ if tz and len(both):
94
+ both["Datetime"] = both["Datetime"].dt.tz_convert(tz)
95
+ both["Date"] = both["Datetime"].dt.strftime("%Y-%m-%d")
96
+ both["time"] = both["Datetime"].dt.strftime("%H:%M:%S")
97
+ return both.reset_index(drop=True)
98
+ return marketdata.to_candles(df, tz)
99
+ except (requests.RequestException, marketdata.MarketDataError) as e:
100
+ if source == "quantvn" or (isinstance(e, marketdata.MarketDataError) and e.code in ("invalid_time",)):
101
+ raise
102
+ elif source == "quantvn":
103
+ raise ValueError(f"the QuantVN API serves {', '.join(marketdata.INTERVALS)}; use source='binance' for {interval}")
104
+ return _from_binance(symbol, interval, start_ms, min(end_ms, now), market, cache_dir, tz)
105
+
106
+
107
+ def _from_binance(symbol, interval, start_ms, end_ms, market, cache_dir, tz) -> pd.DataFrame:
108
+ cache = Path(cache_dir or Path.home() / ".cache/quantvn")
109
+ first = datetime.fromtimestamp(start_ms / 1000, timezone.utc).replace(day=1, hour=0, minute=0, second=0,
110
+ microsecond=0)
111
+ last = datetime.fromtimestamp((end_ms - 1) / 1000, timezone.utc)
112
+ this_month = datetime.now(timezone.utc).replace(day=1, hour=0, minute=0, second=0, microsecond=0)
113
+ months, m = [], first
114
+ while m <= last and m < this_month:
115
+ months.append(m.strftime("%Y-%m"))
116
+ m = m.replace(year=m.year + (m.month == 12), month=m.month % 12 + 1)
117
+
118
+ results = {}
119
+
120
+ def fetch(month):
121
+ return month, extract_csv(download_monthly(symbol, interval, month, cache, market))
122
+
123
+ with ThreadPoolExecutor(max_workers=8) as ex:
124
+ futures = {ex.submit(fetch, mo): mo for mo in months}
125
+ for fut in as_completed(futures):
126
+ try:
127
+ mo, df = fut.result()
128
+ results[mo] = df
129
+ except Exception as e: # a month Binance has not archived: the REST API covers it
130
+ print(f"Skip {symbol} {interval} {futures[fut]}: {e}")
131
+ parts = [results[mo] for mo in sorted(results)]
132
+ covered = max((int(p["t"].max()) for p in parts if len(p)), default=start_ms - 1)
133
+ if covered + 1 < end_ms and interval in _INTERVAL_MS:
134
+ parts.append(_rest(symbol, interval, max(covered + 1, start_ms), end_ms, market))
135
+ parts = [p for p in parts if len(p)]
136
+ if not parts:
137
+ return pd.DataFrame(columns=COLUMNS)
138
+ df = pd.concat(parts, ignore_index=True).drop_duplicates("t").sort_values("t")
139
+ step = _INTERVAL_MS.get(interval, 0)
140
+ now = int(time.time() * 1000)
141
+ df = df[(df["t"] >= start_ms) & (df["t"] < end_ms) & (df["t"] + step <= now)]
142
+ df = df.rename(columns={"t": "ts", "Open": "open", "High": "high", "Low": "low", "Close": "close",
143
+ "Volume": "volume"})
144
+ return marketdata.to_candles(df, tz)
145
+
146
+
147
+ def _rest(symbol, interval, start_ms, end_ms, market) -> pd.DataFrame:
148
+ rows, a = [], start_ms
149
+ limit = 1000
150
+ while a < end_ms:
151
+ r = requests.get(_REST[market], params={"symbol": symbol, "interval": interval, "startTime": a,
152
+ "endTime": end_ms - 1, "limit": limit}, timeout=30)
153
+ r.raise_for_status()
154
+ d = r.json()
155
+ if not d:
156
+ break
157
+ rows += [(int(k[0]), float(k[1]), float(k[2]), float(k[3]), float(k[4]), float(k[5])) for k in d]
158
+ a = int(d[-1][0]) + _INTERVAL_MS[interval]
159
+ if len(d) < limit:
160
+ break
161
+ return pd.DataFrame(rows, columns=["t", "Open", "High", "Low", "Close", "Volume"])
162
+
163
+
164
+ def get_funding_rates(symbol: str, start=None, end=None, source: str = "auto") -> pd.DataFrame:
165
+ """Funding events of a Binance USD-M perpetual: columns Datetime (UTC), rate, mark_price.
166
+
167
+ A long position pays ``rate x notional`` at each event (a short receives it). Default window: the last
168
+ 365 days. ``quantvn.paper.simulate(..., market="CRYPTO_PERP", funding=...)`` takes this frame."""
169
+ symbol = symbol.upper().strip()
170
+ now = int(time.time() * 1000)
171
+ end_ms = marketdata.to_ms(end, now)
172
+ start_ms = marketdata.to_ms(start, end_ms - 365 * 86_400_000)
173
+ df = None
174
+ if source != "binance":
175
+ try:
176
+ df = marketdata.funding(symbol, start_ms, end_ms)
177
+ except (requests.RequestException, marketdata.MarketDataError):
178
+ if source == "quantvn":
179
+ raise
180
+ if df is None:
181
+ rows, a = [], start_ms
182
+ while a < end_ms:
183
+ r = requests.get("https://fapi.binance.com/fapi/v1/fundingRate",
184
+ params={"symbol": symbol, "startTime": a, "endTime": end_ms - 1, "limit": 1000}, timeout=30)
185
+ r.raise_for_status()
186
+ d = r.json()
187
+ if not d:
188
+ break
189
+ rows += [(int(x["fundingTime"]) // 1000 * 1000, float(x["fundingRate"]),
190
+ float(x["markPrice"]) if x.get("markPrice") else float("nan")) for x in d]
191
+ a = int(d[-1]["fundingTime"]) + 1
192
+ if len(d) < 1000:
193
+ break
194
+ df = pd.DataFrame(rows, columns=["ts", "rate", "mark_price"])
195
+ out = pd.DataFrame({"Datetime": pd.to_datetime(df["ts"].astype("int64"), unit="ms", utc=True),
196
+ "rate": df["rate"].astype(float), "mark_price": df["mark_price"].astype(float)})
197
+ return out.reset_index(drop=True)
198
+
199
+
200
+ def list_symbols(market: str = "spot") -> list:
201
+ """Symbols the QuantVN API stores for a market: "spot", "perp" or "funding"."""
202
+ return marketdata.symbols({"spot": "crypto_spot", "perp": "crypto_perp", "funding": "crypto_funding"}[market])
@@ -0,0 +1,52 @@
1
+ """Binance's public archive (data.binance.vision): one zip per symbol, interval and month, no key needed."""
2
+ import io
3
+ import zipfile
4
+ from pathlib import Path
5
+
6
+ import numpy as np
7
+ import pandas as pd
8
+ import requests
9
+
10
+ BASE = "https://data.binance.vision/data"
11
+ MARKET_PATH = {"spot": "spot", "perp": "futures/um"}
12
+ BASE_URL = f"{BASE}/spot/monthly/klines/" # kept for code written against 0.2
13
+
14
+ VALID_INTERVALS = {
15
+ "1m", "3m", "5m", "15m", "30m",
16
+ "1h", "2h", "4h", "6h", "8h", "12h",
17
+ "1d", "3d", "1w", "1M",
18
+ }
19
+
20
+
21
+ def download_monthly(symbol: str, interval: str, month: str, cache_dir: Path, market: str = "spot") -> Path:
22
+ """Download (once) the monthly zip of a symbol and interval, return its local path. Raises RuntimeError
23
+ when Binance has no file for that month."""
24
+ folder = cache_dir / ("" if market == "spot" else market) / symbol / interval
25
+ folder.mkdir(parents=True, exist_ok=True)
26
+ zip_name = f"{symbol}-{interval}-{month}.zip"
27
+ zip_path = folder / zip_name
28
+ if zip_path.exists():
29
+ return zip_path
30
+ url = f"{BASE}/{MARKET_PATH[market]}/monthly/klines/{symbol}/{interval}/{zip_name}"
31
+ resp = requests.get(url, stream=True, timeout=60)
32
+ if resp.status_code != 200:
33
+ raise RuntimeError(f"File not found: {url}")
34
+ tmp = zip_path.with_suffix(".part")
35
+ with open(tmp, "wb") as f:
36
+ for chunk in resp.iter_content(1024 * 1024):
37
+ f.write(chunk)
38
+ tmp.replace(zip_path)
39
+ return zip_path
40
+
41
+
42
+ def extract_csv(zip_path: Path) -> pd.DataFrame:
43
+ """The klines of a monthly zip: columns t (open time, ms UTC), Open, High, Low, Close, Volume.
44
+ Handles the header row of the futures archive and the microsecond times of the spot archive from 2025."""
45
+ with zipfile.ZipFile(zip_path, "r") as zf:
46
+ with zf.open(zf.namelist()[0]) as f:
47
+ df = pd.read_csv(io.TextIOWrapper(f), header=None, usecols=range(6), dtype=str)
48
+ df.columns = ["t", "Open", "High", "Low", "Close", "Volume"]
49
+ df = df.apply(pd.to_numeric, errors="coerce").dropna(subset=["t", "Open", "Close"])
50
+ t = df["t"].astype("int64").to_numpy()
51
+ df["t"] = np.where(t > 10 ** 14, t // 1000, t)
52
+ return df.reset_index(drop=True)
@@ -0,0 +1,4 @@
1
+ from quantvn.fx import data
2
+ from quantvn.fx.data import get_hist as get_fx_hist, list_symbols as list_fx_symbols, swap_schedule
3
+
4
+ __all__ = ["data", "get_fx_hist", "list_fx_symbols", "swap_schedule"]
@@ -0,0 +1,103 @@
1
+ """Forex: the 28 pairs of USD, EUR, GBP, JPY, CHF, AUD, CAD, NZD, plus XAUUSD and XAGUSD.
2
+
3
+ Bars come from the QuantVN market-data API (dataset ``forex``): HistData 1-minute BID bars, and for the weeks
4
+ HistData has not published yet, live mid quotes (TradingView FX_IDC; Yahoo for older gaps of pairs). The
5
+ same prices, the same per-pair spread (``HALF_SPREAD_BP``) and the same swap rule are used by the QuantVN
6
+ Track Record service for ``FOREX`` paper trades.
7
+
8
+ from quantvn.fx import data
9
+ df = data.get_hist("EURUSD", "15m", "2026-10-01", "2026-11-01")
10
+ swap = data.swap_schedule("EURUSD", "2026-10-01", "2026-11-01", rates={"EUR": 2.65, "USD": 4.0})
11
+ quantvn.paper.simulate(df.assign(position=...), market="FOREX", symbol="EURUSD", funding=swap)
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import datetime as dt
16
+ import time
17
+ from typing import Optional
18
+ from zoneinfo import ZoneInfo
19
+
20
+ import pandas as pd
21
+
22
+ from quantvn import marketdata
23
+
24
+ __all__ = ["HALF_SPREAD_BP", "PAIRS", "get_hist", "list_symbols", "swap_schedule"]
25
+
26
+ # Half the bid-ask spread per side, bp: HistData tick data 2019 and 2023, the larger year (Track Record engine/fx.py).
27
+ HALF_SPREAD_BP = {
28
+ "EURUSD": 0.15, "GBPUSD": 0.40, "USDJPY": 0.25, "USDCHF": 0.60, "AUDUSD": 0.80, "USDCAD": 0.50, "NZDUSD": 0.95,
29
+ "EURJPY": 0.40, "EURGBP": 0.60, "EURCHF": 0.65, "EURAUD": 0.80, "EURCAD": 0.70, "EURNZD": 0.90, "GBPJPY": 0.70,
30
+ "GBPCHF": 0.90, "GBPAUD": 0.85, "GBPCAD": 1.00, "GBPNZD": 1.10, "AUDJPY": 0.55, "AUDCAD": 1.15, "AUDCHF": 1.25,
31
+ "AUDNZD": 1.00, "CADJPY": 0.60, "CADCHF": 1.15, "CHFJPY": 0.70, "NZDJPY": 0.65, "NZDCAD": 1.40, "NZDCHF": 1.70,
32
+ "XAUUSD": 1.15, "XAGUSD": 7.45,
33
+ }
34
+ PAIRS = tuple(HALF_SPREAD_BP)
35
+ METALS = ("XAU", "XAG")
36
+ RESOLUTIONS = {"1m", "5m", "15m", "30m", "1h", "4h", "1d"}
37
+ _NY = ZoneInfo("America/New_York")
38
+
39
+
40
+ def get_hist(symbol: str, resolution: str = "1m", start=None, end=None, tz: Optional[str] = None) -> pd.DataFrame:
41
+ """
42
+ Historical bars of a currency pair, gold or silver.
43
+
44
+ Parameters
45
+ ----------
46
+ symbol : str
47
+ "EURUSD", "USDJPY", "XAUUSD", ... (``PAIRS``). "EUR/USD" is accepted.
48
+ resolution : str
49
+ "1m", "5m", "15m", "30m", "1h", "4h" or "1d". Aggregated bars are built from 1-minute bars on UTC
50
+ boundaries (a "1d" bar is a UTC day, not the 17:00 New York forex day).
51
+ start, end : date, datetime or epoch ms, optional
52
+ The window, end exclusive; a value without a time zone is UTC. Default: the 30 days before now.
53
+ tz : str or None
54
+ Time zone of the Datetime column (default None = UTC).
55
+
56
+ Returns
57
+ -------
58
+ pd.DataFrame
59
+ [Datetime, Date, time, Open, High, Low, Close, volume]. Datetime is the bar's OPEN time. volume is NaN:
60
+ spot forex has no consolidated volume. Prices are bid up to HistData's last published month, mid after.
61
+ """
62
+ res = str(resolution).lower().strip()
63
+ if res not in RESOLUTIONS:
64
+ raise ValueError(f"resolution must be one of: {', '.join(sorted(RESOLUTIONS))}.")
65
+ sym = str(symbol).upper().replace("/", "").strip()
66
+ end_ms = marketdata.to_ms(end, int(time.time() * 1000))
67
+ start_ms = marketdata.to_ms(start, end_ms - 30 * 86_400_000)
68
+ return marketdata.to_candles(marketdata.bars("forex", sym, start_ms, end_ms, res), tz)
69
+
70
+
71
+ def list_symbols() -> list:
72
+ """Symbols the QuantVN API stores for forex."""
73
+ return marketdata.symbols("forex")
74
+
75
+
76
+ def swap_schedule(symbol: str, start, end, rates: dict) -> pd.DataFrame:
77
+ """Overnight swap of a forex position as the Track Record service charges it, for ``paper.simulate(...,
78
+ funding=)``: one row per rollover at 17:00 New York, Monday to Friday, with start <= time < end.
79
+
80
+ ``rates``: annual interest rate in percent per currency, e.g. ``{"EUR": 2.65, "USD": 4.0}`` (the service
81
+ uses the central banks' policy rates, held constant between changes). Gold and silver earn no rate.
82
+
83
+ Returns ``Datetime`` (UTC) and ``rate``: what a LONG position pays at that rollover, as a fraction of its
84
+ size, ``(r_quote - r_base) / 100 / 365`` per day; Wednesday's rollover counts three days. Negative = the long
85
+ receives. A short receives what a long pays.
86
+ """
87
+ sym = str(symbol).upper().replace("/", "").strip()
88
+ base, quote = sym[:3], sym[3:6]
89
+ r_base = 0.0 if base in METALS else float(rates[base])
90
+ r_quote = float(rates[quote])
91
+ a, b = marketdata.to_ms(start), marketdata.to_ms(end)
92
+ d = dt.datetime.fromtimestamp(a / 1000, _NY).date() - dt.timedelta(days=1)
93
+ last = dt.datetime.fromtimestamp(b / 1000, _NY).date()
94
+ rows = []
95
+ while d <= last:
96
+ if d.weekday() < 5:
97
+ t = dt.datetime(d.year, d.month, d.day, 17, 0, tzinfo=_NY)
98
+ ms = int(t.timestamp() * 1000)
99
+ if a <= ms < b:
100
+ days = 3 if d.weekday() == 2 else 1
101
+ rows.append((pd.Timestamp(ms, unit="ms", tz="UTC"), (r_quote - r_base) / 100 / 365 * days))
102
+ d += dt.timedelta(days=1)
103
+ return pd.DataFrame(rows, columns=["Datetime", "rate"])