OANDA 報價流使用 `Transfer-Encoding: chunked` 持續推送,`RestRequest.Execute` 會阻塞等待結束標志,無法實時處理。
uses IdHTTP, IdGlobal, IdStream;
var
HTTP: TIdHTTP;
EventStream: TIdEventStream;
JsonBuffer: TStringBuilder;
procedure TForm1.StartStream;
begin
HTTP := TIdHTTP.Create(nil);
HTTP.HandleRedirects := True;
HTTP.Request.UserAgent := 'MyApp/1.0';
EventStream := TIdEventStream.Create;
EventStream.OnWrite := StreamWriteEvent; // 關鍵:每收到一塊數據觸發
HTTP.Get('https://stream-fxtrade.oanda.com/v1/prices?accountId=12345&instruments=EUR_USD', EventStream);
end;
procedure TForm1.StreamWriteEvent(const ABuffer: TIdBytes; AOffset, ACount: Integer; var VResult: Integer);
var
Chunk: string;
Json: TJSONObject;
begin
Chunk := BytesToString(ABuffer, AOffset, ACount, IndyTextEncoding_UTF8);
JsonBuffer.Append(Chunk);
// 簡單按行分割解析(實際需按 chunked 格式解析)
while JsonBuffer.Length > 0 do begin
var LineEnd := JsonBuffer.ToString.IndexOf(#10);
if LineEnd < 0 then Break;
var Line := JsonBuffer.ToString.Substring(0, LineEnd).Trim;
JsonBuffer.Remove(0, LineEnd + 1);
if Line.IsEmpty then Continue;
try
Json := TJSONObject.ParseJSONValue(Line) as TJSONObject;
if Assigned(Json) then ProcessPriceJson(Json);
except end;
end;
VResult := ACount; // 告知 Indy 已處理字節數
end;