sgcWebSockets kitaplığı, önemli bir yeni metot grubuyla Binance entegrasyonunu genişletmeye devam ediyor; bu metotlar Spot REST API, Futures REST API ve WebSocket akışlarını kapsar. Bu makale, sizi hızlıca çalışır duruma getirmek için her yeni metodun, parametrelerinin teknik bir dökümünü ve pratik Delphi kod örneklerini sunar.
İçindekiler
- Yeni Spot REST API Metotları
- Spot Piyasa Verileri: UI KLine'lar, Kayan Pencere ve Alım Satım Günü Ticker'ları
- Spot Emir Yönetimi: OCO, OTO, OTOCO ve SOR Emirleri
- Spot Hesap: Komisyon, Dağılımlar, Hız Limitleri ve Önlenen Eşleşmeler
- Yeni Futures REST API Metotları
- Futures Piyasa Verileri: Sürekli KLine'lar, Premium Endeks ve Daha Fazlası
- Futures Emir Yönetimi: Değiştirme, Toplu ve Zorunlu Emirler
- Futures Hesap: V3 Uç Noktaları, Yapılandırma ve Ücret Yakımı
- Yeni Spot WebSocket Akışları
- Yeni Futures WebSocket Akışları
- Tam Çalışan Örnekler
1. Yeni Spot REST API Metotları
TsgcHTTP_API_Binance_Rest sınıfı; yeni piyasa verisi uç noktaları,
gelişmiş emir türleri ve hesap sorgulama metotlarıyla genişletildi. Tüm metotlara, doğrudan
REST bileşeni aracılığıyla veya TsgcWS_API_Binance bileşeninin
REST_API özelliği aracılığıyla erişilebilir.
Piyasa Verisi Uç Noktaları
| Metot | Açıklama | 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 |
Kayan pencere fiyat değişimi istatistikleri. Sabit 24 saatlik ticker'ın aksine yapılandırılabilir pencere boyutlarını (örneğin 1h, 4h, 1d) destekler. | /api/v3/ticker |
GetTradingDayTicker |
Alım satım günü boyunca (UTC 00:00'dan şu ana kadar) hesaplanan fiyat değişimi istatistikleri. Tek veya birden çok sembolü destekler. | /api/v3/ticker/tradingDay |
GetPriceTickers |
Bir sembol adları JSON dizisi kullanarak tek bir istekte birden çok sembolün fiyat ticker'larını alır. | /api/v3/ticker/price |
GetUIKLines
function GetUIKLines(const aSymbol: String;
aInterval: TsgcHTTPBinanceChartIntervals; aStartTime: Int64 = 0;
aEndTime: Int64 = 0; aLimit: Integer = 500): String;
GetKLines ile GetUIKLines arasındaki fark inceliklidir:
UI varyantı, grafik oluşturma için Binance arka ucu tarafından optimize edilmiştir ve geliştirilmiş görsel sunum için değiştirilmiş kline sınırları döndürebilir.
Yanıt biçimi aynıdır, bu da onu herhangi bir grafik kullanım senaryosu için doğrudan kullanılabilir bir alternatif yapar.
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;
Bu metot, özel pencere boyutlarına izin vererek geleneksel Get24hrTicker'ı genişletir.
aWindowSize için kabul edilen değerler şunları içerir: '1h',
'4h' ve '1d'. Atlanırsa varsayılan pencere kullanılır.
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;
Gelişmiş Emir Türleri
Binance, orijinal OCO'nun ötesine geçen birkaç yeni emir listesi türü sundu. sgcWebSockets kitaplığı artık bunların tümünü yerel olarak destekler.
NewOrderListOCO (Yeni OCO Biçimi)
Yeni OCO biçimi, eski NewOCO'nun yerini alır ve daha esnek
üst/alt fiyat yapılandırmaları sunar. OCO'nun her bacağı, kendi emir türü,
stop fiyatı, trailing delta ve time-in-force değeriyle bağımsız olarak yapılandırılabilir.
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 (Biri-Diğerini-Tetikler)
Bir OTO emir listesi, bir çalışan emir ve bir bekleyen emirden oluşur. Çalışan emir gerçekleştiğinde, bekleyen emir otomatik olarak verilir. Bu, otomatik takip emirleriyle giriş emirleri kurmak için kullanışlıdır.
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 (Biri-Bir-OCO-Tetikler)
OTO ve OCO mantığını birleştirir: bir çalışan emir, gerçekleştiğinde bir OCO çiftini (kâr al + zarar durdur) tetikler. Bu, tek bir API çağrısında tamamen otomatik, çıkış planlı giriş stratejilerine olanak tanır.
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;
Akıllı Emir Yönlendirme (SOR)
SOR emirleri, Binance'in birden çok likidite havuzu arasında yönlendirme yaparak yürütmeyi optimize etmesine olanak tanır.
İki yeni metot sağlanır: canlı yürütme için NewSOROrder ve
gerçekten vermeden doğrulama için TestSOROrder.
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
Mevcut bir emri atomik olarak iptal eder ve yeni bir emir verir. Bu; iki ayrı iptal+verme çağrısı arasında pozisyonsuz kalma riski olmadan emirleri değiştirmesi gereken stratejiler için kritik öneme sahiptir.
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;
Hesap ve Sorgu Uç Noktaları
| Metot | Açıklama |
|---|---|
GetAccountInformation(aOmitZeroBalances) |
aOmitZeroBalances parametresiyle genişletildi. True olarak ayarlandığında, bakiyesi sıfır olan varlıklar yanıttan hariç tutulur. |
GetOrderRateLimitUsage |
Yüksek frekanslı senaryolarda API limitleri içinde kalmak için gerekli olan geçerli emir sayısını ve hız limiti kullanımını döndürür. |
GetPreventedMatches |
Önlenen kendi kendine işlem eşleşmelerini sorgular. Sayfalamayla birlikte sembole, emir kimliğine veya önlenen eşleşme kimliğine göre filtrelemeyi destekler. |
GetAllocations |
Bir emrin havuzlar arasında nasıl dağıtıldığını gösteren SOR emir dağılımlarını alır. |
GetAccountCommission |
Belirli bir sembol için maker/taker komisyon oranını döndürür. |
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;
Not: NewOrder ve TestNewOrder metotları da
yeni isteğe bağlı parametrelerle genişletildi: aSelfTradePreventionMode, aStrategyId ve aStrategyType.
CancelOrder metodu artık koşullu iptal için bir aCancelRestrictions parametresi kabul ediyor.
Bu eklemeler geriye dönük uyumludur, mevcut kod değişiklik olmadan çalışmaya devam edecektir.
2. Yeni Futures REST API Metotları
TsgcHTTP_API_Binance_Futures_Rest sınıfı; piyasa verilerini, emir yönetimini, hesap yapılandırmasını ve akış yönetimini kapsayan
en büyük yeni metot grubunu aldı. Tüm metotlar,
FuturesContracts özelliği tarafından kontrol edilen hem USDT-M hem de COIN-M futures ile çalışır.
Futures Piyasa Verileri
| Metot | Açıklama |
|---|---|
GetContinuousKLines | Bir sürekli sözleşme için kline/mum verileri. Çift, sözleşme türü (örneğin 'PERPETUAL', 'CURRENT_QUARTER') ve aralık gerektirir. |
GetIndexPriceKLines | Bir alım satım çiftinin endeks fiyatına dayalı kline verileri. |
GetMarkPriceKLines | Bir sembolün işaret fiyatına dayalı kline verileri. |
GetPremiumIndexKLines | Basis hesaplaması ve fonlama oranı analizi için premium endeks kline verileri. |
GetFundingInfo | Tüm semboller için fonlama aralığı ve tavan/taban oranları dahil olmak üzere fonlama oranı bilgilerini döndürür. |
GetPriceTickerV2 | Geliştirilmiş yanıt biçimine sahip V2 fiyat ticker'ı. |
GetIndexInfo | Bir bileşik endeks sembolü için endeks fiyatını ve bileşen verilerini döndürür. |
GetAssetIndex | Çoklu varlık modu marj hesaplamaları için varlık endeks fiyatları. |
GetConstituents | Belirli bir bileşik endeks için bileşenleri ve ağırlıklarını sorgular. |
GetDeliveryPrice | Üç aylık/iki üç aylık sözleşmeler için geçmiş teslim fiyatları. |
GetBasis | Belirli bir çift ve sözleşme türü için basis verileri (futures ve spot fiyatları arasındaki fark). |
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 Emir Yönetimi
Yeni Futures emir metotları; deneme emirleri, emir değiştirme, toplu işleme ve tasfiye sorguları sağlar.
| Metot | Açıklama |
|---|---|
TestNewOrder | Bir yeni futures emrini vermeden doğrular. NewOrder imzasını yansıtır. |
ModifyOrder | Mevcut bir açık emrin fiyatını, miktarını veya fiyat eşleştirme modunu değiştirir. |
NewBatchOrders | Bir emir nesneleri JSON dizisi aracılığıyla tek bir istekte en fazla 5 emir verir. |
ModifyBatchOrders | Tek bir istekte en fazla 5 mevcut emri değiştirir. |
CancelBatchOrders | Emir kimliği listesine veya istemci emir kimliği listesine göre birden çok emri iptal eder. |
GetOrderAmendment | Bir emir için emir değişikliği (modifikasyon) geçmişini alır. |
CountdownCancelAll | Bir sembol için tüm açık emirlerin iptal edileceği bir geri sayım sayacı (milisaniye cinsinden) ayarlar. |
GetForceOrders | İsteğe bağlı filtrelemeyle zorunlu tasfiye emirlerini sorgular. |
GetADLQuantile | Pozisyonlar için ADL (Otomatik Kaldıraç Azaltma) kuantil tahminini alır. |
Futures için NewOrder imzası da yeni parametrelerle genişletildi:
aPriceMatch, aSelfTradePreventionMode,
aGoodTillDate ve 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 Hesap ve Yapılandırma
Yapılandırma ve ücret yönetimi metotlarının yanı sıra birkaç V3 hesap uç noktası eklendi.
| Metot | Açıklama |
|---|---|
GetAccountBalanceV3 | Geliştirilmiş çoklu varlık marj desteğine sahip V3 hesap bakiyesi. |
GetAccountInformationV3 | Çoklu varlık marj modu ve güncellenmiş ücret kademeleri dahil olmak üzere V3 hesap ayrıntıları. |
GetPositionInformationV3 | Ek hassasiyet alanlarına sahip V3 pozisyon verileri. |
GetCommissionRate | Belirli bir futures sembolü için geçerli maker/taker komisyon oranını döndürür. |
GetAccountConfig | Hesap düzeyinde yapılandırma: ücret kademesi, pozisyon modu, çoklu varlık marj modu. |
GetSymbolConfig | Sembol başına yapılandırma: kaldıraç, marj türü ve pozisyon modu. |
GetOrderRateLimit | Sembol başına geçerli emir hız limiti durumu. |
GetApiTradingStatus | API alım satım durumu ve alım satım kısıtlamalarını tetikleyebilecek tüm göstergeler. |
ChangeMultiAssetsMode | USDT-M futures için çoklu varlık marj modunu etkinleştirir veya devre dışı bırakır. |
GetMultiAssetsMode | Geçerli çoklu varlık marj modu ayarını sorgular. |
SetFeeBurn | BNB ücret yakımını etkinleştirir veya devre dışı bırakır (ücretleri BNB ile indirimli ödeyin). |
GetFeeBurn | Geçerli ücret yakımı ayarını sorgular. |
Listen Key Yönetimi
Artık üç özel metot, Futures kullanıcı veri akışı listen key yaşam döngüsünü doğrudan REST aracılığıyla, WebSocket bileşeninden bağımsız olarak yönetir:
| Metot | Açıklama |
|---|---|
CreateListenKey | Kullanıcı veri akışı için yeni bir listen key üretir (POST). |
KeepAliveListenKey | Bir listen key'in geçerliliğini uzatır (PUT). Her 60 dakikada bir çağrılmalıdır. |
CloseListenKey | Bir listen key'i geçersiz kılar ve kapatır (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. Yeni Spot WebSocket Akışları
TsgcWS_API_Binance sınıfı, her biri abone olma ve abonelikten çıkma metotlarına sahip
üç yeni akış türüyle genişletildi.
| Metot | Stream | Açıklama |
|---|---|---|
SubscribeAvgPrice / UnSubscribeAvgPrice |
<symbol>@avgPrice |
Bir sembol için gerçek zamanlı ortalama fiyat akışı. |
SubscribeRollingWindowTicker |
<symbol>@ticker_<window> |
Yapılandırılabilir pencere boyutuyla (1h, 4h, 1d) kayan pencere istatistikleri. |
SubscribeAllRollingWindowTickers |
!ticker_<window>@arr |
Belirli bir pencere boyutunda tüm işlem gören semboller için kayan pencere istatistikleri. |
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. Yeni Futures WebSocket Akışları
TsgcWS_API_Binance_Futures sınıfı, en büyük yeni WebSocket
akış aboneliği setini alır. Bunlar; sürekli sözleşmeleri, bileşik endeksleri, varlık endekslerini, endeks fiyatlarını ve
işaret fiyatı kline'larını kapsar.
| Metot | Stream | Açıklama |
|---|---|---|
SubscribeContinuousKLine | <pair>_<contract>@continuousKline_<interval> | Sürekli sözleşmeler için kline akışı. Çift, sözleşme türü ve aralık gerektirir. |
SubscribeCompositeIndex | <symbol>@compositeIndex | Bileşen dökümü içeren bileşik endeks fiyatı akışı. |
SubscribeContractInfo | !contractInfo | Sözleşme bilgisi akışı. Listeleme, listeden çıkarma ve kademe (bracket) değişikliklerine ilişkin güncellemeleri iletir. |
SubscribeAssetIndex / SubscribeAllAssetIndex | <symbol>@assetIndex / !assetIndex@arr | Çoklu varlık marj hesaplamaları için varlık endeks fiyatları. Sembol başına veya tüm piyasa. |
SubscribeIndexPrice | <pair>@indexPrice | Bir alım satım çifti için endeks fiyatı akışı. İsteğe bağlı güncelleme hızı parametresini destekler. |
SubscribeIndexPriceKLine | <pair>@indexPriceKline_<interval> | Yapılandırılabilir aralıklarla endeks fiyatı kline/mum akışı. |
SubscribeMarkPriceKLine | <symbol>@markPriceKline_<interval> | Tasfiye hesaplamalarında kullanılan işaret fiyatını izlemek için işaret fiyatı kline akışı. |
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. Tam Çalışan Örnekler
Örnek 1: Spot REST + WebSocket Birleşik (VCL Uygulaması)
Tipik bir kalıp, emir vermek için REST API'sini ve gerçek zamanlı piyasa verileri için WebSocket API'sini kullanmaktır.
Aşağıdaki örnek, her ikisinin de TsgcWS_API_Binance bileşeni aracılığıyla nasıl kurulacağını gösterir.
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.
Örnek 2: Futures REST + WebSocket (Konsol Uygulaması)
Konsol uygulamaları, başsız botlar ve arka plan hizmetleri için idealdir. Aşağıdaki örnek, yeni Futures metotlarının bir konsol bağlamında kullanımını gösterir.
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.
Örnek 3: OTOCO Emir Stratejisi
OTOCO emir türü, en eksiksiz otomatik alım satım yaşam döngüsünü temsil eder: tek bir çağrı bir giriş emri verir; bu emir gerçekleştiğinde hem bir kâr al hem de bir zarar durdur emrini otomatik olarak kurar.
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;
Özet
Aşağıdaki tablo, her sınıfa eklenen yeni metotların sayısını özetler:
| Bileşen | Sınıf | Yeni Metotlar |
|---|---|---|
| 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 (+ eşleşen UnSubscribe metotları) |
| Futures WebSocket | TsgcWS_API_Binance_Futures |
SubscribeContinuousKLine, SubscribeCompositeIndex, SubscribeContractInfo, SubscribeAssetIndex, SubscribeAllAssetIndex, SubscribeIndexPrice, SubscribeIndexPriceKLine, SubscribeMarkPriceKLine (+ eşleşen UnSubscribe metotları) |
ApiKey ve ApiSecret kimlik bilgileri gerektirir. Üretime geçmeden önce TestNet := True ayarlayarak
Binance TestNet'e karşı geliştirme yapmanız ve test etmeniz şiddetle tavsiye edilir. Ayrıca,
API anahtarı izinlerinin (alım satım, marj, futures) gerçekleştirmeyi planladığınız işlemlerle eşleştiğinden emin olun.
Geriye Dönük Uyumluluk: Tüm eklemeler geriye dönük uyumludur. Mevcut metot imzaları,
varsayılan parametre değerleriyle genişletildi, böylece önceden derlenmiş kod değişiklik olmadan çalışmaya devam eder. Yeni
parametreler (aSelfTradePreventionMode, aStrategyId, aPriceMatch vb.)
varsayılan olarak, API'nin standart davranışını kullanmasına neden olan boş veya sıfır değerlere ayarlanır.
Metninizi buraya girin ...
