-
Notifications
You must be signed in to change notification settings - Fork 2
/
open-defi-api.yaml
3487 lines (2970 loc) · 106 KB
/
open-defi-api.yaml
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
openapi: 3.0.2
info:
version: '0.1'
title: Open DeFi API
contact:
email: [email protected]
url: 'https://tradingstrategy.ai/community'
x-logo:
url: 'https://raw.githubusercontent.com/tradingstrategy-ai/frontend/ec73a013cae04fa3f13c579dcc0dd0d80cbc49cc/src/lib/assets/logo-horizontal.svg'
description: |
Open DeFi API gives you access to decentralised exchange trading data, liquidity and tokens across multiple blockchains.
For more information see [Trading Strategy](https://tradingstrategy.ai/) website.
**This API is still in beta and subject to change**.
## Introduction
This API offres to access to so-called on-chain trading activity. You can fetch live and historical
trading data across different decentralised exchanges (DEXes)
## Use cases
This data is useful e.g. for
* Trading algorithms and bots
* Market data websites
* On-chain oracle data feeds
* Blockchain research
* Risk analysis
## Data availability
Visit [Trading Strategy website](https://tradingstrategy.ai/trading-view) to explore available data.
You can find supported blockchains and exchanges. Price candle chart is available for all trading pairs.
Ultimately all blockchains will be supported, depending on the implementation order.
## Live and historical market data
This API provides live data. However, these API endpoints have not been designed for large data ignestion.
For backtesting trading strategies, [download the historical datasets from Trading Strategy website](https://tradingstrategy.ai/trading-view/backtesting).
## Market data categories
You can find
* Decentralised exchanges
* Trading pairs
* OHLCV price data for candle charts
* OHLC liquidty data for liquidity maps
## Supported blockchains
Examples of supported blockchains:
* Ethereum mainnet
* Binance Smart Chain
* Polygon
## Supported exchanges
Examples of supported exchanges:
* [PancakeSwap](https://tradingstrategy.ai/trading-view/binance/pancakeswap-v2)
* [Uniswap](https://tradingstrategy.ai/trading-view/ethereum/uniswap-v2)
* SushiSwap
* QuickSwap
* Trader Joe
## About OpenAPI specification used
This API specification is written in [OpenAPI v3](https://swagger.io/specification/).
## Documentation, support and questions
* [Trading Strategy documentation](https://tradingstrategy.ai/docs/)
* [Ask questions on Trading Strategy Discord server](https://tradingstrategy.ai/community)
externalDocs:
description: Trading Strategy documentation
url: 'https://tradingstrategy.ai/docs/'
# A list of tags used by the definition with additional metadata.
# The order of the tags can be used to reflect on their order by the parsing tools.
tags:
- name: Blockchain
description: Data about supported blockchains
- name: Exchange
description: Data about decentralised exchanges
- name: Token
description: Data about tokens living on blockchains
- name: Trading pair
description: Data about trading pair
- name: Lending protocol
description: Data about decentralized lending protocols
- name: Trading signal
description: Data about trading signals
# Telemetry tag commented out, because its only ednpoitn /activity is commented out.
# We do not publicly advertise that endpoint, and we do not want an empty tag group.
#
# - name: Telemetry
# description: |
# Storing events of interest pertaining to the TradingStrategy ecosystem,
# such as user iteractions with the charts on the website.
servers:
- url: 'https://tradingstrategy.ai/api/'
- url: 'http://localhost:3456/api/'
# Holds the relative paths to the individual endpoints. The path is appended to the
# basePath in order to construct the full URL.
paths:
'/chains':
x-pyramid-route-name: web_chains
get:
operationId: web_chains
summary: Return information on supported blockchains
tags:
- Blockchain
responses: # list of responses
"200":
description: OK
content:
application/json:
schema:
description: List of chain summmaries
type: array
items:
$ref: '#/components/schemas/ChainSummary'
'404':
description: chain not found
"422":
description: Unexpected error - usually bad query input
content:
application/json:
schema:
$ref: "#/components/schemas/GenericErrorModel"
'/chain-details':
x-pyramid-route-name: web_chain_details
get:
operationId: web_chain_details
summary: Return information on a blockchain status
tags:
- Blockchain
parameters:
- name: chain_id
in: query
description: |
Blockchain ID, e.g, `1` for Ethereum mainnet
required: true
schema:
type: integer
example: 1
- name: chain_slug
in: query
description: |
Blockchain slug, e.g, `ethereum` for Ethereum mainnet
Note: if both `chain_id` and `chain_slug` are given, only `chain_id` will be used
required: false
schema:
type: string
example: ethereum
responses: # list of responses
"200":
description: OK
content:
application/json:
schema:
$ref: "#/components/schemas/ChainDetails"
'404':
description: chain not found
"422":
description: Unexpected error - usually bad query input
content:
application/json:
schema:
$ref: "#/components/schemas/GenericErrorModel"
'/health-check':
x-pyramid-route-name: web_chain_health_check
get:
operationId: web_chain_health_check
summary: |
The blockchain data health check.
Returns various diagnostics informtion on the chain indexing status.
This is a slow endpoint and may take minutes to respond.
It is only intended to be used in monitoring.
tags:
- Blockchain
parameters:
- name: chain_slug
in: query
description: |
Blockchain slug, e.g, `ethereum` for Ethereum mainnet
required: true
schema:
type: string
example: ethereum
responses:
"200":
description: OK
content:
application/json:
schema:
type: object
'404':
description: chain not found
"422":
description: Unexpected error - usually bad query input
content:
application/json:
schema:
$ref: "#/components/schemas/GenericErrorModel"
'/exchanges':
x-pyramid-route-name: web_exchanges
get:
operationId: web_exchanges
summary: |
List of available decentralised exchanges
TODO: Currently pagination is not supported, but the result set should be fairly small (<2000)
tags:
- Exchange
parameters:
- name: chain_slug
in: query
description: |
Blockchain slug, e.g, `ethereum` for Ethereum mainnet.
If present, list exchanges only for this chain.
required: false
schema:
type: string
- name: address
in: query
description: |
Get all DEX venues of a token by token contract address.
required: false
schema:
type: string
- name: sort
in: query
description: |
What kind of sort options is available for the output.
The default `usd_volume_30d` sorts the exchanges based on their monthly volume.
required: false
schema:
type: string
default: usd_volume_30d
enum: [usd_volume_30d, pair_count]
- name: direction
in: query
description: |
Sort order:
* `asc` - Ascending, from A to Z
* `desc` - Descending, from Z to A
required: false
schema:
type: string
enum: [asc, desc]
default: desc
- name: filter_zero_volume
in: query
description: |
When set, do not return exchanegs which have had no volume for last 30 days.
This will speed up the response a bit, as most exchanges are ghost exchanges.
required: false
schema:
type: boolean
default: false
responses: # list of responses
"200":
description: OK
content:
application/json:
schema:
$ref: "#/components/schemas/ExchangeSummaryListing"
'/exchange-details':
x-pyramid-route-name: web_exchange_details
get:
operationId: web_exchange_details
summary: Get data for one exchange to render the exchange page
parameters:
- name: exchange_slug
in: query
description: |
Exchange path slug e.g, `sushiswap`
required: true
schema:
type: string
- name: chain_slug
in: query
description: Blockchain slug, e.g, "ethereum"
required: true
schema:
type: string
tags:
- Exchange
responses: # list of responses
'200':
description: OK
content:
application/json: # operation response mime type
schema: # response schema can be specified for each response
$ref: '#/components/schemas/ExchangeDetails'
'404':
description: Exchange not found - either chain or exchange slug does not match
"422":
description: Unexpected error - usually bad query input
content:
application/json:
schema:
$ref: "#/components/schemas/GenericErrorModel"
'/pair-details':
x-pyramid-route-name: web_pair_details
get:
operationId: web_pair_details
summary: |
Additional information for a trading pair
parameters:
- name: exchange_slug
in: query
description: |
Exchange path slug e.g, `sushiswap`
required: true
schema:
type: string
example: sushiswap
- name: chain_slug
in: query
description: Blockchain slug, e.g, "ethereum"
required: true
schema:
type: string
example: ethereum
- name: pair_slug
in: query
description: |
Trading pair friendly presentation (token0 symbol - token1 symbol) or pair pool contract address.
Symbols can be in any order: base token - quote token or quote token - base token.
If multiple trading pairs match the same symbol the one with the highest volume is returned
(assuming other trading pairs are ones with a fake token).
Examples of accepted `pair_slugs`:
- `ETH-USDC`
- `eth-usdc`
- `WETH-USDC`
- `USDC-WETH`
- `0xB4e16d0168e52d35CaCD2c6185b44281Ec28C9Dc`
The response is a composite of pair summary information, additional trading volume numbers and related links.
required: true
schema:
type: string
example: ETH-USDC
tags:
- Trading pair
responses:
'200':
description: OK
content:
application/json:
schema:
$ref: '#/components/schemas/PairFullInfo'
'404':
description: Pair not found
"422":
description: Unexpected error - usually bad query input
content:
application/json:
schema:
$ref: "#/components/schemas/GenericErrorModel"
'/pair-trade-data':
x-pyramid-route-name: web_pair_trade_data
get:
operationId: web_pair_trade_data
summary: |
Key performance metrics of a trading pair for a given time window
parameters:
- name: pair_id
in: query
description: |
Pair id as received in `/pairs` or `/pair-details`
As the endpoint /pair-details is preferred, this endpoint only gives direct pair_id access for now.
required: true
schema:
type: integer
example: 1
- name: period
in: query
description: |
The time perid for the stats.
Currently only latest stats are supported.
required: true
schema:
type: string
enum: [hourly, daily, weekly, monthly]
example: hourly
tags:
- Trading pair
responses:
'200':
description: OK
content:
application/json:
schema:
$ref: '#/components/schemas/TimeSpanTradeData'
'404':
description: Pair not found or time bucket not suppoted
"422":
description: Unexpected error - usually bad query input
content:
application/json:
schema:
$ref: "#/components/schemas/GenericErrorModel"
'/pairs':
x-pyramid-route-name: web_pairs
get:
operationId: web_pairs
summary: Query and filter trading pairs
description: |
Query different combinations of the trading pairs.
The most common query is all trading pairs of a decentralised exchange.
`/pairs?chain_slugs=ethereum&exchange-slugs=uniswap-v2`
- Can return paginated JSON results for the frontend.
- Can return Microsoft XLSX export of the data. In this case, always get the first 3000 entries.
## Parameter seralisation
Note that lists are not JSON serialised, but use [OpenAPI query parameter serialization](https://swagger.io/docs/specification/serialization/). I.e. lists are comma separated, no spaces between items.
parameters:
- name: exchange_slugs
in: query
description: Slugs for DEXes to look up
required: false
style: form
explode: false
schema:
type: array
items:
type: string
uniqueItems: true
example:
- uniswap-v2
- name: chain_slugs
in: query
description: Slugs for blockchain to look up
required: false
style: form
explode: false
schema:
type: array
items:
type: string
uniqueItems: true
example:
- ethereum
- name: token_addresses
in: query
style: form
explode: false
description: |
For querying trading pairs for a specific token.
For example, to get BUSD trading pairs on BNB chain,
use the token address `0xe9e7cea3dedca5984780bafc599bd69add087d56`.
This will give you all BUSD trading pairs.
Multiple token addresses can be passed using OpenAPI form style array.
For a specific token, the query must also include `chain_slugs` condition, as
any a token may share the same address across multiple chains.
Some tokens and their trading pairs exist in the database,
but `trading pairs do not fulfill the tracking threshold <https://tradingstrategy.ai/docs/programming/tracking.html>`_.
If you query a single such token address you will get an error, as a developer friendliness
features. These are often "spam tokens". Example:
```shell
curl "https://tradingstrategy.ai/api/pairs?token_addresses=0xccf31fd34a364a21ad32ad91b09f5071f7200a3d"
```
required: false
schema:
type: array
items:
type: string
format: address
- name: page
in: query
description: Page number, zero-indexed
required: false
schema:
type: integer
default: 0
minimum: 0
maximum: 1000
- name: page_size
in: query
description: Limit number of pairs returned (default is 20)
required: false
schema:
type: integer
default: 20
minimum: 1
maximum: 1000
- name: sort
in: query
description: |
What kind of sort options are available for the list.
The default `pair_id` sorting makes only sense for machine-to-machine actions.
The recommended sort method is by descending volume (most interesting trading pairs first).
Pairs with a missing sort property (NULL field value) are placed last.
required: false
schema:
type: string
default: pair_id
minimum: 1
maximum: 100
enum: [pair_id, volume, volume_30d, price_change_24h, liquidity, liquidity_change_abs_24h, liquidity_change_relative_24h, tvl]
- name: direction
in: query
description: |
Sort order:
* `asc` - Ascending, from A to Z
* `desc` - Descending, from Z to A
required: false
schema:
type: string
enum: [asc, desc]
default: asc
- name: filter
in: query
description: |
Filter the results based on liquidity.
This allows exclude noisy micro cap trading pairs.
* `unfiltered` - Returns everything within [the tracking rules](https://tradingstrategy.ai/docs/programming/tracking.html).
* `min_liquidity_100k` - pairs with the current liquidity $100k
* `min_liquidity_1M` - pairs with the current liquidity $1M
required: false
schema:
type: string
enum: [unfiltered, min_liquidity_100k, min_liquidity_1M]
default: min_liquidity_1M
- name: eligible_only
in: query
description: |
If true, omit pairs that do not match the "quality" criteria from results.
For example, one of the criteria if a pair is eligible to be listed in the
results is sufficient trading activity with the pair.
required: false
schema:
type: boolean
default: true
- name: format
in: query
description: |
Output format of the data.
* `json` - return JSON data to be rendered in web frontend.
* `excel` - always limited to top 3000 results. Returns a downloadable file.
required: false
schema:
type: string
enum: [json, excel]
default: json
tags:
- Trading pair
responses:
"200":
description: OK
content:
application/json:
schema:
$ref: '#/components/schemas/PaginatedPairSummary'
"422":
description: Unexpected error
content:
application/json:
schema:
$ref: "#/components/schemas/GenericErrorModel"
'/trading-pair-data-availability':
x-pyramid-route-name: web_trading_pair_data_availability
get:
operationId: web_trading_pair_data_availability
summary: Get the information from the oracle about the availability of the trading pair data
description: |
Fetch the latest updated timestamp for multiple trading pairs.
Because Trading Strategy oracle does not generate empty candles in the case there are no trades,
we need to have another mean to check if the server has up-to-date
data where a Trading Strategy can take a decision on. This is to distinguish between the situation
of data not yet updated and no data (no trades were made during the period).
This endpoint gives you the result of trading pair data availability
for multiple pairs.
parameters:
- name: pair_ids
in: query
description: |
Trading pair ids.
Trading pair ids are not stable. Translate your trading pair symbolic tickers by using `/pair-details` endpoint
before calling this API.
The server has a maximum number of trading pairs it will serve in one request
and will give you an error if you try to ask too many trading pairs once.
required: true
style: form
explode: false
schema:
type: array
items:
type: integer
uniqueItems: true
- name: time_bucket
in: query
description: >
What time bucket to use for the candle time frame.
required: true
schema:
type: string
enum: [1m, 5m, 15m, 1h, 4h, 1d, 7d, 30d]
example: 1h
tags:
- Trading pair
responses:
"200":
description: OK
content:
application/json:
schema:
$ref: '#/components/schemas/TradingPairDataAvailabilityList'
"422":
description: Unexpected error
content:
application/json:
schema:
$ref: "#/components/schemas/GenericErrorModel"
'/candles':
x-pyramid-route-name: web_candles
get:
operationId: web_candles
summary: Get the candle stick chart data for one trading pair
description: |
Fetch candle data for selected trading pairs.
You need to resolve the symbolic trading pair names to their internal IDs with
`/pairs` or `/pair-details` to call this API endpoint.
Candles are available for several different pair metrics and can be chosen by the
`candle_type` parameter. Mind that some candle types may not support all possible
time buckets, and time spans for which the data is available may differ.
In addition, not all candle types contain additiona stats, and may only contain
the base Open, High, Low, and Close values (+ candle timestamp).
Candle response size is limited to 10,000 candles. Only the first 10,000 candles
since the start timestamp are returned.
[Inspired by Bitfinex API](https://docs.bitfinex.com/reference#rest-public-candles).
parameters:
- name: pair_ids
in: query
description: |
Primary keys of the trading pairs to fetch the candles for. A maximum of 100
IDs can be passed at a time.
required: false
style: form
explode: false
schema:
type: array
items:
type: integer
minimum: 1
minItems: 1
maxItems: 100
uniqueItems: true
example: "12,6,171"
- name: pair_id
in: query
description: |
**WARNING:** Deprecated, use `pair_ids` instead. Will be removed in future
API versions.
Primary key for the trading pair.
[You can grab any trading pair from Trading Strategy website](https://tradingstrategy.ai/trading-view/trading-pairs).
The primary key is displayed in as internal id.
Ignored if `pair_ids` parameter is also passed.
required: false
schema:
type: integer
minimum: 1
example: 7
- name: time_bucket
in: query
description: >
What time bucket to use for the candle size.
required: true
schema:
type: string
enum: [1m, 5m, 15m, 1h, 4h, 1d, 7d, 30d]
example: 1h
- name: candle_type
in: query
description: |
The pair metric to retrieve the candle data for. Normally the price (measured
in the quote token), but other candle types are also supported.
schema:
type: string
enum: [price, tvl]
default: price
- name: start
in: query
description: |
When the candle fetch period starts.
Use UNIX UTC timestamp, as ISO 8601 formatted string.
[Read more information about the time format](https://docs.python.org/3/library/datetime.html#datetime.datetime.fromisoformat).
If not specific this will be resolved to now() - time_bucket * 100, or getting the last 100 candles.
This range parameter is inclusive.
required: false
schema:
type: string
format: iso8601
example: 2022-01-01
- name: end
in: query
description: |
When the candle fetch period ends.
Use UNIX UTC timestamp, as ISO 8601 formatted string.
If not specific this will be resolved to now().
This range parameter is inclusive.
required: false
schema:
type: string
format: iso8601
minimum: 0
example: 2022-01-02
- name: exchange_type
in: query
description: Exchange type enum - see https://tradingstrategy.ai/docs/programming/api/client/help/tradingstrategy.exchange.ExchangeType.html
required: false
schema:
type: string
example: uniswap_v2
tags:
- Trading pair
responses:
"200":
description: OK
content:
application/json:
schema:
oneOf:
- $ref: '#/components/schemas/MultipairCandleList'
- $ref: '#/components/schemas/MultipairMinimalCandleList'
"422":
description: Unexpected error
content:
application/json:
schema:
$ref: "#/components/schemas/GenericErrorModel"
'/candles-jsonl':
x-pyramid-route-name: web_candles_jsonl
get:
operationId: web_candles_jsonl
summary:
Get the candle data for multiple trading pairs in JSONL format.
description: |
This is preferred method for getting OHLCV data if you need
full historical data for small number od trading pairs.
There is very high limit on amount of data that can be fetched
using this method.
The response is [UTF-8 encoded JSON Lines](https://jsonlines.org/) streamed binary response.
The size of the response cannot be known ahead of time.
Candles are returned from the earliest to the latest.
If no start time is given, start from the genesis.
The server has a byte limit for each response. This is controlled
by `max_bytes` parameter. If the response reaches more than
`max_bytes` in length it is terminated with JSON object
`{"error": true, "max_bytes_reached": served_bytes}`.
The highest value, and response length, you can ask is 100M bytes.
Because Trading Strategy oracle does not generate empty candles when there are no trades,
you might want to distinguish no data yet available and no trade situations
using `/trading-pair-data-availability` endpoint.
**TODO**: Specify the actual per-line JSONL format in OpenAPI schema.
An example code how to stream and decode JSONL OHLCV candles in Python:
```
"""A sample script to download JSONL candle data.
Request all historical data for
- 15m candles
- ETH/USDC
- BNB/BUSD
The download JSONL binary size is 28 Mbytes
"""
import datetime
from collections import defaultdict
from io import StringIO
import requests
import jsonlines
api_url = "https://tradingstrategy.ai/api"
bnb_busd_params = {
"chain_slug": "binance",
"exchange_slug": "pancakeswap-v2",
"pair_slug": "bnb-busd",
}
resp = requests.get(f"{api_url}/pair-details", bnb_busd_params)
assert resp.status_code == 200, f"Got {resp.text}"
bnb_busd = resp.json()
print("Pair #1", bnb_busd["summary"]["pair_name"], bnb_busd["summary"]["pair_id"])
eth_usdc_params = {
"chain_slug": "ethereum",
"exchange_slug": "uniswap-v2",
"pair_slug": "eth-usdc",
}
resp = requests.get(f"{api_url}/pair-details", eth_usdc_params)
assert resp.status_code == 200, f"Got {resp.text}"
eth_usdc = resp.json()
print("Pair #2", eth_usdc["summary"]["pair_name"], eth_usdc["summary"]["pair_id"])
id_list = (eth_usdc["summary"]["pair_id"], bnb_busd["summary"]["pair_id"])
params = {
"pair_ids": ",".join(str(i) for i in id_list),
"time_bucket": "15m",
}
# Iterate the resulting response
# using jsonlines reader.
# We start to decode incoming data on the first arrived byte
# and keep decoding while streaming the response.
# https://stackoverflow.com/a/60846477/315168
print("Loading OHLCV data")
resp = requests.get(f"{api_url}/candles-jsonl", params=params, stream=True)
reader = jsonlines.Reader(resp.raw)
print("Iterating response")
candle_data = defaultdict(list)
for item in reader:
pair_id = item["p"]
candle_data[pair_id].append(item)
eth_usdc_candles = candle_data[eth_usdc["summary"]["pair_id"]]
first_candle = datetime.datetime.utcfromtimestamp(eth_usdc_candles[0]["ts"])
last_candle = datetime.datetime.utcfromtimestamp(eth_usdc_candles[-1]["ts"])
bnb_busd_candles = candle_data[bnb_busd["summary"]["pair_id"]]
print(f"ETH-USDC has {len(eth_usdc_candles):,} candles from {first_candle} to {last_candle}")
print(f"BNB-BUSD has {len(bnb_busd_candles):,} candles")
```
parameters:
- name: pair_ids
in: query
description: |
Trading pair ids.
Trading pair ids are not stable. Translate your trading pair symbolic tickers by using `/pair-details` endpoint
before calling this API.
The server has a maximum number of trading pairs it will serve in one request
and will give you an error if you try to ask too many trading pairs once.
required: false
style: form
explode: false
schema:
type: array
items:
type: integer
uniqueItems: true
- name: time_bucket
in: query
description: >
What time bucket to use for the candle size.
required: true
schema: