GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — ccxt/python/ccxt/alpaca.py at master · ccxt/ccxt

Expand file tree

/

alpaca.py

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
2155 lines (2061 loc) · 98.4 KB
/

alpaca.py

Copy path

File metadata and controls

2155 lines (2061 loc) · 98.4 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
# -*- coding: utf-8 -*-
# PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
# https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
from ccxt.base.exchange import Exchange
from ccxt.abstract.alpaca import ImplicitAPI
from ccxt.base.types import Balances, Currency, DepositAddress, Int, Market, Num, Order, OrderBook, OrderSide, OrderType, Str, Strings, Ticker, Tickers, Trade, Transaction
from ccxt.base.errors import ExchangeError
from ccxt.base.errors import PermissionDenied
from ccxt.base.errors import BadRequest
from ccxt.base.errors import BadSymbol
from ccxt.base.errors import InsufficientFunds
from ccxt.base.errors import InvalidOrder
from ccxt.base.errors import NotSupported
from ccxt.base.errors import RateLimitExceeded
from ccxt.base.decimal_to_precision import TICK_SIZE
from ccxt.base.precise import Precise
class alpaca(Exchange, ImplicitAPI):
def describe(self) -> dict:
return self.deep_extend(super(alpaca, self).describe(), {
'id': 'alpaca',
'name': 'Alpaca',
'countries': ['US'],
# 3 req/s for free
# 150 req/s for subscribers: https://alpaca.markets/data
# for brokers: https://alpaca.markets/docs/api-references/broker-api/#authentication-and-rate-limit
'rateLimit': 333,
'hostname': 'alpaca.markets',
'pro': True,
'urls': {
'logo': 'https://github.com/user-attachments/assets/e9476df8-a450-4c3e-ab9a-1a7794219e1b',
'www': 'https://alpaca.markets',
'api': {
'broker': 'https://broker-api.{hostname}',
'trader': 'https://api.{hostname}',
'market': 'https://data.{hostname}',
},
'test': {
'broker': 'https://broker-api.sandbox.{hostname}',
'trader': 'https://paper-api.{hostname}',
'market': 'https://data.{hostname}',
},
'doc': 'https://alpaca.markets/docs/',
'fees': 'https://docs.alpaca.markets/docs/crypto-fees',
},
'has': {
'CORS': False,
'spot': True,
'margin': False,
'swap': False,
'future': False,
'option': False,
'addMargin': False,
'borrowCrossMargin': False,
'borrowIsolatedMargin': False,
'borrowMargin': False,
'cancelAllOrders': True,
'cancelOrder': True,
'closeAllPositions': False,
'closePosition': False,
'createMarketBuyOrder': True,
'createMarketBuyOrderWithCost': True,
'createMarketOrderWithCost': True,
'createMarketSellOrderWithCost': True,
'createOrder': True,
'createOrderWithTakeProfitAndStopLoss': False,
'createOrderWithTakeProfitAndStopLossWs': False,
'createReduceOnlyOrder': False,
'createStopOrder': True,
'createTriggerOrder': True,
'editOrder': True,
'fetchBalance': True,
'fetchBidsAsks': False,
'fetchBorrowInterest': False,
'fetchBorrowRate': False,
'fetchBorrowRateHistories': False,
'fetchBorrowRateHistory': False,
'fetchBorrowRates': False,
'fetchBorrowRatesPerSymbol': False,
'fetchClosedOrders': True,
'fetchCrossBorrowRate': False,
'fetchCrossBorrowRates': False,
'fetchCurrencies': False,
'fetchDepositAddress': True,
'fetchDepositAddressesByNetwork': False,
'fetchDeposits': True,
'fetchDepositsWithdrawals': True,
'fetchFundingHistory': False,
'fetchFundingInterval': False,
'fetchFundingIntervals': False,
'fetchFundingRate': False,
'fetchFundingRateHistory': False,
'fetchFundingRates': False,
'fetchGreeks': False,
'fetchIndexOHLCV': False,
'fetchIsolatedBorrowRate': False,
'fetchIsolatedBorrowRates': False,
'fetchIsolatedPositions': False,
'fetchL1OrderBook': True,
'fetchL2OrderBook': False,
'fetchLeverage': False,
'fetchLeverages': False,
'fetchLeverageTiers': False,
'fetchLiquidations': False,
'fetchLongShortRatio': False,
'fetchLongShortRatioHistory': False,
'fetchMarginAdjustmentHistory': False,
'fetchMarginMode': False,
'fetchMarginModes': False,
'fetchMarketLeverageTiers': False,
'fetchMarkets': True,
'fetchMarkOHLCV': False,
'fetchMarkPrices': False,
'fetchMyLiquidations': False,
'fetchMySettlementHistory': False,
'fetchMyTrades': True,
'fetchOHLCV': True,
'fetchOpenInterest': False,
'fetchOpenInterestHistory': False,
'fetchOpenInterests': False,
'fetchOpenOrder': False,
'fetchOpenOrders': True,
'fetchOption': False,
'fetchOptionChain': False,
'fetchOrder': True,
'fetchOrderBook': True,
'fetchOrders': True,
'fetchPosition': False,
'fetchPositionHistory': False,
'fetchPositionMode': False,
'fetchPositions': False,
'fetchPositionsForSymbol': False,
'fetchPositionsHistory': False,
'fetchPositionsRisk': False,
'fetchPremiumIndexOHLCV': False,
'fetchSettlementHistory': False,
'fetchStatus': False,
'fetchTicker': True,
'fetchTickers': True,
'fetchTime': True,
'fetchTrades': True,
'fetchTradingFee': False,
'fetchTradingFees': False,
'fetchTransactionFees': False,
'fetchTransactions': False,
'fetchTransfers': False,
'fetchVolatilityHistory': False,
'fetchWithdrawals': True,
'reduceMargin': False,
'repayCrossMargin': False,
'repayIsolatedMargin': False,
'sandbox': True,
'setLeverage': False,
'setMargin': False,
'setMarginMode': False,
'setPositionMode': False,
'transfer': False,
'withdraw': True,
},
'api': {
'broker': {
'private': {
'get': {
'v1/accounts/{account_id}/tokenization/requests': {'cost': 1},
'v1/accounts/{account_id}/tokenization/requests/{tokenization_request_id}': {'cost': 1},
'v1/accounts/{account_id}/tokenization/requests:by_client_request_id': {'cost': 1},
'v1/accounts/{account_id}/tokenization/requests:by_issuer_request_id': {'cost': 1},
'v1/fpsl/analytics/{account_id}/loans': {'cost': 1},
'v1/ipos': {'cost': 1},
'v1/ipos/{offering_reference}': {'cost': 1},
'v1/wallets/travel-rule/vasps': {'cost': 1},
'v1beta1/acats': {'cost': 1},
'v1beta1/acats/contrabrokers': {'cost': 1},
'v1beta1/acats/{account_id}': {'cost': 1},
'v1beta1/acats/{account_id}/{acats_id}': {'cost': 1},
'v1beta1/acats/{account_id}/{acats_id}/assets': {'cost': 1},
},
'post': {
'v1beta1/acats/{account_id}': {'cost': 1},
},
'patch': {
'v1/accounts/{account_id}/wallets/whitelists/{whitelisted_address_id}/travel-rule-info': {'cost': 1},
},
},
},
'trader': {
'private': {
'get': {
'v2/account': {'cost': 1},
'v2/orders': {'cost': 1},
'v2/orders/{order_id}': {'cost': 1},
'v2/positions': {'cost': 1},
'v2/positions/{symbol_or_asset_id}': {'cost': 1},
'v2/account/portfolio/history': {'cost': 1},
'v2/watchlists': {'cost': 1},
'v2/watchlists/{watchlist_id}': {'cost': 1},
'v2/watchlists:by_name': {'cost': 1},
'v2/account/configurations': {'cost': 1},
'v2/account/activities': {'cost': 1},
'v2/account/activities/{activity_type}': {'cost': 1},
'v2/calendar': {'cost': 1},
'v2/clock': {'cost': 1},
'v2/assets': {'cost': 1},
'v2/assets/{symbol_or_asset_id}': {'cost': 1},
'v2/corporate_actions/announcements/{id}': {'cost': 1},
'v2/corporate_actions/announcements': {'cost': 1},
'v2/wallets': {'cost': 1},
'v2/wallets/transfers': {'cost': 1},
'v1/locates': {'cost': 1},
'v1/locates/{locate_id}': {'cost': 1},
'v1/locates/quotes': {'cost': 1},
'v2/tokenization/requests': {'cost': 1},
'v2/tokenization/requests/{tokenization_request_id}': {'cost': 1},
'v2/tokenization/requests:by_client_request_id': {'cost': 1},
'v2/wallets/travel-rule/vasps': {'cost': 1},
},
'post': {
'v2/orders': {'cost': 1},
'v2/watchlists': {'cost': 1},
'v2/watchlists/{watchlist_id}': {'cost': 1},
'v2/watchlists:by_name': {'cost': 1},
'v2/wallets/transfers': {'cost': 1},
'v1/locates': {'cost': 1},
},
'put': {
'v2/orders/{order_id}': {'cost': 1},
'v2/watchlists/{watchlist_id}': {'cost': 1},
'v2/watchlists:by_name': {'cost': 1},
},
'patch': {
'v2/orders/{order_id}': {'cost': 1},
'v2/account/configurations': {'cost': 1},
'v2/wallets/whitelists/{whitelisted_address_id}/travel-rule-info': {'cost': 1},
},
'delete': {
'v2/orders': {'cost': 1},
'v2/orders/{order_id}': {'cost': 1},
'v2/positions': {'cost': 1},
'v2/positions/{symbol_or_asset_id}': {'cost': 1},
'v2/watchlists/{watchlist_id}': {'cost': 1},
'v2/watchlists:by_name': {'cost': 1},
'v2/watchlists/{watchlist_id}/{symbol}': {'cost': 1},
},
},
},
'market': {
'public': {
'get': {
'v1beta3/crypto/{loc}/bars': {'cost': 1},
'v1beta3/crypto/{loc}/latest/bars': {'cost': 1},
'v1beta3/crypto/{loc}/latest/orderbooks': {'cost': 1},
'v1beta3/crypto/{loc}/latest/quotes': {'cost': 1},
'v1beta3/crypto/{loc}/latest/trades': {'cost': 1},
'v1beta3/crypto/{loc}/quotes': {'cost': 1},
'v1beta3/crypto/{loc}/snapshots': {'cost': 1},
'v1beta3/crypto/{loc}/trades': {'cost': 1},
},
},
'private': {
'get': {
'v1beta1/corporate-actions': {'cost': 1},
'v1beta1/fixed_income/latest/prices': {'cost': 1},
'v1beta1/fixed_income/latest/quotes': {'cost': 1},
'v1beta1/forex/latest/rates': {'cost': 1},
'v1beta1/forex/rates': {'cost': 1},
'v1beta1/logos/{symbol}': {'cost': 1},
'v1beta1/news': {'cost': 1},
'v1beta1/screener/stocks/most-actives': {'cost': 1},
'v1beta1/screener/{market_type}/movers': {'cost': 1},
'v2/stocks/auctions': {'cost': 1},
'v2/stocks/bars': {'cost': 1},
'v2/stocks/bars/latest': {'cost': 1},
'v2/stocks/meta/conditions/{ticktype}': {'cost': 1},
'v2/stocks/meta/exchanges': {'cost': 1},
'v2/stocks/quotes': {'cost': 1},
'v2/stocks/quotes/latest': {'cost': 1},
'v2/stocks/snapshots': {'cost': 1},
'v2/stocks/trades': {'cost': 1},
'v2/stocks/trades/latest': {'cost': 1},
'v2/stocks/{symbol}/auctions': {'cost': 1},
'v2/stocks/{symbol}/bars': {'cost': 1},
'v2/stocks/{symbol}/bars/latest': {'cost': 1},
'v2/stocks/{symbol}/quotes': {'cost': 1},
'v2/stocks/{symbol}/quotes/latest': {'cost': 1},
'v2/stocks/{symbol}/snapshot': {'cost': 1},
'v2/stocks/{symbol}/trades': {'cost': 1},
'v2/stocks/{symbol}/trades/latest': {'cost': 1},
},
},
},
},
'timeframes': {
'1m': '1min',
'3m': '3min',
'5m': '5min',
'15m': '15min',
'30m': '30min',
'1h': '1H',
'2h': '2H',
'4h': '4H',
'6h': '6H',
'8h': '8H',
'12h': '12H',
'1d': '1D',
'3d': '3D',
'1w': '1W',
'1M': '1M',
},
'precisionMode': TICK_SIZE,
'requiredCredentials': {
'apiKey': True,
'secret': True,
},
'fees': {
'trading': {
'tierBased': True,
'percentage': True,
'maker': self.parse_number('0.0015'),
'taker': self.parse_number('0.0025'),
'tiers': {
'taker': [
[self.parse_number('0'), self.parse_number('0.0025')],
[self.parse_number('100000'), self.parse_number('0.0022')],
[self.parse_number('500000'), self.parse_number('0.0020')],
[self.parse_number('1000000'), self.parse_number('0.0018')],
[self.parse_number('10000000'), self.parse_number('0.0015')],
[self.parse_number('25000000'), self.parse_number('0.0013')],
[self.parse_number('50000000'), self.parse_number('0.0012')],
[self.parse_number('100000000'), self.parse_number('0.001')],
],
'maker': [
[self.parse_number('0'), self.parse_number('0.0015')],
[self.parse_number('100000'), self.parse_number('0.0012')],
[self.parse_number('500000'), self.parse_number('0.001')],
[self.parse_number('1000000'), self.parse_number('0.0008')],
[self.parse_number('10000000'), self.parse_number('0.0005')],
[self.parse_number('25000000'), self.parse_number('0.0002')],
[self.parse_number('50000000'), self.parse_number('0.0002')],
[self.parse_number('100000000'), self.parse_number('0.00')],
],
},
},
},
'headers': {
'APCA-PARTNER-ID': 'ccxt',
},
'options': {
'minCostUSD': 10, # alpaca floors USD-quoted crypto buy orders at 10 USD notional, a venue parameter that has changed before
'defaultExchange': 'CBSE',
'exchanges': [
'CBSE', # Coinbase
'FTX', # FTXUS
'GNSS', # Genesis
'ERSX', # ErisX
],
'createOrder': {
'timeInForce': 'gtc', # fok, gtc, ioc
},
'clientOrderId': 'ccxt_{id}',
},
'features': {
'spot': {
'sandbox': True,
'createOrder': {
'marginMode': False,
'triggerPrice': True,
'triggerPriceType': None,
'triggerDirection': False,
'stopLossPrice': False, # todo
'takeProfitPrice': False, # todo
'attachedStopLossTakeProfit': {
'triggerPriceType': {
'last': True,
'mark': True,
'index': True,
},
'price': True,
},
'timeInForce': {
'IOC': True,
'FOK': False, # {"code":42210000,"message":"invalid crypto time_in_force"} — verified live 2026-09-13
'PO': False, # {"code":40010001,"message":"invalid time_in_force for crypto order"} — verified live 2026-09-13
'GTD': False,
},
'hedged': False,
'trailing': True, # todo: implementation
'leverage': False,
'marketBuyRequiresPrice': False,
'marketBuyByCost': False,
'selfTradePrevention': False,
'iceberg': False,
},
'createOrders': None,
'fetchMyTrades': {
'marginMode': False,
'limit': 100,
'daysBack': 100000,
'untilDays': 100000,
'symbolRequired': False,
},
'fetchOrder': {
'marginMode': False,
'trigger': False,
'trailing': False,
'symbolRequired': False,
},
'fetchOpenOrders': {
'marginMode': False,
'limit': 500,
'trigger': False,
'trailing': False,
'symbolRequired': False,
},
'fetchOrders': {
'marginMode': False,
'limit': 500,
'daysBack': 100000,
'untilDays': 100000,
'trigger': False,
'trailing': False,
'symbolRequired': False,
},
'fetchClosedOrders': {
'marginMode': False,
'limit': 500,
'daysBack': 100000,
'daysBackCanceled': None,
'untilDays': 100000,
'trigger': False,
'trailing': False,
'symbolRequired': False,
},
'fetchOHLCV': {
'limit': 1000,
},
},
'swap': {
'linear': None,
'inverse': None,
},
'future': {
'linear': None,
'inverse': None,
},
},
'exceptions': {
'exact': {
'forbidden.': PermissionDenied, # {"message": "forbidden."}
'40410000': InvalidOrder, # { "code": 40410000, "message": "order is not found."}
'40010001': BadRequest, # {"code":40010001,"message":"invalid order type for crypto order"}
'40110000': PermissionDenied, # { "code": 40110000, "message": "request is not authorized"}
'42210000': BadRequest, # {"code":42210000,"message":"invalid crypto time_in_force"}
'42910000': RateLimitExceeded, # {"code":42910000,"message":"rate limit exceeded"}
},
'broad': {
'Invalid format for parameter': BadRequest, # {"message":"Invalid format for parameter start: error parsing '0' as RFC3339 or 2006-01-02 time: parsing time \"0\" as \"2006-01-02\": cannot parse \"0\" as \"2006\""}
'Invalid symbol': BadSymbol, # {"message":"Invalid symbol(s): BTC/USDdsda does not match ^[A-Z]+/[A-Z]+$"}
'cost basis must be': InvalidOrder, # {"code":40310000,"message":"cost basis must be >= minimal amount of order 10"}
'insufficient balance for': InsufficientFunds, # {"available":"0","balance":"0","code":40310000,"message":"insufficient balance for USDT (requested: 221.63, available: 0)","symbol":"USDT"}
'orders are rejected by user request': PermissionDenied, # {"code":40310000,"message":"new orders are rejected by user request"} — the account has suspend_trade enabled
},
},
})
def fetch_time(self, params: dict = {}) -> Int:
"""
fetches the current integer timestamp in milliseconds from the exchange server
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns int: the current integer timestamp in milliseconds from the exchange server
"""
response = self.traderPrivateGetV2Clock(params)
#
# {
# timestamp: '2023-11-22T08:07:57.654738097-05:00',
# is_open: false,
# next_open: '2023-11-22T09:30:00-05:00',
# next_close: '2023-11-22T16:00:00-05:00'
# }
#
timestamp = self.parse8601(self.safe_string(response, 'timestamp'))
if timestamp is None:
raise ExchangeError(self.id + ' fetchTime() missing timestamp')
return timestamp
def fetch_markets(self, params: dict = {}) -> list[Market]:
"""
retrieves data on all markets for alpaca
https://docs.alpaca.markets/reference/get-v2-assets
:param dict [params]: extra parameters specific to the exchange API endpoint
:returns dict[]: an array of objects representing market data
"""
request = {
'asset_class': 'crypto',
'status': 'active',
}
assets = self.traderPrivateGetV2Assets(self.extend(request, params))
#
# [
# {
# "id": "c150e086-1e75-44e6-9c2c-093bb1e93139",
# "class": "crypto",
# "exchange": "CRYPTO",
# "symbol": "BTC/USDT",
# "name": "Bitcoin / USD Tether",
# "status": "active",
# "tradable": true,
# "marginable": false,
# "maintenance_margin_requirement": 100,
# "shortable": false,
# "easy_to_borrow": false,
# "fractionable": true,
# "attributes": [],
# "min_order_size": "0.000026873",
# "min_trade_increment": "0.000000001",
# "price_increment": "1"
# }
# ]
#
return self.parse_markets(assets)
def parse_market(self, asset: dict) -> Market:
#
# {
# "id": "c150e086-1e75-44e6-9c2c-093bb1e93139",
# "class": "crypto",
# "exchange": "CRYPTO",
# "symbol": "BTC/USDT",
# "name": "Bitcoin / USD Tether",
# "status": "active",
# "tradable": true,
# "marginable": false,
# "maintenance_margin_requirement": 101,
# "shortable": false,
# "easy_to_borrow": false,
# "fractionable": true,
# "attributes": [],
# "min_order_size": "0.000026873",
# "min_trade_increment": "0.000000001",
# "price_increment": "1"
# }
#
marketId = self.safe_string(asset, 'symbol')
if marketId is None:
raise ExchangeError(self.id + ' parseMarket() missing marketId')
parts = marketId.split('/')
assetClass = self.safe_string(asset, 'class')
baseId = self.safe_string(parts, 0)
quoteId = self.safe_string(parts, 1)
base = self.safe_currency_code(baseId)
quote = self.safe_currency_code(quoteId)
# Us equity markets do not include quote in symbol.
# We can safely coerce us_equity quote to USD
if quote is None and assetClass == 'us_equity':
quote = 'USD'
if (base is None) or (quote is None):
return None
symbol = base + '/' + quote
status = self.safe_string(asset, 'status')
active = (status == 'active')
minAmount = self.safe_number(asset, 'min_order_size')
amount = self.safe_number(asset, 'min_trade_increment')
price = self.safe_number(asset, 'price_increment')
minCost = None
if (assetClass == 'crypto') and (quote == 'USD'):
# alpaca rejects USD-quoted crypto buy orders below 10 USD notional: {"code":40310000,"message":"cost basis must be >= minimal amount of order 10"}
# USDT-, USDC- and BTC-quoted pairs accept smaller orders, and sell orders are not floored — verified live 2026-08-25
minCost = self.safe_number(self.options, 'minCostUSD', self.parse_number('10'))
return self.safe_market_structure({
'id': marketId,
'symbol': symbol,
'base': base,
'quote': quote,
'settle': None,
'baseId': baseId,
'quoteId': quoteId,
'settleId': None,
'type': 'spot',
'spot': True,
'margin': None,
'swap': False,
'future': False,
'option': False,
'active': active,
'contract': False,
'linear': None,
'inverse': None,
'contractSize': None,
'expiry': None,
'expiryDatetime': None,
'strike': None,
'optionType': None,
'precision': {
'amount': amount,
'price': price,
},
'limits': {
'leverage': {
'min': None,
'max': None,
},
'amount': {
'min': minAmount,
'max': None,
},
'price': {
'min': None,
'max': None,
},
'cost': {
'min': minCost,
'max': None,
},
},
'created': None,
'info': asset,
})
def fetch_trades(self, symbol: str, since: Int = None, limit: Int = None, params: dict = {}) -> list[Trade]:
"""
get the list of most recent trades for a particular symbol
https://docs.alpaca.markets/reference/cryptotrades
https://docs.alpaca.markets/reference/cryptolatesttrades
:param str symbol: unified symbol of the market to fetch trades for
:param int [since]: timestamp in ms of the earliest trade to fetch
:param int [limit]: the maximum amount of trades to fetch
:param dict [params]: extra parameters specific to the exchange API endpoint
:param str [params.loc]: crypto location, default: us
:param str [params.method]: method, default: marketPublicGetV1beta3CryptoLocTrades
:returns Trade[]: a list of `trade structures <https://docs.ccxt.com/?id=public-trades>`
"""
if self.markets is None:
self.load_markets()
market = self.market(symbol)
marketId = self.safe_string(market, 'id')
loc = self.safe_string(params, 'loc', 'us')
method = self.safe_string(params, 'method', 'marketPublicGetV1beta3CryptoLocTrades')
request = {
'symbols': marketId,
'loc': loc,
}
paramsOmitted = self.omit(params, ['loc', 'method'])
symbolTrades = None
if method == 'marketPublicGetV1beta3CryptoLocTrades':
if since is not None:
request['start'] = self.iso8601(since)
if limit is not None:
request['limit'] = limit
response = self.marketPublicGetV1beta3CryptoLocTrades(self.extend(request, paramsOmitted))
#
# {
# "next_page_token": null,
# "trades": {
# "BTC/USD": [
# {
# "i": 36440704,
# "p": 22625,
# "s": 0.0001,
# "t": "2022-07-21T11:47:31.073391Z",
# "tks": "B"
# }
# ]
# }
# }
#
trades = self.safe_dict(response, 'trades', {})
symbolTrades = self.safe_list(trades, marketId, [])
elif method == 'marketPublicGetV1beta3CryptoLocLatestTrades':
response = self.marketPublicGetV1beta3CryptoLocLatestTrades(self.extend(request, paramsOmitted))
#
# {
# "trades": {
# "BTC/USD": {
# "i": 36440704,
# "p": 22625,
# "s": 0.0001,
# "t": "2022-07-21T11:47:31.073391Z",
# "tks": "B"
# }
# }
# }
#
trades = self.safe_dict(response, 'trades', {})
symbolTrade = self.safe_dict(trades, marketId, {})
symbolTrades = [symbolTrade]
else:
raise NotSupported(self.id + ' fetchTrades() does not support ' + method + ', marketPublicGetV1beta3CryptoLocTrades and marketPublicGetV1beta3CryptoLocLatestTrades are supported')
symbolTradesList = []
if symbolTrades is not None:
symbolTradesList = symbolTrades
return self.parse_trades(symbolTradesList, market, since, limit)
def fetch_order_book(self, symbol: str, limit: Int = None, params: dict = {}) -> OrderBook:
"""
fetches information on open orders with bid(buy) and ask(sell) prices, volumes and other data
https://docs.alpaca.markets/reference/cryptolatestorderbooks
:param str symbol: unified symbol of the market to fetch the order book for
:param int [limit]: the maximum amount of order book entries to return
:param dict [params]: extra parameters specific to the exchange API endpoint
:param str [params.loc]: crypto location, default: us
:returns dict: an `order book structure <https://docs.ccxt.com/?id=order-book-structure>`
"""
if self.markets is None:
self.load_markets()
market = self.market(symbol)
id = self.safe_string(market, 'id')
loc = self.safe_string(params, 'loc', 'us')
request = {
'symbols': id,
'loc': loc,
}
response = self.marketPublicGetV1beta3CryptoLocLatestOrderbooks(self.extend(request, params))
#
# {
# "orderbooks":{
# "BTC/USD":{
# "a":[
# {
# "p":22208,
# "s":0.0051
# },
# {
# "p":22209,
# "s":0.1123
# },
# {
# "p":22210,
# "s":0.2465
# }
# ],
# "b":[
# {
# "p":22203,
# "s":0.395
# },
# {
# "p":22202,
# "s":0.2465
# },
# {
# "p":22201,
# "s":0.6455
# }
# ],
# "t":"2022-07-19T13:41:55.13210112Z"
# }
# }
# }
#
orderbooks = self.safe_dict(response, 'orderbooks', {})
rawOrderbook = self.safe_dict(orderbooks, id, {})
timestamp = self.parse8601(self.safe_string(rawOrderbook, 't'))
return self.parse_order_book(rawOrderbook, market['symbol'], timestamp, 'b', 'a', 'p', 's')
def fetch_ohlcv(self, symbol: str, timeframe: str = '1m', since: Int = None, limit: Int = None, params: dict = {}) -> list[list]:
"""
fetches historical candlestick data containing the open, high, low, and close price, and the volume of a market
https://docs.alpaca.markets/reference/cryptobars
https://docs.alpaca.markets/reference/cryptolatestbars
:param str symbol: unified symbol of the market to fetch OHLCV data for
:param str timeframe: the length of time each candle represents
:param int [since]: timestamp in ms of the earliest candle to fetch
:param int [limit]: the maximum amount of candles to fetch
:param dict [params]: extra parameters specific to the exchange API endpoint
:param int [params.until]: timestamp in ms of the latest candle to fetch
:param boolean [params.paginate]: default False, when True will automatically paginate by calling self endpoint multiple times. See in the docs all the [available parameters](https://github.com/ccxt/ccxt/wiki/Manual#pagination-params)
:param int [params.paginationCalls]: the maximum number of requests while following next_page_token, default 10 — when the cap is reached the result is silently truncated to the pages already fetched, so raise it for long ranges, 10 requests cover roughly 30 days of 1h candles
:param str [params.loc]: crypto location, default: us
:param str [params.method]: method, default: marketPublicGetV1beta3CryptoLocBars
:returns int[][]: A list of candles ordered as timestamp, open, high, low, close, volume
"""
if self.markets is None:
self.load_markets()
market = self.market(symbol)
marketId = self.safe_string(market, 'id')
loc = self.safe_string(params, 'loc', 'us')
method = self.safe_string(params, 'method', 'marketPublicGetV1beta3CryptoLocBars')
paginate = False
query = None
paginate, query = self.handle_option_bool_and_params(params, 'fetchOHLCV', 'paginate', False)
paginationCalls, queryPagination = self.handle_option_integer_and_params(query, 'fetchOHLCV', 'paginationCalls', 10)
query = queryPagination
request = {
'symbols': marketId,
'loc': loc,
}
query = self.omit(query, ['loc', 'method'])
ohlcvs = None
if method == 'marketPublicGetV1beta3CryptoLocBars':
if limit is not None:
request['limit'] = limit
if since is not None:
request['start'] = self.iso8601(since)
until = self.safe_integer(query, 'until')
if until is not None:
query = self.omit(query, 'until')
request['end'] = self.iso8601(until)
request['timeframe'] = self.safe_string(self.timeframes, timeframe, timeframe)
response = self.marketPublicGetV1beta3CryptoLocBars(self.extend(request, query))
#
# {
# "bars": {
# "BTC/USD": [
# {
# "c": 22887,
# "h": 22888,
# "l": 22873,
# "n": 11,
# "o": 22883,
# "t": "2022-07-21T05:00:00Z",
# "v": 1.1138,
# "vw": 22883.0155324116
# },
# {
# "c": 22895,
# "h": 22895,
# "l": 22884,
# "n": 6,
# "o": 22884,
# "t": "2022-07-21T05:01:00Z",
# "v": 0.001,
# "vw": 22889.5
# }
# ]
# },
# "next_page_token": "QlRDL1VTRHxNfDIwMjItMDctMjFUMDU6MDE6MDAuMDAwMDAwMDAwWg=="
# }
#
bars = self.safe_dict(response, 'bars', {})
ohlcvs = self.safe_list(bars, marketId, [])
if paginate:
# the endpoint answers with a server-sized page plus a next_page_token regardless of the requested limit
pageToken = self.safe_string(response, 'next_page_token')
for i in range(1, paginationCalls):
ohlcvsLength = len(ohlcvs)
if (pageToken is None) or ((limit is not None) and (ohlcvsLength >= limit)):
break
request['page_token'] = pageToken
response = self.marketPublicGetV1beta3CryptoLocBars(self.extend(request, query))
bars = self.safe_dict(response, 'bars', {})
page = self.safe_list(bars, marketId, [])
pageLength = len(page)
if pageLength == 0:
break
ohlcvs = self.array_concat(ohlcvs, page)
pageToken = self.safe_string(response, 'next_page_token')
elif method == 'marketPublicGetV1beta3CryptoLocLatestBars':
response = self.marketPublicGetV1beta3CryptoLocLatestBars(self.extend(request, query))
#
# {
# "bars": {
# "BTC/USD": {
# "c": 22887,
# "h": 22888,
# "l": 22873,
# "n": 11,
# "o": 22883,
# "t": "2022-07-21T05:00:00Z",
# "v": 1.1138,
# "vw": 22883.0155324116
# }
# }
# }
#
bars = self.safe_dict(response, 'bars', {})
bar = self.safe_dict(bars, marketId, {})
ohlcvs = [bar]
else:
raise NotSupported(self.id + ' fetchOHLCV() does not support ' + method + ', marketPublicGetV1beta3CryptoLocBars and marketPublicGetV1beta3CryptoLocLatestBars are supported')
return self.parse_ohlcvs(ohlcvs, market, timeframe, since, limit)
def parse_ohlcv(self, ohlcv: object, market: Market = None) -> list:
#
# {
# "c":22895,
# "h":22895,
# "l":22884,
# "n":6,
# "o":22884,
# "t":"2022-07-21T05:01:00Z",
# "v":0.001,
# "vw":22889.5
# }
#
datetime = self.safe_string(ohlcv, 't')
timestamp = self.parse8601(datetime)
return [
timestamp, # timestamp
self.safe_number(ohlcv, 'o'), # open
self.safe_number(ohlcv, 'h'), # high
self.safe_number(ohlcv, 'l'), # low
self.safe_number(ohlcv, 'c'), # close
self.safe_number(ohlcv, 'v'), # volume
]
def fetch_ticker(self, symbol: str, params: dict = {}) -> Ticker:
"""
fetches a price ticker, a statistical calculation with the information calculated over the past 24 hours for a specific market
https://docs.alpaca.markets/reference/cryptosnapshots-1
:param str symbol: unified symbol of the market to fetch the ticker for
:param dict [params]: extra parameters specific to the exchange API endpoint
:param str [params.loc]: crypto location, default: us
:returns dict: a `ticker structure <https://docs.ccxt.com/?id=ticker-structure>`
"""
if self.markets is None:
self.load_markets()
symbolValue = self.symbol(symbol)
tickers = self.fetch_tickers([symbolValue], params)
ticker = self.safe_dict(tickers, symbolValue)
return ticker
def fetch_tickers(self, symbols: Strings = None, params: dict = {}) -> Tickers:
"""
fetches price tickers for multiple markets, statistical information calculated over the past 24 hours for each market
https://docs.alpaca.markets/reference/cryptosnapshots-1
:param str[] [symbols]: unified symbols of the markets to fetch tickers for, defaults to all markets
:param dict [params]: extra parameters specific to the exchange API endpoint
:param str [params.loc]: crypto location, default: us
:returns dict: a dictionary of `ticker structures <https://docs.ccxt.com/?id=ticker-structure>`
"""
if self.markets is None:
self.load_markets()
# every listed market is a crypto market because fetchMarkets requests asset_class=crypto, so default to all of them
# symbol iteration order differs per language
symbolsSorted = self.sort(self.symbols) if (symbols is None) else symbols
symbolsNormalized = self.market_symbols(symbolsSorted)
loc = self.safe_string(params, 'loc', 'us')
ids = self.market_ids(symbolsNormalized)
request = {
'symbols': ','.join(ids),
'loc': loc,
}
paramsOmitted = self.omit(params, 'loc')
response = self.marketPublicGetV1beta3CryptoLocSnapshots(self.extend(request, paramsOmitted))
#
# {
# "snapshots": {
# "BTC/USD": {
# "dailyBar": {
# "c": 69403.554,
# "h": 69609.6515,
# "l": 69013.26,
# "n": 9,
# "o": 69536.7,
# "t": "2024-11-01T05:00:00Z",
# "v": 0.210809181,
# "vw": 69327.655393908
# },
# "latestQuote": {
# "ap": 69424.19,
# "as": 0.68149,
# "bp": 69366.086,
# "bs": 0.68312,
# "t": "2024-11-01T08:31:41.880246926Z"
# },
# "latestTrade": {
# "i": 5272941104897543146,
# "p": 69416.9,
# "s": 0.014017324,
# "t": "2024-11-01T08:14:28.245088803Z",
# "tks": "B"
# },
# "minuteBar": {
# "c": 69403.554,
# "h": 69403.554,
# "l": 69399.125,
# "n": 0,
# "o": 69399.125,
# "t": "2024-11-01T08:30:00Z",
# "v": 0,
# "vw": 0
# },
# "prevDailyBar": {
# "c": 69515.1415,
# "h": 72668.837,
# "l": 68796.85,
# "n": 129,
# "o": 72258.9,
# "t": "2024-10-31T05:00:00Z",
# "v": 2.217683307,
# "vw": 70782.6811608144
# }
# },
# }
# }
View remainder of file in raw view
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.