Jump to content
roPopa

Delphi Binance API program

Recommended Posts

Hi all
Did anyone have any piece of code working with binance API?
I found myself in need of an "hello word" example and I did not find it on the intenet.

 

Anyone can help me to understand that I am thinking correct or not please.

I have the following code
 

Code:
procedure TfrmMain.btnInfoClick(Sender: TObject);
var workStream     : TStringStream;
    workResponse   : TStringStream;
    responseObject : ISuperObject;
    serverTIME     : Int64;
begin
  mDEBUG.Lines.Clear;
  try
    workStream   := TStringStream.Create;
    workResponse := TStringStream.Create;

    restCLIENT_MAIN.ResetToDefaults;
    restREQUEST_MAIN.ResetToDefaults;
    restRESPONSE_MAIN.ResetToDefaults;
    restCLIENT_MAIN.BaseURL := API_URL;
    serverTIME              := GetAPI_TIME;
    restREQUEST_MAIN.Resource       := '/sapi/v1/broker/info';
    restREQUEST_MAIN.ResourceSuffix := '?timestamp=' + serverTIME.ToString + '&signature=' + SECRET_KEY;
    restREQUEST_MAIN.Method         := TRESTRequestMethod.rmGET;
    restREQUEST_MAIN.AddParameter('Content-Type', 'application/json');
    restREQUEST_MAIN.AddParameter('X-MBX-APIKEY', CLIENT_KEY);
    restREQUEST_MAIN.Execute;
    workResponse   := TStringStream.Create(restRESPONSE_MAIN.JSONText);
    responseObject := TSuperObject.ParseStream(workResponse, True);
    if responseObject <> nil then begin
      mDEBUG.Lines.Add(responseObject.AsString);
    end else begin
      mDEBUG.Lines.Add(restRESPONSE_MAIN.Content);
    end;
  finally
    mDEBUG.Lines.Add('');
    mDEBUG.Lines.Add('restCLIENT_MAIN.BaseURL:' + restCLIENT_MAIN.BaseURL);
    mDEBUG.Lines.Add('restREQUEST_MAIN.Resource:' + restREQUEST_MAIN.Resource);
    mDEBUG.Lines.Add('restREQUEST_MAIN.ResourceSuffix:' + restREQUEST_MAIN.ResourceSuffix);
    FreeAndNil(workStream);
    FreeAndNil(workResponse);
  end;
end;


the result is

Code:
{"msg":"API-key format invalid.","code":-2014}


 

but the postman give me a different error. (timestamp difference)
What I am missing?

Anyone can help me with some hints?

postman1.png

postman2.png

Edited by roPopa

Share this post


Link to post
[code]
SIGNED (TRADE and USER_DATA) Endpoint security
SIGNED endpoints require an additional parameter, signature, to be sent in the query string or request body.
Endpoints use HMAC SHA256 signatures. The HMAC SHA256 signature is a keyed HMAC SHA256 operation. Use your secretKey as the key and totalParams as the value for the HMAC operation.
The signature is not case sensitive.
totalParams is defined as the query string concatenated with the request body.
[/code]

see the:  Use your secretKey as the key and totalParams as the value for the HMAC operation.

 

Be very carefull with your secret key !

 

 

Also make sure, you have your computer/server synchronized with a timeserver. 

(and if i got it correct, you have to need the timestamp in UTC time, not local time).

 

 

 

 

this had to be one post, sorry

Edited by mvanrijnen

Share this post


Link to post

I wrote a program in Delphi 10 which uses REST components to connect to Binance.

In Delphi 10 you can use REST debugger to test the connection and get all the data and components which you can copy to the Form.

 

In REST debugger:

Request menu:

Method: GET

URL: https://api.binance.com/api/v3/exchangeInfo

 

(if you generated API KEY you can use that:

Parameters menu:

HEADER: X-CMC_PRO_API_KEY=   your_api_key

HEADER: Accept=application/json

)

 

Click on Send Request and you'll get the data.

On Tabulator Data menu you modify this:

JSON Root Element: symbols

click on "Nested"

click on Apply

 

You get the all the data from Cryptos you want.

 

Click on "Copy Components" then create a the Form and paste the components to the Form. 

Create a stringgrid to the form.

 

Click on RESTRequest1 and choose Execute.

 

Click right mouse button on the form1 and choose Bind Visually.

Link the MemTable to the StringGrid. 

 

And you are done!

You will see the data from Binance!

 

Share this post


Link to post
Posted (edited)

I use Delphi websocket to get data from Binance.

uses IdIOHandler, IdIOHandlerSocket, IdIOHandlerStack, IdSSL, IdSSLOpenSSL, IdWebSocketSimpleClient;

type

...

procedure lSWC1DataEvent(Sender: TObject; const Text: string);

private

...

public

...

 

 

procedure TForm1.lSWC1DataEvent(Sender: TObject; const Text: string);
begin
 Form1.smemo1.Lines.Add(text);
end;

 

#use these parameters to avoid SSL3_READ_BYTES:sslv3 alert handshake failure

procedure TForm1.Button1Click(Sender: TObject);
var lSWC:TIdSimpleWebSocketClient;
begin
  lSWC := TIdSimpleWebSocketClient.Create(self);
  lSWC.onDataEvent := lSWC1DataEvent;             //:= self.lSWC1DataEvent; //TSWSCDataEvent
  lSWC.AutoCreateHandler := false; 
  if not lSWC.AutoCreateHandler then
  begin
    if lSWC.IOHandler=nil then
      lSWC.IOHandler := TIdSSLIOHandlerSocketOpenSSL.Create(lSWC);
    (lSWC.IOHandler as TIdSSLIOHandlerSocketOpenSSL).SSLOptions.Mode := TIdSSLMode.sslmClient;

    (lSWC.IOHandler as TIdSSLIOHandlerSocketOpenSSL).SSLOptions.Method := sslvSSLv23;
    (lSWC.IOHandler as TIdSSLIOHandlerSocketOpenSSL).SSLOptions.SSLVersions := [TIdSSLVersion.sslvSSLv23];
  end;

  lSWC.Connect('wss://stream.binance.com:9443/ws/btcusdt@kline_15m');
  (lSWC.IOHandler as TIdSSLIOHandlerSocketOpenSSL).PassThrough:=false; 
end;

 

 

added this .pas to my Project:

https://github.com/arvanus/Indy/blob/WebSocketImpl/Lib/Core/IdWebSocketSimpleClient.pas

 

 

Edited by DavidOp
  • Like 1

Share this post


Link to post
Posted (edited)

Tested and find the final solution:

(lSWC.IOHandler as TIdSSLIOHandlerSocketOpenSSL).PassThrough:=false;

lSWC.Connect('wss://stream.binance.com:9443/ws');
lSWC.writeText('{"method": "SUBSCRIBE","params": ["btcusdt@kline_15m"],"id": 1}');

lSWC.writeText('{"method": "SUBSCRIBE","params": ["ethusdt@kline_15m"],"id": 1}');

....

 

One connection is allowed so you can not run two "connection" command. You have to connect to Binance first and use JSON format to SUBSCRIBE to the crypto/history/candlestick/kindle.

Of course you can use the command (and use this format):

 lSWC.Connect('wss://stream.binance.com:9443/ws/btcusdt@kline_15m/ethusdt@kline_15m/.../...'); but it can not be long (maybe 1500 is the max char sum) or it won't work. 

The PassThrough section needs to be used before connection command.

 

PS:

HEADER: X-CMC_PRO_API_KEY=   your_api_key    -> wrong 

HEADER: X-MBX-APIKEY = ....             -> right one

Edited by DavidOp

Share this post


Link to post

Sometimes needs to be waiting few more seceonds:

lSWC.Connect('wss://stream.binance.com:9443/ws');

sleep(3000);
lSWC.writeText('{"method": "SUBSCRIBE","params": ["btcusdt@kline_15m"],"id": 1}');

Share this post


Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×