forked from svanas/delphereum
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathweb3.coincap.pas
106 lines (90 loc) · 2.82 KB
/
web3.coincap.pas
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
{******************************************************************************}
{ }
{ Delphereum }
{ }
{ Copyright(c) 2020 Stefan van As <[email protected]> }
{ Github Repository <https://github.com/svanas/delphereum> }
{ }
{ Distributed under Creative Commons NonCommercial (aka CC BY-NC) license. }
{ }
{******************************************************************************}
unit web3.coincap;
interface
uses
// Delphi
System.Types,
// web3
web3,
web3.http;
type
ITicker = interface
function Symbol: string; // most common symbol used to identify this asset on an exchange
function Price : Extended; // volume-weighted price based on real-time market data, translated to USD
end;
TAsyncTicker = reference to procedure(ticker: ITicker; err: IError);
function ticker(const asset: string; callback: TAsyncTicker): IAsyncResult; overload;
function ticker(const asset: string; callback: TAsyncJsonObject): IAsyncResult; overload;
implementation
uses
// Delphi
System.JSON,
System.NetEncoding,
// web3
web3.json;
type
TTicker = class(TInterfacedObject, ITicker)
private
FJsonObject: TJsonObject;
public
function Symbol: string;
function Price : Extended;
constructor Create(aJsonObject: TJsonObject);
destructor Destroy; override;
end;
constructor TTicker.Create(aJsonObject: TJsonObject);
begin
inherited Create;
FJsonObject := aJsonObject;
end;
destructor TTicker.Destroy;
begin
if Assigned(FJsonObject) then
FJsonObject.Free;
inherited Destroy;
end;
function TTicker.Symbol: string;
begin
Result := getPropAsStr(FJsonObject, 'symbol');
end;
function TTicker.Price: Extended;
begin
Result := getPropAsExt(FJsonObject, 'priceUsd');
end;
function ticker(const asset: string; callback: TAsyncTicker): IAsyncResult;
begin
Result := ticker(asset, procedure(obj: TJsonObject; err: IError)
var
data: TJsonObject;
begin
if Assigned(err) then
begin
callback(nil, err);
EXIT;
end;
data := getPropAsObj(obj, 'data');
if not Assigned(data) then
begin
callback(nil, TError.Create('%s.data is null', [asset]));
EXIT;
end;
callback(TTicker.Create(data.Clone as TJsonObject), nil);
end);
end;
function ticker(const asset: string; callback: TAsyncJsonObject): IAsyncResult;
begin
Result := web3.http.get(
'https://api.coincap.io/v2/assets/' + TNetEncoding.URL.Encode(asset),
callback
);
end;
end.