developers:chart

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Next revision
Previous revision
developers:chart [2025/03/14 02:48] – created chaddevelopers:chart [2026/06/24 14:59] (current) juan
Line 5: Line 5:
 <bootnote> <bootnote>
 All times are in CST. All times are in CST.
 +</bootnote>
 +
 +The complete API documentation is available via Swagger UI at:
 +
 +[[https://api-sim.t4login.com/chart/swagger/index.html|T4 Chart API Documentation]]
 +
 +The Swagger documentation provides:
 +  * Complete list of available endpoints
 +  * Request parameters and response formats
 +  * Interactive testing capability
 +  * Authentication requirements
 +
 +<bootnote info>
 +**What changed in this revision** \\
 +This page documents the **open-source decoder libraries** that consume the chart API's compact binary response:
 +  * A top-level section **[[#Decoder Libraries]]** documenting the JavaScript (``@t4/chart-decoder``), Python (``t4login``) and .NET (``T4APIDemo``) reference decoders, including the streaming handler interface, the ``ChartDataState`` field reference, and the ``ChartDataChange`` / ``MarketMode`` / ``BidOffer`` enumerations.
 +
 +See **[[#Revision Notes / Changelog]]** at the bottom for the detailed list.
 </bootnote> </bootnote>
  
Line 21: Line 39:
 ^ Header           ^ Value                                                   ^ Description                                                                             ^ ^ Header           ^ Value                                                   ^ Description                                                                             ^
 | Authorization    | Bearer <token>                                          | **Required**. A valid bearer token to authenticate the request.                         | | Authorization    | Bearer <token>                                          | **Required**. A valid bearer token to authenticate the request.                         |
-| Accept           | application/octet-stream, application/t4                | **Optional**. Specifies the content type that the client can handle. Use this header to request a compact binary format response. If omitted, the default response format is JSON. | 
  
 **Examples:** **Examples:**
Line 27: Line 44:
   * To authorize the request, include the bearer token:   * To authorize the request, include the bearer token:
     <code>Authorization: Bearer YOUR_ACCESS_TOKEN</code>     <code>Authorization: Bearer YOUR_ACCESS_TOKEN</code>
- 
-  * To receive the response in a compact binary format, set the `Accept` header accordingly: 
-    <code>Accept: application/octet-stream</code> 
-    or 
-    <code>Accept: application/t4</code> 
- 
-Setting the `Accept` header is optional, and if it is not included, the API will return the response in a JSON format. 
  
 ==== Parameters ==== ==== Parameters ====
Line 171: Line 181:
 } }
 </code> </code>
- 
- 
- 
- 
  
 ===== Non-Aggregated Chart Data (Trade History) ===== ===== Non-Aggregated Chart Data (Trade History) =====
Line 187: Line 193:
 ^ Header        ^ Value                                                      ^ Description                                                                             ^ ^ Header        ^ Value                                                      ^ Description                                                                             ^
 | Authorization | Bearer <token>                                             | **Required**. A valid bearer token to authenticate the request.                         | | Authorization | Bearer <token>                                             | **Required**. A valid bearer token to authenticate the request.                         |
-| Accept        | application/octet-stream, application/t4                   | **Optional**. Specifies the content type that the client can handle. Use this header to request a compact binary format response. If omitted, the default response format is JSON. | 
  
 ==== Parameters ==== ==== Parameters ====
Line 233: Line 238:
 | time       | The specific time when the VWAP is calculated.                     | | time       | The specific time when the VWAP is calculated.                     |
 | vwapPrice  | The volume-weighted average price for the trades up to the specified time. | | vwapPrice  | The volume-weighted average price for the trades up to the specified time. |
- 
  
 ==== Example JSON Response ==== ==== Example JSON Response ====
Line 270: Line 274:
 } }
 </code> </code>
 +
 +The response is structured as a JSON object with various elements containing detailed trade data and related information for the specified contract and exchange within the requested time frame.
 +
 +===== Decoder Libraries =====
 +
 +Open-source reference decoders are maintained alongside this API so you do not have to implement the binary format by hand. The libraries are line-for-line ports of the original Java ``com.t4login`` chart-data reader and are validated against each other and against the CSV/JSON output.
 +
 +All of the tools below live in the public **CTS-Futures/t4-api-tools** repository:
 +
 +[[https://github.com/CTS-Futures/t4-api-tools/tree/main/tools|https://github.com/CTS-Futures/t4-api-tools/tree/main/tools]]
 +
 +^ Language    ^ Package / module                ^ Location in the repo                                  ^
 +| JavaScript  | ``@t4/chart-decoder`` (ES modules) | ``tools/JavaScript/t4-javascript-api/`` (and a browser copy under ``tools/JavaScript/JSDemo/decoder/``) |
 +| Python      | ``t4login``                     | ``tools/Python/t4-pythonConversion-api/src/t4login/``         |
 +| .NET (C#)   | ``T4APIDemo`` (NuGet)           | ``tools/dotNet/T4APIDemo/``                                    |
 +
 +==== JavaScript: @t4/chart-decoder ====
 +
 +Requires **Node 18+** (uses global ``fetch``) or any modern browser. The only runtime dependency is **decimal.js**.
 +
 +=== Install ===
 +Clone the [[https://github.com/CTS-Futures/t4-api-tools/tree/main/tools|t4-api-tools]] repository, then install dependencies:
 +
 +<code powershell>
 +git clone https://github.com/CTS-Futures/t4-api-tools.git
 +cd t4-api-tools/tools/JavaScript/t4-javascript-api
 +npm install
 +</code>
 +
 +=== Aggregated barchart (push / handler model) ===
 +
 +``ChartDataStreamReaderAggr`` decodes the whole stream and dispatches each record to a handler. Any subset of callbacks may be supplied; missing callbacks are skipped.
 +
 +<code javascript>
 +import { ChartClient } from '@t4/chart-decoder';
 +
 +const client = new ChartClient({ token: 'YOUR_ACCESS_TOKEN' });
 +
 +await client.getBarchartBinary({
 +  exchangeId: 'CME_Eq',
 +  contractId: 'ESM6',
 +  barInterval: 'Minute',
 +  barPeriod:   1,
 +  tradeDateStart: '2026-05-01',
 +  tradeDateEnd:   '2026-05-02',
 +  handler: {
 +    onMarketDefinition(def) { /* def.MarketID, def.TickValue, ... */ },
 +    onBar(bar)              { console.log(bar.Time.toString(), bar.ClosePrice.toString()); },
 +    onModeChange(marketId, tradeDate, time, mode) { /* ... */ },
 +    onSettlement(marketId, tradeDate, time, price, held) { /* ... */ },
 +    onOpenInterest(marketId, tradeDate, time, oi) { /* ... */ },
 +  },
 +});
 +</code>
 +
 +The handler interface:
 +
 +^ Callback                                                            ^ Emitted for tag(s)                ^
 +| ``onMarketDefinition(marketDefinition)``                            | ``CTAG_MARKET_DEFINITION``        |
 +| ``onBar(bar)``                                                      | ``CTAG_BAR``, ``CTAG_BAR_DELTA``  |
 +| ``onModeChange(marketId, tradeDate, time, mode)``                   | ``CTAG_MARKET_MODE``              |
 +| ``onSettlement(marketId, tradeDate, time, settlementPrice, held)``  | ``CTAG_SETTLEMENT_PRICE``         |
 +| ``onOpenInterest(marketId, tradeDate, time, openInterest)``         | ``CTAG_OPEN_INTEREST``            |
 +
 +=== Non-aggregated trade history (pull / state model) ===
 +
 +``ChartDataStreamReader`` is a sequential cursor. Each ``read()`` consumes one record and mutates the public ``reader.state`` object; ``read()`` returns ``false`` at end-of-stream. Branch on ``state.Change``:
 +
 +<code javascript>
 +import { ChartClient, ChartDataChange } from '@t4/chart-decoder';
 +
 +const reader = await client.getTradehistoryBinary({
 +  exchangeId: 'CME_E',
 +  contractId: 'YM',
 +  tradeDateStart: '2024-01-08',
 +  tradeDateEnd:   '2024-01-08',
 +});
 +
 +while (reader.read()) {
 +  const s = reader.state;
 +  switch (s.Change) {
 +    case ChartDataChange.Trade:
 +      console.log(s.LastTimeTicks, s.LastTradePrice.toString(), s.TradeVolume, s.AtBidOrOffer);
 +      break;
 +    case ChartDataChange.Quote:
 +      console.log('BBO', s.BidPrice.toString(), s.OfferPrice.toString());
 +      break;
 +    case ChartDataChange.Settlement:
 +      console.log('settle', s.SettlementPrice?.toString());
 +      break;
 +    // ... MarketMode, OpenInterest, VWAP, TPO, TradeBar, TickChange, RFQ ...
 +  }
 +}
 +</code>
 +
 +=== Lower-level / advanced usage ===
 +
 +You can also decode bytes you already have (e.g. from a saved file) without the HTTP client:
 +
 +<code javascript>
 +import {
 +  ByteReader, NDateTime, ChartDataType,
 +  ChartDataStreamReader, ChartDataStreamReaderAggr,
 +  extractT4BinPayload,
 +} from '@t4/chart-decoder';
 +
 +// Aggregated:
 +ChartDataStreamReaderAggr.read(extractT4BinPayload(bytes), handler);
 +
 +// Non-aggregated:
 +const reader = new ChartDataStreamReader({
 +  data: new ByteReader(extractT4BinPayload(bytes)),
 +  tradeDate: new NDateTime(0n),
 +  marketId: 'XCME_E YM (H24)',
 +  dataType: ChartDataType.get(0), // Tick
 +});
 +</code>
 +
 +=== Browser (no bundler) ===
 +
 +The JSDemo copy ships a ``decoder/loader.js`` ES-module entry point that publishes the decoder on ``window.T4ChartDecoder`` and fires a ``t4-decoder-ready`` event, so classic ``<script>`` code can use it without an ``import`` statement:
 +
 +<code html>
 +<script type="module" src="decoder/loader.js"></script>
 +<script>
 +  window.addEventListener('t4-decoder-ready', (e) => {
 +    const { ChartDataStreamReaderAggr, extractT4BinPayload } = e.detail;
 +    // ...
 +  });
 +</script>
 +</code>
 +
 +==== Python: t4login ====
 +
 +The Python package mirrors the JavaScript API one-to-one (same class names, same field names). It is the original conversion the JavaScript port was derived from.
 +
 +=== Install ===
 +Clone the [[https://github.com/CTS-Futures/t4-api-tools/tree/main/tools|t4-api-tools]] repository, then install dependencies:
 +
 +<code powershell>
 +git clone https://github.com/CTS-Futures/t4-api-tools.git
 +cd t4-api-tools/tools/Python/t4-pythonConversion-api
 +pip install -e .                  # installs from pyproject.toml
 +</code>
 +
 +=== Usage ===
 +
 +<code python>
 +from t4login.client.chart_client import ChartClient
 +from t4login.definitions.chartdata.chart_data_change import ChartDataChange
 +
 +client = ChartClient(token="YOUR_ACCESS_TOKEN")
 +
 +# Aggregated (handler model)
 +client.get_barchart_binary(
 +    exchange_id="CME_Eq", contract_id="ESM6",
 +    trade_date_start="2026-05-01", trade_date_end="2026-05-02",
 +    handler=my_handler,
 +)
 +
 +# Non-aggregated (state model)
 +reader = client.get_tradehistory_binary(
 +    exchange_id="CME_E", contract_id="YM",
 +    trade_date_start="2024-01-08", trade_date_end="2024-01-08",
 +)
 +while reader.read():
 +    s = reader.state
 +    if s.Change == ChartDataChange.Trade:
 +        print(s.LastTradePrice, s.TradeVolume)
 +</code>
 +
 +==== .NET: T4APIDemo ====
 +
 +The .NET reference decoder ships as the ``T4APIDemo`` NuGet package in the same repository, under ``tools/dotNet/T4APIDemo/``. It mirrors the JavaScript and Python decoders (same class, handler and ``ChartDataState`` field names) for 1:1 parity across all implementations.
 +
 +=== Install ===
 +Clone the [[https://github.com/CTS-Futures/t4-api-tools/tree/main/tools|t4-api-tools]] repository, then restore and build the project:
 +
 +<code powershell>
 +git clone https://github.com/CTS-Futures/t4-api-tools.git
 +cd t4-api-tools/tools/dotNet/T4APIDemo
 +dotnet restore
 +dotnet build
 +</code>
 +
 +==== ChartDataState field reference (T4Bin) ====
 +
 +Populated by ``ChartDataStreamReader``. Field names are PascalCase for parity across Java/Python/JS. Prices are ``Price`` objects (call ``.toString()`` / Python ``str()``); 64-bit tick times are ``BigInt`` in JS.
 +
 +^ Group        ^ Fields                                                                                                   ^
 +| Change       | ``Change`` (a **[[#ChartDataChange]]** value)                                                             |
 +| Trade date   | ``TradeDate``, ``TradeDateTicks``                                                                         |
 +| Market def.  | ``MarketDefined``, ``MarketID``, ``Numerator``, ``Denominator``, ``PriceCode``, ``TickValue``, ``VPT``, ``MinCabPrice``, ``MinPriceIncrement``, ``PointValue`` |
 +| Last trade   | ``LastTradePrice``, ``TradeVolume``, ``LastTTV``, ``LastTimeTicks``, ``AtBidOrOffer`` (**[[#BidOffer]]**), ``DueToSpread``, ``OrderVolumes`` |
 +| Bar          | ``BarStartTime``, ``BarCloseTime``, ``BarOpenPrice``, ``BarHighPrice``, ``BarLowPrice``, ``BarClosePrice``, ``BarVolume``, ``BarBidVolume``, ``BarOfferVolume``, ``BarTrades``, ``BarTradesAtBid``, ``BarTradesAtOffer`` |
 +| TPO          | ``TPOStartTime``, ``TPOBasePrice``, ``TPOPrice``, ``TPOVolume``, ``TPOVolumeAtBid``, ``TPOVolumeAtOffer``, ``TPOIsOpening``, ``TPOIsClosing`` |
 +| Quote        | ``BidPrice``, ``BidRealVolume``, ``BidImpliedVolume``, ``OfferPrice``, ``OfferRealVolume``, ``OfferImpliedVolume`` |
 +| Session      | ``Mode`` (**[[#MarketMode]]**), ``SettlementPrice``, ``SettlementHeldPrice``, ``ClearedVolume``, ``OpenInterest``, ``VWAP_Price`` |
 +| RFQ          | ``RFQBuySell`` (**[[#BidOffer]]**), ``RFQVolume``                                                         |
 +
 +==== Enumerations ====
 +
 +=== ChartDataChange ===
 +The ``state.Change`` discriminator after each ``read()``.
 +
 +^ Value ^ Name               ^ Value ^ Name              ^
 +| 0     | ``NONE``           | 8     | ``TickChange``    |
 +| 1     | ``Trade``        |   | 9     | ``RFQ``           |
 +| 2     | ``Quote``        |   | 10    | ``HeldSettlement``|
 +| 3     | ``MarketMode``     | 11    | ``ClearedVolume`` |
 +| 4     | ``Settlement``     | 12    | ``OpenInterest``  |
 +| 5     | ``TradeBar``       | 13    | ``VWAP``          |
 +| 6     | ``TradeDate``    |   | 14    | ``MarketSwitch``  |
 +| 7     | ``TPO``          |   | 15    | ``MarketDefinition`` |
 +
 +=== MarketMode ===
 +Exchange session lifecycle state (the ``marketMode`` field in JSON, and ``state.Mode`` / ``onModeChange`` in binary).
 +
 +^ Value ^ Name               ^ Value ^ Name             ^
 +| 0     | ``Undefined``    |   | 8     | ``Failed``       |
 +| 1     | ``PreOpen``      |   | 9     | ``PreCross``     |
 +| 2     | ``Open``           | 10    | ``Cross``        |
 +| 3     | ``RestrictedOpen`` |  | 11    | ``Expired``      |
 +| 4     | ``PreClosed``    |   | 12    | ``Rejected``     |
 +| 5     | ``Closed``         | 13    | ``Unavailable``  |
 +| 6     | ``Suspended``    |   | 14    | ``NoPermission`` |
 +| 7     | ``Halted``         | 15    | ``TrialExpired`` |
 +
 +=== BidOffer ===
 +Which side of the market a trade/RFQ executed against (mirrors the JSON ``aggressorSide``).
 +
 +^ Value ^ Name          ^
 +| 1     | ``Bid``       |
 +| 0     | ``Undefined`` |
 +| -1    | ``Offer``     |
 +
 +===== Revision Notes / Changelog =====
 +
 +^ Area ^ Change ^
 +| New section | **Decoder Libraries** — JavaScript (``@t4/chart-decoder``), Python (``t4login``) and .NET (``T4APIDemo``) usage, the aggregated handler interface, the non-aggregated state-cursor model, browser loader, the ``ChartDataState`` field reference, and the ``ChartDataChange`` / ``MarketMode`` / ``BidOffer`` enumerations. |
 +
 +**Source of truth:** the field and enumeration tables above are generated from the decoder source under
 +``tools/JavaScript/t4-javascript-api/src`` (mirror under ``tools/JavaScript/JSDemo/decoder``),
 +``tools/Python/t4-pythonConversion-api/src/t4login`` and ``tools/dotNet/T4APIDemo``.
 +
  
 The response is structured as a JSON object with various elements containing detailed trade data and related information for the specified contract and exchange within the requested time frame. The response is structured as a JSON object with various elements containing detailed trade data and related information for the specified contract and exchange within the requested time frame.
  
  • developers/chart.1741920528.txt.gz
  • Last modified: 2025/03/14 02:48
  • by chad