pyjuque开源项目

我要开发同款
匿名用户2021年11月08日
32阅读
开发技术Python
所属分类应用工具、IM/聊天/语音工具
授权协议MIT License

作品详情

PythonJujuQuantEngine

PYJUQUE  (pai-jook)(Py-thonJu-juQu-antE-ngine)

Thisprojectimplementsthebasicfunctionalityrequiredtoengageinalgorithmictrading.Itcanberegardedasastartingpointformorecomplextradingbots.

Installation

Makesureyouhavepipinstalled.Run:

pipinstallpyjuque

Youshouldbegoodtogo!Checkouttheexamplesection.

GettingStarted

Checkouttheseexamplestogetstartedstratghtaway:strategy1,strategy2.Belowisthesimplestexampleofhowtogetstartedwithpyjuque.Readthenextsectiontounderstandthethinkingbehindit.

frompyjuque.BotimportdefineBotimporttimedefcustomEntryStrategy(bot_controller,symbol):#signal=will_moon(symbol)#bool#last_price=get_price(symbol)#floatreturnsignal,last_price##Definestheoverallconfigurationofthebotbot_config={'name':'my_bot','test_run':False#settoTruetoruninsimulationmode'exchange':{'name':'binance','params':{#puthereanyparamthatccxtaccepts'api_key':'YOUR_API_KEY','secret':'YOUR_API_SECRET'},},'symbols':['LINK/BTC','ETH/BTC'],#!!allsymbolsmusttradeagainstsamecoin#!!IE:[XX/BTC,YY/BTC]OR[AA/EUR,CC/EUR]'starting_balance':0.0005,#denominatedinthequoteassetagainstwhich#thesymbolsaretrading(BTCinthiscase)'strategy':{'custom':True,'entry_function':customEntryStrategy,},'entry_settings':{'initial_entry_allocation':100,#100%ofstarting_balancegoesineverytrade'signal_distance':0.3#uponreceivinganentry_signal,entryorder#isplaced0.3%awayfrommarketprice},'exit_settings':{'take_profit':3,#takeprofit3%aboveentryorders'stop_loss_value':10#stoploss10%belowentryorders},}##Runsthebotinaninfiniteloopthatexecutesevery60seconds##stoppablefromtheterminalwithCTRL+CdefMain():bot_controller=defineBot(bot_config)whileTrue:try:bot_controller.executeBot()exceptKeyboardInterrupt:returntime.sleep(60)if__name__=='__main__':Main()RunaSimpleBot

Theideabehindthislibraryistoallowyoutoimplementwhatevertradingstrategyyouwant,withouthavingtoworryabouthowtoconnecttothedifferentexchangesviaapis,orhowtoplace,cancelandkeeptrackoforders.Yousimplyprovidethesignalsandpyjuquedoestherest.

Thereareanumberofsettingsthatyoudefine,likewhatsymbolstotradeon,howmuchmoneytoplacepertradeandwhatexchangetouse.Youalsogettosetexitsettingssuchasatakeprofitvalueandastoplossvalue.Allthesesettingsgetspecifiedinaconfigdict.Belowisacompleteexampleofaconfigdict:

##Definestheoverallconfigurationofthebotbot_config={#Nameofthebot,asstoredinthedatabase'name':'my_bot',#exchangeinformation(fillwithyourapikeyandsecret)'exchange':{'name':'binance',#or'okex''params':{#anyparameteracceptedbyccxtcangohere'api_key':'your_api_key_here','secret':'your_secret_here',#'password':'your_password_here'#ifusing'okex'},},#startingbalanceforbot'starting_balance':0.0005,#symbolstotradeon#!IMPORTANT!allsymbolsmusttradeagainstthesamecoin#!!IE:[AAA/BTC,BBB/BTC]OR[AAA/USDT,CCC/USDT]'symbols':['LINK/BTC','ETH/BTC'],#strategyclass/function(herewedefinetheentryandexitstrategies.)#thisbotplacesanentryorderwhen'customEntryFunction'retrunstrue'strategy':{'custom':True,'entry_function':customEntryFunction},#whenthebotreceivesthebuysignal,theorderisplacedaccording#tothesettingsspecifiedbelow'entry_settings':{#between0and100,the%ofthestarting_balancetoputinanorder'initial_entry_allocation':100,#numberbetween0and100-1%meansthatwhenwegetabuysignal,#weplacebuyorder1%belowcurrentprice.if0,weplaceamarket#orderimmediatelyuponreceivingsignal'signal_distance':0.3},#Thisbotexitswhenourfilledordershavereachedatake_profit%above#thebuyprice,orastop_loss_value%belowit'exit_settings':{#takeprofitvaluebetween0andinfinity,3%meansweplaceoursell#orders3%abovethepricesthatourbuyordersfilledat'take_profit':3,#stoplossvalueinpercent-10%meansstoplossat10%belowour#buyorder'sfilledprice'stop_loss_value':10},}

Besidesthesesettings,youneedtoprovideanentrystrategy.Itcanbeassimpleasafunction,oramorecomplexstrategyclass.We'llgooverthesimpleexample:

#Thisisoursignalfunction.#Itreceivestwoparameters-thebot_controller,#whichgivesusaccesstotheexchangeandtothe#database,andthesymbolonwhichthebotis#currentlycheckingentrysignals.##Itmustreturntwovalues,abooleanandanumber.#Thebooleanisthesignal,andthenumberisthe#latestpriceofthatsymbol#defcustomEntryFunction(bot_controller,symbol):#...dosomestuffhere...returnsignal,last_price_of_symbol

Thebeautyofthisisthatyoucandowhatevertheheckyouwantinthatcustomentryfunction,becauseaslongasyoureturnasymbolandthelatestprice,pyjuquewillbehappy.Youcancheckcoinspricesandtheirindicators,thevolumeonmultipleexchanges,differentorderbooks,evenweatherdata,twitterfeedsorastronomicalevents.

Here'sacompleteexampleofhowtogetstartedwithpyjuque:

frompyjuque.BotimportdefineBot##Thisisoursignalfunctionfornow.defcustomEntryFunction(bot_controller,symbol):#...dosomestuffhere...returnsignal,last_price##Definestheoverallconfigurationofthebotbot_config={...}##Runsthebotinaninfiniteloop,stoppable##fromtheterminalwithCTRL+CdefMain():bot_controller=defineBot(bot_config)whileTrue:try:bot_controller.executeBot()exceptKeyboardInterrupt:returntime.sleep(60)if__name__=='__main__':Main()

Uponcreatingthebot,adatabasewillbecreatedinyourcomputer,keepingtrackofordersplaced.Youcanrunthisexampleanditwillwork-butyoushouldupdatecustomEntryFunctiontodosomecalculations&returntruesometimes,becauseinitscurrentstatethebotwon'tevermakeanytrades.

Checkouttheseexamplesformoreinfo:strategy1,strategy2.

FeaturesCurrentFeatures:LongBot(PlacingBuyOrdersonCustomSignals)Market,Limit&StopLossOrdersAutomaticallyPlacingExitOrderwhenEntryOrderwasfulfilledStatePersistance,thebotstorestradeslocallyBinanceLocalOrderBookPlottingCapabilitiesSimpleDefiinitianofEntryStrategy&ExitRules(viabot_config)StatePersistenceUsingSQLAlchemy,foranyflavourofSQLInDevelopment:GridBotFutureFeatures:ShortBotOCOordersSellingonsignalsTrailingStopLossMultipleEntriesModules

Thislibraryimplementsthefollowingmodules:

BotController

Atpyjuque/Engine/BotController.py.

Amodulewhichhandlesthebuyingandsellingofassets,givensimpleormoreadvancedrules,allowingustorunastrategyindefinitely.

Throughthebotcontrolleryoucanaccessthefollowingobjects

bot_controller.exchangebot_controller.exchangehassomemethodsthatareusedunderthehoodbypyjquue,likegetOHLCVplaceLimitOrderplaceMarketOrderetcbot_controller.exchange.ccxt,accxtobjectwhichusesthecredentialsyouprovidedinthebot_configbot_controller.session,SQLAlchemysessionthroughwhichyoucanquerythedatabasebot_controller.botmodel,themodelofthebotasstoredinthedbbot_controller.status_printer,ayaspinspinnerusedforlogging

Youcanalsoaccessthefollowingfunctions

bot_controller.executeBot(),whichgoesthroughabotloopof:checkingsignalsonsymbolsandplacingordersifsignalsaretruecheckingallopenordersplacedbythebotandupdatingthem,likeso:ifabuyorderwasfilleditplacesthesubsequentexitorder,atatake_profitpriceabovethebuypriceifthecurrentpriceisbelowstop_loss_valueforanopenbuyorder,exitsusingmarketpricebot_controller.log()whichallowsyoutoprintsomestufftotheterminalbot_controller.bot_model.getOrders(bot_controller.session)whichallowsyoutogetallordersbot_controller.bot_model.getOpenOrders(bot_controller.session)whichallowsyoutogetallopenordersExchangeConnectors

Implementingmultipleexchangeswithccxt.CheckoutimplementationatCcxtExchange.Currentlyimplemented:

binanceokex

Older(Deprecated):

Atpyjuque/Exchanges.

Binance-basedontheofficialRESTAPILocalOrderBook(forBinance)

Atpyjuque/Exchanges/BinanceOrderBook.py.

Createsandstoresalocalorderbookforthespecifiedsymbols.OrderBookisupdatedeverysecondthroughawebsocketconnectiontotheExchange(currentlyBinance).Checkoutthisexample.

frompyjuque.Exchanges.BinanceOrderBookimportOrderBook#Initialize&startOrderBookwithdesiredsymbolsob=OrderBook(symbols=['BTC/USDT','LTC/USDT'])ob.startOrderBook()...#GetUpdatedOrderBookdataatanypointinyourcodeordb=ob.getOrderBook()print(ordb){'BTC/USDT':{'asks':[['13662.31000000','3.24473100'],['13662.82000000','0.06815300'],['13663.08000000','0.00900000'],...['20000.00000000','95.22325900']],'bids':[['13662.30000000','1.26362900'],['13661.78000000','0.04395000'],['13661.62000000','0.01439200'],...['10188.00000000','1.11546400']],'lastUpdateId':6382686192#ignorethis},'LTC/USDT':{'asks':[...],'bids':[...],'lastUpdateId':1521585540#ignorethis},'counter':11#ignorethis}ComingSoonMoreExchanges

BinanceFutures,Bitmex,Bitfinex,FTX,Bybit.MarginTrading,MarketMaking,HyperParameterTuning.

Contributing

Tocontributesimplyforktherepo,writeyourdesiredfeatureinyourownforkandmakeapullrequestuponfinishing.Writingtestsisalsoappreciated.

声明:本文仅代表作者观点,不代表本站立场。如果侵犯到您的合法权益,请联系我们删除侵权资源!如果遇到资源链接失效,请您通过评论或工单的方式通知管理员。未经允许,不得转载,本站所有资源文章禁止商业使用运营!
下载安装【程序员客栈】APP
实时对接需求、及时收发消息、丰富的开放项目需求、随时随地查看项目状态

评论