这是一种基于Pyhton的API,使用Selenium,并要求从Trading212平台获取信息,请注意,我本人或Trading212对与此API的使用有关的结果负责。
我将继续从事这个项目,并将对任何反馈进行加注。
PIP安装APIT212
要开始使用此API,您首先需要使用APIT212登录到帐户,然后您可以使用所有功能并创建自己的交易机器人或将其用于Trading212平台的Scarpe数据。
from apit212 import *
api = Apit212 ()
api . setup ( username = "[email protected]" , password = "pass******" , mode = "demo" )
from apit212 import *
api = Apit212 ()
api . setup ( username = "[email protected]" , password = "pass******" , mode = "live" )
最好设置一个ENV文件来保存敏感信息,例如您的用户名或密码。这是一个有用的链接.env
USER = [email protected]
PASS = password123
from dotenv import load_dotenv
from apit212 import *
import os
load_dotenv ( '.env' )
username : str = os . getenv ( 'USER' )
password : str = os . getenv ( 'PASS' )
api = Apit212 ()
api . setup ( username = "[email protected]" , password = "pass******" , mode = "demo" )
没有正确的股票符号,此API是没有用的,因此我有一个解决方案。
from apit212 import Tickers
ticker = Tickers ()
print ( ticker . fetch_symbols ( symbol = 'META' ))
print ( ticker . find_by_name ( full_name = 'tesla' ))
有很多数据需要阅读,但是您追求的关键是tricker,这将返回Trading212平台使用的符号。
[{ ' ticker ' : ' FB ' , ' type ' : ' STOCK ' , ' currency ' : ' USD ' , ' shortName ' : ' META ' , ' fullName ' : ' Meta Platforms ' , ' description ' : ' Meta Platforms Inc ' , ' minTrade ' : 0.1, ' digitsPrecision ' : 2, ' exchangeId ' : 68, ' tradable ' : True, ' underlyingInstrumentTicker ' : ' FB_US_EQ ' , ' underlyingLeverageCoefficient ' : 1.0, ' dealerExclusions ' : [], ' maxOpenLong ' : 1121, ' leverage ' : ' 1:5 ' , ' insignificantDigits ' : 0, ' baseTicker ' : nan, ' expiryDate ' : nan, ' minTradeSizeCoefficient ' : 10.0, ' isin ' : ' US30303M1027 ' , ' countryOfOrigin ' : ' US ' , ' quantityPrecision ' : 1.0, ' priorityIndex ' : 25.0, ' maxTrade ' : nan, ' conditionalVisibility ' : nan, ' suspended ' : nan}]
[{ ' ticker ' : ' TSLA ' , ' type ' : ' STOCK ' , ' currency ' : ' USD ' , ' shortName ' : ' TSLA ' , ' fullName ' : ' Tesla ' , ' description ' : ' Tesla, Inc. ' , ' minTrade ' : 0.1, ' digitsPrecision ' : 2, ' exchangeId ' : 68, ' tradable ' : True, ' underlyingInstrumentTicker ' : ' TSLA_US_EQ ' , ' underlyingLeverageCoefficient ' : 1.0, ' dealerExclusions ' : [], ' maxOpenLong ' : 1405, ' leverage ' : ' 1:5 ' , ' insignificantDigits ' : 0, ' baseTicker ' : nan, ' expiryDate ' : nan, ' minTradeSizeCoefficient ' : 10.0, ' isin ' : ' US88160R1014 ' , ' countryOfOrigin ' : ' US ' , ' quantityPrecision ' : 1.0, ' priorityIndex ' : 100.0, ' maxTrade ' : nan, ' conditionalVisibility ' : nan, ' suspended ' : nan}]
from apit212 import Tickers
ticker = Tickers ()
meta = ticker . fetch_symbols ( symbol = 'META' )
print ( len ( meta ))
print ( meta [ 0 ][ 'ticker' ])
使用广泛使用的股票程序查找股票通常会返回1个结果,但是在某些情况下,您可能会得到多个结果,因此可以检查返回的字符串的好习惯。
1
FB
交易CFD简单地称为CFD类
from apit212 import *
api = Apit212 ()
api . setup ( username = "[email protected]" , password = "pass******" , mode = "demo" )
cfd = CFD ( cred = api )
交易权益简单地称呼股权类。
from apit212 import *
client = Apit212 ( username = "[email protected]" , password = "pass******" , mode = "live" )
equity = Equity ()
auth_validate函数将返回帐户ID和交易类型。
validate = cfd . auth_validate ()
print ( validate )
{ ' id ' : ' *******-****-****-****-************ ' , ' accountId ' : ******** , ' customerId ' : ********* , ' tradingType ' : ' CFD ' , ' customerUuid ' : ' ********-****-****-****-************ ' , ' frontend ' : ' WC4 ' , ' readyToTrade ' : True, ' deviceUuid ' : ' ' }
get_account功能将返回您的帐户详细信息。
account = cfd . get_account ()
print ( account )
{ ' demoAccounts ' : [{ ' id ' : ******** , ' type ' : ' DEMO ' , ' tradingType ' : ' CFD ' , ' customerId ' : ******** ,
' createdDate ' : ' 2023-01-17T03:20:48.000+00:00 ' , ' status ' : ' ACTIVE ' , ' registerSource ' : ' WC4 ' ,
' currencyCode ' : ' GBP ' , ' readyToTrade ' : True}], ' liveAccounts ' : [{ ' id ' : ******** , ' type ' : ' LIVE ' ,
' tradingType ' : ' CFD ' , ' customerId ' : ******** , ' createdDate ' : ' 2023-01-17T03:20:32.000+00:00 ' ,
' status ' : ' PENDING_ACTIVATION ' , ' registerSource ' : ' WC4 ' , ' currencyCode ' : ' GBP ' , ' readyToTrade ' : False}]}
get_funds功能将返回帐户资金。
funds = cfd . get_funds ()
print ( funds )
{ ' ******* ' : { ' accountId ' : ******** , ' tradingType ' : ' CFD ' , ' currency ' : ' GBP ' ,
' freeForWithdraw ' : 486.83, ' freeForCfdTransfer ' : 0, ' total ' : 486.83,
' lockedCash ' : { ' totalLockedCash ' : 0, ' lockedCash ' : []}}}
get_summary返回您帐户的摘要。
summary = cfd . get_summary ()
print ( summary )
' open ' : { ' unfilteredCount ' : 1, ' items ' : [{ ' positionId ' : ' ********-****-****-****-************ ' , ' humanId ' : ' ******** ' ,
' created ' : ' 2023-07-03T18:17:46.563+03:00 ' , ' averagePrice ' : 192.25, ' averagePriceConverted ' : 150.73025341182984,
' currentPrice ' : 192.2, ' value ' : 1054.82, ' investment ' : 1055.11, ' code ' : ' AAPL ' , ' margin ' : 212.02, ' ppl ' : -0.28,
' quantity ' : 7, ' maxBuy ' : 9.0, ' maxSell ' : 7, ' maxOpenBuy ' : 2033.0, ' maxOpenSell ' : 2040.0, ' swap ' : -1.06, ' frontend ' : ' WC4 ' }]}
GET_COMPANIES返回可以在Trading212平台上进行交易的工具
companies = cfd . get_companies ()
print ( companies )
[{ ' ticker ' : ' SIGTl_EQ ' , ' isin ' : ' GB0008769993 ' }, { ' ticker ' : ' PDYPY_US_EQ ' , ' isin ' : ' US3440441026 ' }...]
GET_INSTROMENT_INFO将返回有关仪器的信息。
info = cfd . get_instruments_info ( instrument = "TSLA" )
print ( info )
{ ' code ' : ' TSLA ' , ' type ' : ' STOCK ' , ' margin ' : 0.2, ' shortPositionSwap ' : -0.07030593058663,
' longPositionSwap ' : -0.27928156941337, ' tsSwapCharges ' : ' 1970-01-01T23:00:00.000+02:00 ' ,
' marginPercent ' : ' 20 ' , ' leverage ' : ' 1:5 ' }
GET_ORDER_INFO GET
orderInfo = cfd . get_order_info ( instrument = "TSLA" , quamtity = 1.5 )
print ( orderInfo )
{ ' buyMargin ' : 40.18, ' sellMargin ' : 40.18, ' buySwap ' : -0.2, ' sellSwap ' : -0.05}
tickers = [ "TSLA" , "AAPL" ]
deviation = cfd . get_deviations ( instruments = tickers )
print ( deviation )
[{ ' request ' : { ' ticker ' : ' TSLA ' , ' useAskPrice ' : False}, ' response ' : { ' timestamp ' : 1694073610000, ' price ' : 250.68, ' period ' : ' d1 ' }}, { ' request ' : { ' ticker ' : ' AAPL ' , ' useAskPrice ' : False}, ' response ' : { ' timestamp ' : 1694073610000, ' price ' : 178.18, ' period ' : ' d1 ' }}]
get_position返回给定位置ID的信息,该ID可以从get_summary函数中删除
position = cfd . get_position ( position_id = 274187113 )
print ( position )
[{ ' eventType ' : { ' action ' : ' opened ' , ' source ' : ' MARKET_ORDER ' },
' eventNumber ' : { ' name ' : ' MO3053019640 ' , ' id ' : ' 274187113 ' , ' frontend ' : ' WC4 ' }, ' time ' : ' 2023-08-02T22:42:54.000+03:00 ' ,
' direction ' : ' sell ' , ' quantity ' : 1.0, ' price ' : ' 105.29 ' , ' avgQuantity ' : 1.0, ' avgPrice ' : ' 105.2900 ' , ' modifiedDirection ' :
' sell ' }]
GET_ALL_RESULT功能将返回您所有交易结果的列表。您需要要求每个页面。您可能还需要通过时区。
results = cfd . get_all_results ()
print ( results )
{ ' data ' : [{ ' direction ' : ' buy ' , ' code ' : ' AAPL ' , ' quantity ' : 0.1, ' orderNumber ' : { ' name ' : ' P************ ' , ' link ' : ' positionHistory/********-****-****-****-************ ' , ' id ' : ' ********-****-****-****-************ ' , ' frontend ' : ' WC4 ' }, ' price ' : ' 176.6700 ' , ' closePrice ' : ' 181.98 ' , ' result ' : ' 0.42 ' , ' eventNumber ' : { ' name ' : ' PO3062546222 ' , ' id ' : ' ********-****-****-****-************ ' }, ' eventType ' : ' closed ' , ' time ' : ' 2023-08-29T17:15:55.000+03:00 ' , ' openingTime ' : ' 2023-08-25T11:51:15.000+03:00 ' }, ...], ' nextPage ' : ' result?perPage=20&onlyFullyClosed=false&page=2 ' , ' currentPage ' : ' result?perPage=20&onlyFullyClosed=false&page=1 ' , ' totalSize ' : 133}
orderHist = cfd . get_order_hist ( page_number = 1 )
print ( orderHist )
{ ' data ' : [], ' currentPage ' : ' order?filter=all&perPage=20&from=2023-09-06T02:00:00.000+03:00&to=2023-09-08T01:59:59.173+03:00&page=1 ' , ' totalSize ' : 0}
positionHist = cfd . get_posistion_hist ( page_number = 1 )
print ( positionHist )
{ ' data ' : [], ' currentPage ' : ' position?perPage=20&from=2023-09-06T02:00:00.000+03:00&to=2023-09-08T01:59:59.173+03:00&page=1 ' , ' totalSize ' : 0}
Fast_price将仪器价格作为浮点部重新启动。如果请求失败,则没有返回
price = cfd . fast_price ( instrument = "TSLA" )
print ( price )
253.49
Chart_data返回了带有蜡烛日期OHLC(开放,高,低,关闭)的字典。默认设置为1分钟。
charts = cfd . chart_data ( instrument = "TSLA" , period = "ONE_MINUTE" )
print ( charts )
[{ ' request ' : { ' ticker ' : ' TSLA ' , ' period ' : ' ONE_MINUTE ' , ' size ' : 500, ' useAskPrice ' : False}, ' response ' : { ' candles ' : [[1691152740000, 259.6, 259.97, 259.43, 259.49, 47], [1691152800000, 259.38, 259.94, 259.17, 259.56, 58], [1691152860000, 259.62, 260.34, 259.62, 260.19, 42]
Multi_price函数将返回所有通过的仪器的最后一个QOUT价格。
tickers = [ "TSLA" , "AAPL" , "GOOG" ]
multiprice = cfd . multi_price ( instruments = tickers )
print ( multiprice )
[{ ' ticker ' : ' TSLA ' , ' price ' : 251.34}, { ' ticker ' : ' AAPL ' , ' price ' : 181.96}, { ' ticker ' : ' GOOG ' , ' price ' : 135.18}]
Market_order功能提交市场订单,需要该工具的当前价格。
targetPrice = cfd . fast_price ( instrument = "TSLA" )
marketOrder = cfd . market_order ( instrument = "TSLA" , target_price = targePrice ,
quantity = 1.5 , take_profit = 10 , stop_loss = 10 )
limit_order函数提交限制顺序
marketOrder = cfd . limit_order ( instrument = "TSLA" , target_price = 127 ,
quantity = 1.5 , take_profit = 10 , stop_loss = 10 )
set_limits函数允许您修改或添加ofeross或takeprofit到现有邮局(需要positionID才能执行此功能)
limits = cfd . set_limits ( position_id = 27361748 , TP = 10 , SL = 10 )
add_trailing_stop函数在现有位置添加了一个尾声
trailing = cfd . add_trailing_stop ( position_id = 27361748 , distance = 1 )
CLOSS_POINTION函数用于关闭打开位置。它需要当前价格。
currentPrice = cfd . fast_price ( instrument = "TSLA" )
close = cfd . close_position ( position_id = 23948174 , current_price = currentPrice )
cancelAll = cfd . cancel_all_orders ()
CANCEL_ORDER函数用于取消限制顺序。
cancel = cfd . cancel_order ( order_id = ** ** ** ** ** )
get_live功能将返回股票的当前价格
tickers = [ "TSLA" , "AAPL" ]
prices = cfd . live_price ( instruments = tickers )
print ( prices )
[{ ' request ' : { ' ticker ' : ' TSLA ' , ' useAskPrice ' : False}, ' response ' : { ' timestamp ' : 1690531210000, ' price ' : 255.8, ' period ' : ' d1 ' }}, { ' request ' : { ' ticker ' : ' AAPL ' , ' useAskPrice ' : False}, ' response ' : { ' timestamp ' : 1690531210000, ' price ' : 193.29, ' period ' : ' d1 ' }}]
get_funds功能将返回您的帐户资金。
funds = cfd . get_funds ()
print ( funds )
{ ' 20434246 ' : { ' accountId ' : ******** , ' tradingType ' : ' CFD ' , ' currency ' : ' GBP ' ,
' freeForWithdraw ' : 486.83, ' freeForCfdTransfer ' : 0, ' total ' : 486.83,
' lockedCash ' : { ' totalLockedCash ' : 0, ' lockedCash ' : []}}}
Taxing_Stop功能允许您在开放位置中添加一个尾声。
trailing_stop = cfd . trailing_stop ( position_id = "***-****-***" , distance = 0.5 )
ADD_LIMITS功能允许您将Sotloss和TakeProfit添加到现有位置。
update_limits = client . add_limits ( position_id = "***-****-***" , TP = 1 , SL = 1 )
要设置新的止动或TakeProfit,只需将距离传递到TP(获利)或SL(停止损失)参数。该功能将获得当前价格并应用距离。
all_position_hist函数将返回位置历史记录。
position_history = cfd . all_position_hist ()
all_order_hist返回订单数据
order_history = cfd . all_order_hist ()
get_instrument函数将重新编写有关仪器的信息。
tsla_info = cfd . get_instruments_info ( instrument = 'TSLA' )
print ( tsla_info )
{ ' code ' : ' TSLA ' , ' type ' : ' STOCK ' , ' margin ' : 0.2, ' shortPositionSwap ' : -0.07030593058663,
' longPositionSwap ' : -0.27928156941337, ' tsSwapCharges ' : ' 1970-01-01T23:00:00.000+02:00 ' ,
' marginPercent ' : ' 20 ' , ' leverage ' : ' 1:5 ' }
get_position函数将返回qouted positionID的信息。
position = cfd . get_position ( position_id = "***-****-***" )
print ( position )
[{ ' eventType ' : { ' action ' : ' opened ' , ' source ' : ' MARKET_ORDER ' },
' eventNumber ' : { ' name ' : ' MO3053019640 ' , ' id ' : ' 274187113 ' , ' frontend ' : ' WC4 ' }, ' time ' : ' 2023-08-02T22:42:54.000+03:00 ' ,
' direction ' : ' sell ' , ' quantity ' : 1.0, ' price ' : ' 105.29 ' , ' avgQuantity ' : 1.0, ' avgPrice ' : ' 105.2900 ' , ' modifiedDirection ' :
' sell ' }]
get_summary函数将返回帐户摘要。此功能也可以用于获取订单ID,并且当前有ppl
summary = cfd . get_summary ()
print ( summary )
' open ' : { ' unfilteredCount ' : 1, ' items ' : [{ ' positionId ' : ' ********-****-****-****-************ ' , ' humanId ' : ' ******** ' ,
' created ' : ' 2023-07-03T18:17:46.563+03:00 ' , ' averagePrice ' : 192.25, ' averagePriceConverted ' : 150.73025341182984,
' currentPrice ' : 192.2, ' value ' : 1054.82, ' investment ' : 1055.11, ' code ' : ' AAPL ' , ' margin ' : 212.02, ' ppl ' : -0.28,
' quantity ' : 7, ' maxBuy ' : 9.0, ' maxSell ' : 7, ' maxOpenBuy ' : 2033.0, ' maxOpenSell ' : 2040.0, ' swap ' : -1.06, ' frontend ' : ' WC4 ' }]}
LIVE_PRICE功能将返回通过仪器的当前询问价格。
ticker = [ "TSLA" , "AAPL" , "GOOG" ]
live_price = cfd . live_price ( instruments = ticker )
print ( live_price )
[{ ' ticker ' : ' TSLA ' , ' price ' : 253.49}, { ' ticker ' : ' AAPL ' , ' price ' : 182.08}, { ' ticker ' : ' GOOG ' , ' price ' : 128.44}]
fast_price函数将返回最后一个Qout的图表价格作为浮点
price = cfd . fast_price ( instrument = "TSLA" )
print ( price )
253.49
Chart_data功能将返回传递仪器的最后图表数据
chart = cfd . chart_data ( instrument = "TSLA" )
print ( chart )
[{ ' request ' : { ' ticker ' : ' TSLA ' , ' period ' : ' ONE_MINUTE ' , ' size ' : 500, ' useAskPrice ' : False}, ' response ' : { ' candles ' : [[1691152740000, 259.6, 259.97, 259.43, 259.49, 47], [1691152800000, 259.38, 259.94, 259.17, 259.56, 58], [1691152860000, 259.62, 260.34, 259.62, 260.19, 42]
get_deviations功能将返回价格偏差
ticker = [ "TSLA" , "AAPL" , "GOOG" ]
deviations = cfd . get_deviations ( instruments = ticker )
print ( deviations )
[{ ' request ' : { ' ticker ' : ' TSLA ' , ' useAskPrice ' : False}, ' response ' : { ' timestamp ' : 1691136010000, ' price ' : 259.38, ' period ' : ' d1 ' }}, { ' request ' : { ' ticker ' : ' AAPL ' , ' useAskPrice ' : False}, ' response ' : { ' timestamp ' : 1691136010000, ' price ' : 188.99, ' period ' : ' d1 ' }}, { ' request ' : { ' ticker ' : ' GOOG ' , ' useAskPrice ' : False}, ' response ' : { ' timestamp ' : 1691136010000, ' price ' : 129.05, ' period ' : ' d1 ' }}]
GET_COMPANIES功能将返回当前在T212及其各自ISIN ID上列出的公司。
companies = cfd . get_companies ()
print ( companies )
[{ ' ticker ' : ' SIGTl_EQ ' , ' isin ' : ' GB0008769993 ' }, { ' ticker ' : ' PDYPY_US_EQ ' , ' isin ' : ' US3440441026 ' }...]
limit_order函数提交限制顺序,并获取数量,target_price,take_profit&stop_loss parms。
limit_order = cfd . limit_order ( instrument = "TSLA" ,
quantity = 5 , target_price = 129 , take_profit = 130 , stop_loss = 128 )
{'account': {'dealer': 'AVUSUK', 'positions': [{'positionId': '********-****-****-****-************',
'humanId': '**********', 'created': '2023-07-03T18:17:46.563+03:00' ...
Market_order功能提交市场订单,并采用数量,target_price,take_profit&stop_loss parms。
market_order = cfd . market_order ( instrument = "TSLA" ,
quantity = 5 , target_price = 129 , take_profit = 130 , stop_loss = 128 )
CANCEL_ORDER功能将取消需要订购的待处理订单。
cancel_order = cfd . cancel_order ( order_id )
您还可以使用cancel_all_orders取消所有待定限制订单。
cancel_all = cfd . cancel_all_orders ()
CLOSS_POINTION功能将提交请求以取消打开位置。
close_position = cfd . close_position ( position_id = 'ordexxxxx' , current_price = current_price )
username = "[email protected]"
password = "password132"
api = Apit212 ()
api . setup ( username = username , password = password , mode = "demo" )
cfd = CFD ( cred = api )
target_price = 128
while True :
sleep ( 60 )
price = cfd . fast_price ( "TSLA" )
if price <= target_price :
marketOrder = cfd . market_order ( instrument = "TSLA" , target_price = price , quantity = 1 , take_profit = 10 ,
stop_loss = 10 )
break
在进行交易时,您可能会遇到问题,并且在出现这些问题的情况下制定协议总是很好。
以下是您在进行交易时可能会遇到的一些例外列表。
如果您得到此回复,请停止提出请求
目前,这仅使用股票帐户,您只能在演示帐户上提交交易。请阅读正式文档,以更好地了解API。
为了使用官方API,您需要使用Trading212应用程序生成密钥。 /settings/api(beta)然后简单地生成一个新键,然后将其传递给apitkey()。equity()类。
from apit212 import *
key = "20557******************************"
client = Apitkey ()
info = client . Equity ( api_key = key , mode = "live" )
这是使用Trading212 API-Token可用的功能。
这是一个非正式的API,交易本人要么是负责使用此API的API。强烈建议您在转移到真钱之前使用练习帐户。 APIT212不是交易机器人