これは、Seleniumを使用したPyhtonベースのAPIであり、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' ))
読み抜けるデータはかなりありますが、あなたが残しているキーはティッカーです。
[{ ' 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つの結果を返すことがよくありますが、場合によっては複数の結果が得られる場合があるため、弦のレンを確認するための良い練習が返されます。
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_instruments_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関数は、すべての取引結果のリストを返します。各ページをリクエストする必要があります。また、TimeZoneを通過する必要がある場合があります。
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関数は、すべての渡された機器の最後のQOUTED価格を返します。
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関数を使用すると、既存の郵便配置にストップロスまたはテイクプロビットを変更または追加できます(この機能を実行するには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 )
close_position関数は、開いた位置を閉じるために使用されます。現在の価格が必要になります。
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 ' : []}}}
Trailing_Stop関数を使用すると、トレーリングストップを開いた位置に追加できます。
trailing_stop = cfd . trailing_stop ( position_id = "***-****-***" , distance = 0.5 )
add_limits関数を使用すると、既存のポジションにストップロスとテイクプロビットを追加できます。
update_limits = client . add_limits ( position_id = "***-****-***" , TP = 1 , SL = 1 )
新しいストップロスまたはテイクプロビットを設定するには、TP(利益を取る)またはSL(停止損失)パラメーションまでの距離を渡すだけです。関数は現在の価格を取得し、距離を適用します。
all_position_hist関数は、位置履歴を返します。
position_history = cfd . all_position_hist ()
all_order_histは注文データを返します
order_history = cfd . all_order_hist ()
get_instrument関数は、機器に関する情報をrecunrします。
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を取得するためにも使用できます。
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関数は、渡された機器の現在のASK価格を返します。
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関数は、フロートとして最後のQoutedチャート価格を返します
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関数は制限順序を送信し、数量、ターゲット_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 ()
close_position関数は、オープンポジションをキャンセルするリクエストを送信します。
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() classに渡すだけです。
from apit212 import *
key = "20557******************************"
client = Apitkey ()
info = client . Equity ( api_key = key , mode = "live" )
Trading212 API-Tokenを使用して、利用可能な関数は次のとおりです。
これは非公式のAPIであり、Trading212の自分自身がこのAPIの使用を担当しています。実際のお金に移る前に、練習アカウントを使用することを強くお勧めします。 APIT212は取引ボットではありません