Package: apit212
Apit212This is a Pyhton based API using selenium and requests to get information from the trading212 Platform, please note that either myself or trading212 take responsibility for the outcomes related to the uses of this API.I will continue to work on this project and would appriciate any feedback.RequirmentsSeleniumRequestsPython3FirefoxInstallationpip install apit212Importto start using this API you will first need to login to the account usingapit212you will then be able to use all the functions and create your own trading bot or use it to scarpe data from the trading212 platform.Demo account:fromapit212import*api=Apit212()api.setup(username="flock92@account.api",password="pass******",mode="demo")Live account:fromapit212import*api=Apit212()api.setup(username="flock92@account.api",password="pass******",mode="live")Best PracticeIt's good practice to set up an env file to save sensitive informaton like your user name or password.Here is a useful link.envUSER=flock92@account.api
PASS=password123fromdotenvimportload_dotenvfromapit212import*importosload_dotenv('.env')username:str=os.getenv('USER')password:str=os.getenv('PASS')api=Apit212()api.setup(username="flock92@account.api",password="pass******",mode="demo")Correct TickerThis API is useless without the correct ticker symbol so i've got a solution.fromapit212importTickersticker=Tickers()print(ticker.fetch_symbols(symbol='META'))print(ticker.find_by_name(full_name='tesla'))consoleThere is quite a bit of data to read through but the key you are after istickerthis will return the symbol used by the trading212 platform.[{'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}]examplefromapit212importTickersticker=Tickers()meta=ticker.fetch_symbols(symbol='META')print(len(meta))print(meta[0]['ticker'])consolefinding a ticker using the widely used ticker will often return 1 result but on some occasions you may get multiple results
so its good practice to check the len of the string returned.1FBCFD or Trade EquityTo trade CFD's simply call the CFD classfromapit212import*api=Apit212()api.setup(username="flock92@account.api",password="pass******",mode="demo")cfd=CFD(cred=api)To trade Equity's simply call the Equity class.fromapit212import*client=Apit212(username="flock92@account.api",password="pass******",mode="live")equity=Equity()Account dataCheck sessionTheauth_validatefunction will return account ID and trade type.validate=cfd.auth_validate()print(validate)Console:{'id':'*******-****-****-****-************','accountId':********,'customerId':*********,'tradingType':'CFD','customerUuid':'********-****-****-****-************','frontend':'WC4','readyToTrade':True,'deviceUuid':''}get_accountTheget_accountfunction will return your account details.account=cfd.get_account()print(account)Console{'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_fundsTheget_fundsfunction will return the accounts funds.funds=cfd.get_funds()print(funds)Console{'*******':{'accountId':********,'tradingType':'CFD','currency':'GBP','freeForWithdraw':486.83,'freeForCfdTransfer':0,'total':486.83,'lockedCash':{'totalLockedCash':0,'lockedCash':[]}}}Get summaryTheget_summaryreturns a summary of you account.summary=cfd.get_summary()print(summary)Console'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 companiesTheget_companiesreturns instruments avaliable to trade on the trading212 platformcompanies=cfd.get_companies()print(companies)Console[{'ticker':'SIGTl_EQ','isin':'GB0008769993'},{'ticker':'PDYPY_US_EQ','isin':'US3440441026'}...]Get instrument infoTheget_instruments_infowill return information about an instrument.info=cfd.get_instruments_info(instrument="TSLA")print(info)Console{'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 infoTheget_order_infogetorderInfo=cfd.get_order_info(instrument="TSLA",quamtity=1.5)print(orderInfo)Console{'buyMargin':40.18,'sellMargin':40.18,'buySwap':-0.2,'sellSwap':-0.05}Get deviationtickers=["TSLA","AAPL"]deviation=cfd.get_deviations(instruments=tickers)print(deviation)Console[{'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 positionTheget_positionreturns infomation for a given position ID, this ID's can be exstracted from the get_summary functionposition=cfd.get_position(position_id=274187113)print(position)Console[{'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 resultsTheget_all_resultfunction will return a list of all your trading results. you will need to request each page. you may also need to pass your timezone.results=cfd.get_all_results()print(results)Console{'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}Get order HistoryorderHist=cfd.get_order_hist(page_number=1)print(orderHist)Console{'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}Get position HistorypositionHist=cfd.get_posistion_hist(page_number=1)print(positionHist)Console{'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 priceThefast_priceretruns an instruments price as a float. if the request fails None is returnedprice=cfd.fast_price(instrument="TSLA")print(price)console253.49Chart dataThechart_datareturns a dictionary with the candle date OHLC (open, high, low, close) the period requested. which is set to 1minute by default.charts=cfd.chart_data(instrument="TSLA",period="ONE_MINUTE")print(charts)Console[{'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 multiple price dataThemulti_pricefunction will return the last qouted price for all passed instruments.tickers=["TSLA","AAPL","GOOG"]multiprice=cfd.multi_price(instruments=tickers)print(multiprice)Console[{'ticker':'TSLA','price':251.34},{'ticker':'AAPL','price':181.96},{'ticker':'GOOG','price':135.18}]TRADESMarket orderThemarket_orderfunction submits a market order and requires the current price of the instrument.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 orderThelimit_orderfunction submits a limit ordermarketOrder=cfd.limit_order(instrument="TSLA",target_price=127,quantity=1.5,take_profit=10,stop_loss=10)Set limitsTheset_limitsfunction allows you to modify or add a stoploss or takeprofit to an existing postion (the positionID is required to carry out this function)limits=cfd.set_limits(position_id=27361748,TP=10,SL=10)add trailing stopTheadd_trailing_stopfunction adds a trailing stop to an existing positiontrailing=cfd.add_trailing_stop(position_id=27361748,distance=1)close positionTheclose_positionfunction is used to close an open position. it will required the current price.currentPrice=cfd.fast_price(instrument="TSLA")close=cfd.close_position(position_id=23948174,current_price=currentPrice)cancel all orderscancelAll=cfd.cancel_all_orders()cancel orderThecancel_orderfunction is used to cancel a limit order.cancel=cfd.cancel_order(order_id=**********)Get ticker pricetheget_livefunction will return the current price of a tickertickers=["TSLA","AAPL"]prices=cfd.live_price(instruments=tickers)print(prices)Console:[{'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 FundsTheget_fundsfunction will return your accounts funds.funds=cfd.get_funds()print(funds)Console:{'20434246':{'accountId':********,'tradingType':'CFD','currency':'GBP','freeForWithdraw':486.83,'freeForCfdTransfer':0,'total':486.83,'lockedCash':{'totalLockedCash':0,'lockedCash':[]}}}Add trailing stop lossthetrailing_stopfunction allows you to add a trailing stop to a open position.trailing_stop=cfd.trailing_stop(position_id="***-****-***",distance=0.5)Add/Change stoploss and takeprofitTheadd_limitsfunction allows you to add a stoploss and takeprofit to an existing position.update_limits=client.add_limits(position_id="***-****-***",TP=1,SL=1)To set a new stoploss or takeprofit just pass the distance to the TP (take profit) or SL (stop loss) params. The function will get the current price and apply the distance.Get all position historyTheall_position_histfunction will return the position history.position_history=cfd.all_position_hist()Get order historyTheall_order_histreturns orders dataorder_history=cfd.all_order_hist()Get Insturments infoTheget_instrumentfunction will retunr information about the instrument.tsla_info=cfd.get_instruments_info(instrument='TSLA')print(tsla_info)Console:{'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 informationTheget_positionfunction will returns information for the qouted positionID.position=cfd.get_position(position_id="***-****-***")print(position)console[{'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 SummaryTheget_summaryfunction will return the account summary. this function can also be used to get order ID's and there current PPLsummary=cfd.get_summary()print(summary)Example:'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 live PriceThelive_pricefunction will return the current ask price for the passed instrument.ticker=["TSLA","AAPL","GOOG"]live_price=cfd.live_price(instruments=ticker)print(live_price)console:[{'ticker':'TSLA','price':253.49},{'ticker':'AAPL','price':182.08},{'ticker':'GOOG','price':128.44}]Get fast priceThefast_pricefunction will return the last qouted chart price as a floatprice=cfd.fast_price(instrument="TSLA")print(price)console:253.49Get chart datathechart_datafunction will return the lastest chart data for passed instrumentchart=cfd.chart_data(instrument="TSLA")print(chart)console:[{'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 price deviationsTheget_deviationsfunction will return price deviationsticker=["TSLA","AAPL","GOOG"]deviations=cfd.get_deviations(instruments=ticker)print(deviations)console:[{'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 CompaniesTheget_companiesfunction will return companies currently listed on T212 & their respective isin ID.companies=cfd.get_companies()print(companies)console:[{'ticker':'SIGTl_EQ','isin':'GB0008769993'},{'ticker':'PDYPY_US_EQ','isin':'US3440441026'}...]Limit OrderThelimit_orderfunction submit a limit order and takes quantity, 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)Console:{'account': {'dealer': 'AVUSUK', 'positions': [{'positionId': '********-****-****-****-************',
'humanId': '**********', 'created': '2023-07-03T18:17:46.563+03:00' ...Market OrderThemarket_orderfunction submit a market order and takes quantity, 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 orderThecancel_orderfunction will cancel a pending order it requires a orderID.cancel_order=cfd.cancel_order(order_id)You can also use thecancel_all_ordersto cancel all pending limits orders.cancel_all=cfd.cancel_all_orders()Close PositionTheclose_positionfunction will submit a request to cancel a open position.close_position=cfd.close_position(position_id='ordexxxxx',current_price=current_price)CODE EXAMPLESusername="flock92@account.api"password="password132"api=Apit212()api.setup(username=username,password=password,mode="demo")cfd=CFD(cred=api)target_price=128whileTrue:sleep(60)price=cfd.fast_price("TSLA")ifprice<=target_price:marketOrder=cfd.market_order(instrument="TSLA",target_price=price,quantity=1,take_profit=10,stop_loss=10)breakTrade ExceptionsWhen carrying out a trade you might run into issues and it's always good to have protocols in place to deal with these issues when they arise.below is a list ofsomeexceptions you might come across when carrying out a trade.BusinessExceptionMinQuantityExceededNoPriceExceptionInstrumentNotSupportedSpreadIsBiggerThanMinDistanceInstrumentDisabledStopLossMustBeBelowCurrentPriceInsufficientFundsMaxBuyInsufficientFundsMaxSellMarketStillNotOpenQuantityPrecisionMismatchInternalErrorJust stop making the request if you get this responseUsing trading212 official APIThis is currently only working with equity accounts and you can only submit trades on your demo account. please read the official documentation to get a better understanding and limitations of the API.SetupIn order to use the official API you will need to generate a key using the trading212 app. /settings/API(Beta) then simply generate a new Key and pass it to theApitkey().Equity()Class.fromapit212import*key="20557******************************"client=Apitkey()info=client.Equity(api_key=key,mode="live")FunctionsHere are the functions avalible using the trading212 API-token.exchange_listinstrument_listpiescreate_piedelete_piefetch_pieupdate_pieequity_orderslimit_ordermarket_orderstop_oderstop_limit_ordercancel_orderfetch_orderaccount_dataaccount_metafetch_all_posistionsfetch_positionorder_historypaid_out_dividendsexport_listexport_csvtransactionsDisclaimerThis is an unofficial API & either myself of trading212 are responsible for the use of this API. It is strongly advised that you use a practice account before moving onto real money.apit212 isnota trading bot