New Binance API Methods in sgcWebSockets

The sgcWebSockets library continues to expand its Binance integration with a significant batch of new methods covering the Spot REST API, Futures REST API, and WebSocket streams. This article provides a technical breakdown of each new method, its parameters, and practical Delphi code examples to get you up and running quickly.

1. New Spot REST API Methods

The TsgcHTTP_API_Binance_Rest class has been extended with new market data endpoints, advanced order types, and account query methods. All methods are accessible either directly via the REST component or through the REST_API property of TsgcWS_API_Binance.

Market Data Endpoints

Method Description Binance Endpoint
GetUIKLines Optimized kline/candlestick data for UI presentation. Returns data in a format identical to GetKLines but tuned for chart rendering. /api/v3/uiKlines
GetRollingWindowTicker Rolling window price change statistics. Supports configurable window sizes (e.g., 1h, 4h, 1d) unlike the fixed 24hr ticker. /api/v3/ticker
GetTradingDayTicker Price change statistics computed over the trading day (UTC 00:00 to current). Supports single or multiple symbols. /api/v3/ticker/tradingDay
GetPriceTickers Retrieve price tickers for multiple symbols in a single request using a JSON array of symbol names. /api/v3/ticker/price

GetUIKLines

function GetUIKLines(const aSymbol: String;
  aInterval: TsgcHTTPBinanceChartIntervals; aStartTime: Int64 = 0;
  aEndTime: Int64 = 0; aLimit: Integer = 500): String;

The difference between GetKLines and GetUIKLines is subtle: the UI variant is optimized by the Binance backend for chart rendering and may return modified kline boundaries for improved visual presentation. The response format is identical, making it a drop-in replacement for any charting use case.

var
  vJSON: string;
begin
  // Retrieve 1-hour UI-optimized klines for BTCUSDT
  vJSON := sgcBinanceREST.GetUIKLines('BTCUSDT', bcih1h, 0, 0, 100);
  Memo1.Lines.Add(vJSON);
end;

GetRollingWindowTicker

function GetRollingWindowTicker(const aSymbol: String = '';
  const aSymbols: String = ''; const aWindowSize: String = ''): String;

This method extends the traditional Get24hrTicker by allowing custom window sizes. Accepted values for aWindowSize include '1h', '4h', and '1d'. If omitted, the default window is used.

var
  vJSON: string;
begin
  // Get 4-hour rolling window stats for ETHUSDT
  vJSON := sgcBinanceREST.GetRollingWindowTicker('ETHUSDT', '', '4h');
  Memo1.Lines.Add(vJSON);

  // Get rolling window for multiple symbols
  vJSON := sgcBinanceREST.GetRollingWindowTicker('',
    '["BTCUSDT","ETHUSDT"]', '1h');
  Memo1.Lines.Add(vJSON);
end;

GetTradingDayTicker

function GetTradingDayTicker(const aSymbol: String = '';
  const aSymbols: String = ''; const aType: String = ''): String;
var
  vJSON: string;
begin
  // Get trading day statistics for BTCUSDT (FULL response)
  vJSON := sgcBinanceREST.GetTradingDayTicker('BTCUSDT', '', 'FULL');
  Memo1.Lines.Add(vJSON);
end;

Advanced Order Types

Binance has introduced several new order list types that go beyond the original OCO. The sgcWebSockets library now supports all of them natively.

NewOrderListOCO (New OCO Format)

The new OCO format replaces the legacy NewOCO and introduces more flexible above/below price configurations. Each leg of the OCO can be independently configured with its own order type, stop price, trailing delta, and time-in-force.

function NewOrderListOCO(const aSymbol, aSide: String;
  aQuantity: Double; const aAboveType: String;
  const aBelowType: String;
  aAboveClientOrderId: String = '';
  aAboveIcebergQty: Double = 0; aAbovePrice: Double = 0;
  aAboveStopPrice: Double = 0; aAboveTrailingDelta: Int64 = 0;
  aAboveTimeInForce: String = '';
  aBelowClientOrderId: String = '';
  aBelowIcebergQty: Double = 0; aBelowPrice: Double = 0;
  aBelowStopPrice: Double = 0; aBelowTrailingDelta: Int64 = 0;
  aBelowTimeInForce: String = '';
  aListClientOrderId: String = '';
  aNewOrderRespType: String = '';
  aSelfTradePreventionMode: String = ''): String;
var
  vJSON: string;
begin
  // Place a new-format OCO: take-profit above + stop-loss below
  vJSON := sgcBinanceREST.NewOrderListOCO(
    'BTCUSDT',          // symbol
    'SELL',              // side
    0.001,              // quantity
    'LIMIT_MAKER',      // above type (take-profit)
    'STOP_LOSS_LIMIT',  // below type (stop-loss)
    '',                 // aboveClientOrderId
    0,                  // aboveIcebergQty
    72000.0,            // abovePrice (take-profit price)
    0,                  // aboveStopPrice
    0,                  // aboveTrailingDelta
    '',                 // aboveTimeInForce
    '',                 // belowClientOrderId
    0,                  // belowIcebergQty
    62000.0,            // belowPrice (limit price for stop)
    62500.0,            // belowStopPrice (trigger price)
    0,                  // belowTrailingDelta
    'GTC'               // belowTimeInForce
  );
  Memo1.Lines.Add(vJSON);
end;

NewOrderListOTO (One-Triggers-the-Other)

An OTO order list consists of a working order and a pending order. When the working order executes, the pending order is automatically placed. This is useful for setting up entry orders with automatic follow-up orders.

function NewOrderListOTO(const aSymbol: String;
  const aWorkingType, aWorkingSide: String;
  aWorkingQuantity: Double; aWorkingPrice: Double;
  const aPendingType, aPendingSide: String;
  aPendingQuantity: Double;
  { ... additional optional parameters ... }
  ): String;
var
  vJSON: string;
begin
  // Buy BTCUSDT at limit, then automatically place a stop-loss sell
  vJSON := sgcBinanceREST.NewOrderListOTO(
    'BTCUSDT',
    'LIMIT', 'BUY',       // working order: limit buy
    0.001, 65000.0,        // working quantity and price
    'STOP_LOSS_LIMIT', 'SELL',  // pending: stop-loss sell
    0.001,                 // pending quantity
    '',                    // workingClientOrderId
    'GTC',                 // workingTimeInForce
    0,                     // workingIcebergQty
    '',                    // pendingClientOrderId
    62000.0,               // pendingPrice (limit)
    62500.0                // pendingStopPrice (trigger)
  );
  Memo1.Lines.Add(vJSON);
end;

NewOrderListOTOCO (One-Triggers-an-OCO)

Combines OTO and OCO logic: a working order triggers an OCO pair (take-profit + stop-loss) when filled. This enables fully automated entry-with-exit-plan strategies in a single API call.

var
  vJSON: string;
begin
  // Entry: limit buy at 65000
  // On fill: places OCO with take-profit at 72000 and stop-loss at 62000
  vJSON := sgcBinanceREST.NewOrderListOTOCO(
    'BTCUSDT',
    'LIMIT', 'BUY',          // working order
    0.001, 65000.0,           // working qty & price
    'SELL',                   // pending side
    'LIMIT_MAKER',            // pending above type
    'STOP_LOSS_LIMIT',        // pending below type
    0.001,                   // pending quantity
    '',                      // workingClientOrderId
    'GTC',                   // workingTimeInForce
    0,                       // workingIcebergQty
    '',                      // pendingAboveClientOrderId
    72000.0,                 // pendingAbovePrice (take-profit)
    0,                       // pendingAboveStopPrice
    0,                       // pendingAboveTrailingDelta
    '',                      // pendingAboveTimeInForce
    0,                       // pendingAboveIcebergQty
    '',                      // pendingBelowClientOrderId
    62000.0,                 // pendingBelowPrice
    62500.0                  // pendingBelowStopPrice
  );
  Memo1.Lines.Add(vJSON);
end;

Smart Order Routing (SOR)

SOR orders allow Binance to optimize execution by routing across multiple liquidity pools. Two new methods are provided: NewSOROrder for live execution and TestSOROrder for validation without actual placement.

function NewSOROrder(const aSymbol, aSide, aType: String;
  aQuantity: Double; aTimeInForce: String = '';
  aPrice: Double = 0; aNewClientOrderId: String = '';
  aNewOrderRespType: String = '';
  aIcebergQty: Double = 0;
  aSelfTradePreventionMode: String = '';
  aStrategyId: Int64 = 0; aStrategyType: Integer = 0): String;
var
  vJSON: string;
begin
  // Place a SOR limit order
  vJSON := sgcBinanceREST.NewSOROrder(
    'BTCUSDT', 'BUY', 'LIMIT',
    0.001,             // quantity
    'GTC',             // timeInForce
    65000.0            // price
  );
  Memo1.Lines.Add(vJSON);

  // Test a SOR order without execution
  vJSON := sgcBinanceREST.TestSOROrder('BTCUSDT', 'BUY', 'LIMIT',
    0.001, 'GTC', 65000.0);
  Memo1.Lines.Add(vJSON);
end;

CancelReplaceOrder

Atomically cancels an existing order and places a new one. This is critical for strategies that need to modify orders without the risk of being left without a position in between two separate cancel+place calls.

var
  vJSON: string;
begin
  // Cancel order 123456 and replace it with a new limit buy
  vJSON := sgcBinanceREST.CancelReplaceOrder(
    'BTCUSDT', 'BUY', 'LIMIT',
    'STOP_ON_FAILURE',   // mode: only place new if cancel succeeds
    'GTC',               // timeInForce
    0.001,               // quantity
    0,                   // quoteOrderQty
    64500.0,             // new price
    '',                  // cancelNewClientOrderId
    '',                  // cancelOrigClientOrderId
    123456               // cancelOrderId
  );
  Memo1.Lines.Add(vJSON);
end;

Account & Query Endpoints

Method Description
GetAccountInformation(aOmitZeroBalances) Extended with aOmitZeroBalances parameter. When set to True, assets with zero balance are excluded from the response.
GetOrderRateLimitUsage Returns the current order count and rate limit usage, essential for staying within API limits in high-frequency scenarios.
GetPreventedMatches Queries prevented self-trade matches. Supports filtering by symbol, order ID, or prevented match ID with pagination.
GetAllocations Retrieves SOR order allocations, showing how an order was distributed across pools.
GetAccountCommission Returns the maker/taker commission rate for a specific symbol.
var
  vJSON: string;
begin
  // Get account info, omitting zero balances
  vJSON := sgcBinanceREST.GetAccountInformation(True);
  Memo1.Lines.Add(vJSON);

  // Check order rate limit usage
  vJSON := sgcBinanceREST.GetOrderRateLimitUsage;
  Memo1.Lines.Add(vJSON);

  // Get commission rates for BTCUSDT
  vJSON := sgcBinanceREST.GetAccountCommission('BTCUSDT');
  Memo1.Lines.Add(vJSON);

  // Get prevented matches for a symbol
  vJSON := sgcBinanceREST.GetPreventedMatches('BTCUSDT');
  Memo1.Lines.Add(vJSON);

  // Get SOR allocations for a symbol
  vJSON := sgcBinanceREST.GetAllocations('BTCUSDT');
  Memo1.Lines.Add(vJSON);
end;
Note: The NewOrder and TestNewOrder methods have also been extended with new optional parameters: aSelfTradePreventionMode, aStrategyId, and aStrategyType. The CancelOrder method now accepts a aCancelRestrictions parameter for conditional cancellation. These additions are backward-compatible — existing code will continue to work without changes.

2. New Futures REST API Methods

The TsgcHTTP_API_Binance_Futures_Rest class has received the largest batch of new methods, covering market data, order management, account configuration, and stream management. All methods work with both USDT-M and COIN-M futures, controlled by the FuturesContracts property.

Futures Market Data

Method Description
GetContinuousKLinesKline/candlestick data for a continuous contract. Requires pair, contract type (e.g., 'PERPETUAL', 'CURRENT_QUARTER'), and interval.
GetIndexPriceKLinesKline data based on the index price of a trading pair.
GetMarkPriceKLinesKline data based on the mark price of a symbol.
GetPremiumIndexKLinesPremium index kline data for basis calculation and funding rate analysis.
GetFundingInfoReturns funding rate info for all symbols including funding interval and cap/floor rates.
GetPriceTickerV2V2 price ticker with improved response format.
GetIndexInfoReturns the index price and constituent data for a composite index symbol.
GetAssetIndexAsset index prices for multi-asset mode margin calculations.
GetConstituentsQuery the constituents and their weights for a given composite index.
GetDeliveryPriceHistorical delivery prices for quarterly/bi-quarterly contracts.
GetBasisBasis data (spread between futures and spot prices) for a given pair and contract type.
var
  vJSON: string;
begin
  // Continuous klines for BTCUSDT perpetual, 1h interval
  vJSON := sgcBinanceFutREST.GetContinuousKLines(
    'BTCUSDT', 'PERPETUAL', bcih1h, 0, 0, 100);
  Memo1.Lines.Add(vJSON);

  // Mark price klines for ETHUSDT, 15m interval
  vJSON := sgcBinanceFutREST.GetMarkPriceKLines('ETHUSDT', bcih15m);
  Memo1.Lines.Add(vJSON);

  // Index price klines
  vJSON := sgcBinanceFutREST.GetIndexPriceKLines('BTCUSDT', bcih4h);
  Memo1.Lines.Add(vJSON);

  // Premium index klines for funding analysis
  vJSON := sgcBinanceFutREST.GetPremiumIndexKLines('BTCUSDT', bcih1h);
  Memo1.Lines.Add(vJSON);

  // Get funding info for all symbols
  vJSON := sgcBinanceFutREST.GetFundingInfo;
  Memo1.Lines.Add(vJSON);

  // V2 price ticker
  vJSON := sgcBinanceFutREST.GetPriceTickerV2('BTCUSDT');
  Memo1.Lines.Add(vJSON);

  // Basis data
  vJSON := sgcBinanceFutREST.GetBasis('BTCUSDT', 'PERPETUAL', oip1h, 30);
  Memo1.Lines.Add(vJSON);

  // Delivery price history
  vJSON := sgcBinanceFutREST.GetDeliveryPrice('BTCUSD');
  Memo1.Lines.Add(vJSON);
end;

Futures Order Management

The new Futures order methods provide test orders, order modification, batch processing, and liquidation queries.

Method Description
TestNewOrderValidates a new futures order without placing it. Mirrors the NewOrder signature.
ModifyOrderModifies price, quantity, or price matching mode of an existing open order.
NewBatchOrdersPlaces up to 5 orders in a single request via a JSON array of order objects.
ModifyBatchOrdersModifies up to 5 existing orders in a single request.
CancelBatchOrdersCancels multiple orders by order ID list or client order ID list.
GetOrderAmendmentRetrieves order amendment (modification) history for an order.
CountdownCancelAllSets a countdown timer (in milliseconds) after which all open orders for a symbol are cancelled.
GetForceOrdersQueries forced liquidation orders with optional filtering.
GetADLQuantileRetrieves ADL (Auto-Deleveraging) quantile estimation for positions.

The NewOrder signature for Futures has also been extended with new parameters: aPriceMatch, aSelfTradePreventionMode, aGoodTillDate, and aPriceProtect.

var
  vJSON: string;
begin
  // Test a futures order without execution
  vJSON := sgcBinanceFutREST.TestNewOrder(
    'BTCUSDT', 'BUY', '', 'LIMIT',
    'GTC', 0.001, 'false', 65000.0);
  Memo1.Lines.Add('TestNewOrder: ' + vJSON);

  // Modify an existing order's price
  vJSON := sgcBinanceFutREST.ModifyOrder('BTCUSDT', 123456, '',
    'BUY', 0.001, 64800.0);
  Memo1.Lines.Add('ModifyOrder: ' + vJSON);

  // Cancel multiple orders at once
  vJSON := sgcBinanceFutREST.CancelBatchOrders('BTCUSDT',
    '[123456,123457,123458]');
  Memo1.Lines.Add('CancelBatch: ' + vJSON);

  // Set countdown cancel: cancel all BTCUSDT orders in 30 seconds
  vJSON := sgcBinanceFutREST.CountdownCancelAll('BTCUSDT', 30000);
  Memo1.Lines.Add('Countdown: ' + vJSON);

  // Query forced liquidation orders
  vJSON := sgcBinanceFutREST.GetForceOrders('BTCUSDT');
  Memo1.Lines.Add('ForceOrders: ' + vJSON);

  // ADL quantile estimation
  vJSON := sgcBinanceFutREST.GetADLQuantile('BTCUSDT');
  Memo1.Lines.Add('ADL: ' + vJSON);
end;

Futures Account & Configuration

Several V3 account endpoints have been added alongside configuration and fee management methods.

Method Description
GetAccountBalanceV3V3 account balance with improved multi-asset margin support.
GetAccountInformationV3V3 account details including multi-asset margin mode and updated fee tiers.
GetPositionInformationV3V3 position data with additional precision fields.
GetCommissionRateReturns the current maker/taker commission rate for a specific futures symbol.
GetAccountConfigAccount-level configuration: fee tier, position mode, multi-asset margin mode.
GetSymbolConfigPer-symbol configuration: leverage, margin type, and position mode.
GetOrderRateLimitCurrent order rate limit status per symbol.
GetApiTradingStatusAPI trading status and any indicators that might trigger trading restrictions.
ChangeMultiAssetsModeEnable or disable multi-asset margin mode for USDT-M futures.
GetMultiAssetsModeQuery the current multi-asset margin mode setting.
SetFeeBurnEnable or disable BNB fee burn (pay fees with BNB at a discount).
GetFeeBurnQuery the current fee burn setting.

Listen Key Management

Three dedicated methods now handle the Futures user data stream listen key lifecycle directly via REST, independent of the WebSocket component:

Method Description
CreateListenKeyGenerates a new listen key for the user data stream (POST).
KeepAliveListenKeyExtends the validity of a listen key (PUT). Must be called every 60 minutes.
CloseListenKeyInvalidates and closes a listen key (DELETE).
var
  vJSON: string;
begin
  // V3 balance and account info
  vJSON := sgcBinanceFutREST.GetAccountBalanceV3;
  Memo1.Lines.Add('V3 Balance: ' + vJSON);

  vJSON := sgcBinanceFutREST.GetAccountInformationV3;
  Memo1.Lines.Add('V3 Account: ' + vJSON);

  vJSON := sgcBinanceFutREST.GetPositionInformationV3('BTCUSDT');
  Memo1.Lines.Add('V3 Position: ' + vJSON);

  // Commission rate
  vJSON := sgcBinanceFutREST.GetCommissionRate('BTCUSDT');
  Memo1.Lines.Add('Commission: ' + vJSON);

  // Account and symbol configuration
  vJSON := sgcBinanceFutREST.GetAccountConfig;
  Memo1.Lines.Add('AccountConfig: ' + vJSON);

  vJSON := sgcBinanceFutREST.GetSymbolConfig('BTCUSDT');
  Memo1.Lines.Add('SymbolConfig: ' + vJSON);

  // Enable multi-asset margin mode
  vJSON := sgcBinanceFutREST.ChangeMultiAssetsMode(True);
  Memo1.Lines.Add('MultiAssets: ' + vJSON);

  // Enable BNB fee burn
  vJSON := sgcBinanceFutREST.SetFeeBurn(True);
  Memo1.Lines.Add('FeeBurn: ' + vJSON);

  // Check API trading status
  vJSON := sgcBinanceFutREST.GetApiTradingStatus('BTCUSDT');
  Memo1.Lines.Add('TradingStatus: ' + vJSON);

  // Listen key lifecycle (REST-only approach)
  vJSON := sgcBinanceFutREST.CreateListenKey;
  Memo1.Lines.Add('ListenKey: ' + vJSON);
end;

3. New Spot WebSocket Streams

The TsgcWS_API_Binance class has been extended with three new stream types, each with subscribe and unsubscribe methods.

Method Stream Description
SubscribeAvgPrice / UnSubscribeAvgPrice <symbol>@avgPrice Real-time average price stream for a symbol.
SubscribeRollingWindowTicker <symbol>@ticker_<window> Rolling window statistics with configurable window size (1h, 4h, 1d).
SubscribeAllRollingWindowTickers !ticker_<window>@arr Rolling window stats for all traded symbols at a specific window size.

A new enumeration type TsgcWSBinanceRollingWindowSize is provided for type-safe window size specification:

TsgcWSBinanceRollingWindowSize = (brw1h, brw4h, brw1d);
procedure TForm1.btnSubscribeClick(Sender: TObject);
begin
  if not sgcWebSocketClient1.Active then
    sgcWebSocketClient1.Active := True;

  // Subscribe to average price updates for BTCUSDT
  sgcBinance.SubscribeAvgPrice('btcusdt');

  // Subscribe to 1-hour rolling window ticker for ETHUSDT
  sgcBinance.SubscribeRollingWindowTicker('ethusdt', brw1h);

  // Subscribe to all tickers with a 4-hour rolling window
  sgcBinance.SubscribeAllRollingWindowTickers(brw4h);
end;

procedure TForm1.btnUnsubscribeClick(Sender: TObject);
begin
  sgcBinance.UnSubscribeAvgPrice('btcusdt');
  sgcBinance.UnSubscribeRollingWindowTicker('ethusdt', brw1h);
  sgcBinance.UnSubscribeAllRollingWindowTickers(brw4h);
end;

4. New Futures WebSocket Streams

The TsgcWS_API_Binance_Futures class receives the largest set of new WebSocket stream subscriptions. These cover continuous contracts, composite indices, asset indices, index prices, and mark price klines.

Method Stream Description
SubscribeContinuousKLine<pair>_<contract>@continuousKline_<interval>Kline stream for continuous contracts. Requires pair, contract type, and interval.
SubscribeCompositeIndex<symbol>@compositeIndexComposite index price stream with component breakdown.
SubscribeContractInfo!contractInfoContract information stream. Pushes updates on listing, delisting, and bracket changes.
SubscribeAssetIndex / SubscribeAllAssetIndex<symbol>@assetIndex / !assetIndex@arrAsset index prices for multi-asset margin calculations. Per-symbol or full market.
SubscribeIndexPrice<pair>@indexPriceIndex price stream for a trading pair. Supports optional update speed parameter.
SubscribeIndexPriceKLine<pair>@indexPriceKline_<interval>Index price kline/candlestick stream with configurable intervals.
SubscribeMarkPriceKLine<symbol>@markPriceKline_<interval>Mark price kline stream for tracking the mark price used in liquidation calculations.
procedure TForm1.SubscribeFuturesStreams;
begin
  if not sgcWebSocketClient1.Active then
    sgcWebSocketClient1.Active := True;

  // Continuous kline for BTCUSDT perpetual contract, 1h interval
  sgcBinanceFutures.SubscribeContinuousKLine('btcusdt',
    'perpetual', bci1h);

  // Composite index stream
  sgcBinanceFutures.SubscribeCompositeIndex('defiusdt');

  // Contract info updates (no symbol needed)
  sgcBinanceFutures.SubscribeContractInfo;

  // Asset index for a single symbol
  sgcBinanceFutures.SubscribeAssetIndex('btcusd');

  // All asset index prices
  sgcBinanceFutures.SubscribeAllAssetIndex;

  // Index price with default update speed
  sgcBinanceFutures.SubscribeIndexPrice('btcusdt');

  // Index price kline, 15m interval
  sgcBinanceFutures.SubscribeIndexPriceKLine('btcusdt', bci15m);

  // Mark price kline, 5m interval
  sgcBinanceFutures.SubscribeMarkPriceKLine('btcusdt', bci5m);
end;

5. Full Working Examples

Example 1: Spot REST + WebSocket Combined (VCL Application)

A typical pattern is to use the REST API for placing orders and the WebSocket API for real-time market data. The following example demonstrates setting up both through the TsgcWS_API_Binance component.

unit MainForm;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
  StdCtrls, sgcWebSocket_Classes, sgcWebSocket_API_Binance,
  sgcWebSocket_APIs, sgcBase_Classes, sgcWebSocket_Client, sgcWebSocket;

type
  TForm1 = class(TForm)
    sgcWebSocketClient1: TsgcWebSocketClient;
    sgcBinance: TsgcWSAPI_Binance;
    btnConnect: TButton;
    btnGetTicker: TButton;
    btnPlaceSOROrder: TButton;
    Memo1: TMemo;
    procedure FormCreate(Sender: TObject);
    procedure btnConnectClick(Sender: TObject);
    procedure btnGetTickerClick(Sender: TObject);
    procedure btnPlaceSOROrderClick(Sender: TObject);
    procedure sgcWebSocketClient1Message(Connection: TsgcWSConnection;
      const Text: string);
  end;

implementation

{$R *.dfm}

procedure TForm1.FormCreate(Sender: TObject);
begin
  // Configure API credentials
  sgcBinance.Binance.ApiKey := 'your-api-key';
  sgcBinance.Binance.ApiSecret := 'your-api-secret';
  sgcBinance.Binance.TestNet := True;  // use testnet during development
  sgcBinance.Binance.UserStream := False;
end;

procedure TForm1.btnConnectClick(Sender: TObject);
begin
  sgcWebSocketClient1.Active := True;

  // Subscribe to new streams
  sgcBinance.SubscribeAvgPrice('btcusdt');
  sgcBinance.SubscribeRollingWindowTicker('btcusdt', brw1h);
end;

procedure TForm1.btnGetTickerClick(Sender: TObject);
begin
  // Use new REST endpoints via the integrated REST_API property
  Memo1.Lines.Add(sgcBinance.REST_API.GetTradingDayTicker('BTCUSDT'));
  Memo1.Lines.Add(sgcBinance.REST_API.GetRollingWindowTicker('BTCUSDT',
    '', '4h'));
  Memo1.Lines.Add(sgcBinance.REST_API.GetAccountCommission('BTCUSDT'));
end;

procedure TForm1.btnPlaceSOROrderClick(Sender: TObject);
begin
  // Test a Smart Order Routing order
  Memo1.Lines.Add(sgcBinance.REST_API.TestSOROrder(
    'BTCUSDT', 'BUY', 'LIMIT', 0.001, 'GTC', 65000.0));
end;

procedure TForm1.sgcWebSocketClient1Message(Connection: TsgcWSConnection;
  const Text: string);
begin
  Memo1.Lines.Add(Text);
end;

end.

Example 2: Futures REST + WebSocket (Console Application)

Console applications are ideal for headless bots and background services. The following example demonstrates using the new Futures methods in a console context.

program BinanceFuturesConsole;

{$APPTYPE CONSOLE}
{$R *.res}

uses
  Classes, SysUtils,
  sgcWebSocket, sgcWebSocket_APIs, sgcWebSocket_Types,
  sgcWebSocket_Classes, sgcHTTP_API_Binance;

var
  FutREST: TsgcHTTP_API_Binance_Futures_Rest;
  vJSON: string;

begin
  try
    FutREST := TsgcHTTP_API_Binance_Futures_Rest.Create(nil);
    try
      FutREST.BinanceOptions.ApiKey := 'your-api-key';
      FutREST.BinanceOptions.ApiSecret := 'your-api-secret';
      FutREST.BinanceOptions.TestNet := True;
      FutREST.FuturesContracts := bfchUSDT;

      // New market data methods
      vJSON := FutREST.GetFundingInfo;
      WriteLn('Funding Info: ', Copy(vJSON, 1, 200), '...');

      vJSON := FutREST.GetPriceTickerV2('BTCUSDT');
      WriteLn('PriceV2: ', vJSON);

      vJSON := FutREST.GetContinuousKLines('BTCUSDT',
        'PERPETUAL', bcih1h, 0, 0, 5);
      WriteLn('ContinuousKLines: ', Copy(vJSON, 1, 200), '...');

      // V3 account endpoints
      vJSON := FutREST.GetAccountBalanceV3;
      WriteLn('V3 Balance: ', Copy(vJSON, 1, 200), '...');

      // Account configuration
      vJSON := FutREST.GetAccountConfig;
      WriteLn('Config: ', vJSON);

      vJSON := FutREST.GetSymbolConfig('BTCUSDT');
      WriteLn('SymbolConfig: ', vJSON);

      // Commission and fee management
      vJSON := FutREST.GetCommissionRate('BTCUSDT');
      WriteLn('Commission: ', vJSON);

      vJSON := FutREST.GetFeeBurn;
      WriteLn('FeeBurn: ', vJSON);

      // Listen key management
      vJSON := FutREST.CreateListenKey;
      WriteLn('ListenKey: ', vJSON);

    finally
      FutREST.Free;
    end;

  except
    on E: Exception do
      WriteLn(E.ClassName, ': ', E.Message);
  end;
end.

Example 3: OTOCO Order Strategy

The OTOCO order type represents the most complete automated trade lifecycle: a single call places an entry order that, once filled, automatically sets up both a take-profit and a stop-loss.

procedure TForm1.PlaceOTOCOStrategy;
var
  vResult: string;
begin
  // Strategy: buy ETHUSDT at 3400, take profit at 3600, stop-loss at 3300
  vResult := sgcBinance.REST_API.NewOrderListOTOCO(
    'ETHUSDT',
    // Working order: limit buy entry
    'LIMIT',              // workingType
    'BUY',                // workingSide
    0.1,                  // workingQuantity
    3400.0,               // workingPrice
    // Pending OCO (triggered after entry fills)
    'SELL',                // pendingSide
    'LIMIT_MAKER',         // pendingAboveType (take-profit)
    'STOP_LOSS_LIMIT',     // pendingBelowType (stop-loss)
    0.1,                  // pendingQuantity
    '',                   // workingClientOrderId
    'GTC',                // workingTimeInForce
    0,                    // workingIcebergQty
    '',                   // pendingAboveClientOrderId
    3600.0,               // pendingAbovePrice (take-profit target)
    0,                    // pendingAboveStopPrice
    0,                    // pendingAboveTrailingDelta
    '',                   // pendingAboveTimeInForce
    0,                    // pendingAboveIcebergQty
    '',                   // pendingBelowClientOrderId
    3250.0,               // pendingBelowPrice (stop-loss limit)
    3300.0                // pendingBelowStopPrice (trigger)
  );

  if Pos('"orderListId"', vResult) > 0 then
    Memo1.Lines.Add('OTOCO placed successfully')
  else
    Memo1.Lines.Add('OTOCO error: ' + vResult);
end;

Summary

The following table summarizes the count of new methods added to each class:

Component Class New Methods
Spot REST API TsgcHTTP_API_Binance_Rest GetUIKLines, GetRollingWindowTicker, GetTradingDayTicker, NewOrderListOCO, NewOrderListOTO, NewOrderListOTOCO, NewSOROrder, TestSOROrder, CancelReplaceOrder, GetOrderRateLimitUsage, GetPreventedMatches, GetAllocations, GetAccountCommission
Futures REST API TsgcHTTP_API_Binance_Futures_Rest TestNewOrder, ModifyOrder, NewBatchOrders, ModifyBatchOrders, CancelBatchOrders, GetOrderAmendment, CountdownCancelAll, GetForceOrders, GetADLQuantile, GetAccountBalanceV3, GetAccountInformationV3, GetPositionInformationV3, GetCommissionRate, GetAccountConfig, GetSymbolConfig, GetOrderRateLimit, GetApiTradingStatus, ChangeMultiAssetsMode, GetMultiAssetsMode, SetFeeBurn, GetFeeBurn, GetContinuousKLines, GetIndexPriceKLines, GetMarkPriceKLines, GetPremiumIndexKLines, GetFundingInfo, GetPriceTickerV2, GetIndexInfo, GetAssetIndex, GetConstituents, GetDeliveryPrice, GetBasis, CreateListenKey, KeepAliveListenKey, CloseListenKey
Spot WebSocket TsgcWS_API_Binance SubscribeAvgPrice, SubscribeRollingWindowTicker, SubscribeAllRollingWindowTickers (+ matching UnSubscribe methods)
Futures WebSocket TsgcWS_API_Binance_Futures SubscribeContinuousKLine, SubscribeCompositeIndex, SubscribeContractInfo, SubscribeAssetIndex, SubscribeAllAssetIndex, SubscribeIndexPrice, SubscribeIndexPriceKLine, SubscribeMarkPriceKLine (+ matching UnSubscribe methods)
Important: All trading methods that place, modify, or cancel orders require valid ApiKey and ApiSecret credentials. It is strongly recommended to develop and test against the Binance TestNet by setting TestNet := True before moving to production. Also, ensure that the API key permissions (trading, margin, futures) match the operations you intend to perform.
Backward Compatibility: All additions are backward-compatible. Existing method signatures have been extended with default parameter values, so previously compiled code continues to work without modification. The new parameters (aSelfTradePreventionMode, aStrategyId, aPriceMatch, etc.) default to empty or zero values that cause the API to use its standard behavior.

Enter your text here ...

Stay Informed

When you subscribe to the blog, we will send you an e-mail when there are new updates on the site so you wouldn't miss them.

OpenAI Delphi Client Update

Related Posts