PYJUQUE (pai-jook)(Py-thonJu-juQu-antE-ngine)
Thisprojectimplementsthebasicfunctionalityrequiredtoengageinalgorithmictrading.Itcanberegardedasastartingpointformorecomplextradingbots.
InstallationMakesureyouhavepipinstalled.Run:
pipinstallpyjuqueYoushouldbegoodtogo!Checkouttheexamplesection.
GettingStartedCheckouttheseexamplestogetstartedstratghtaway: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()RunaSimpleBotTheideabehindthislibraryistoallowyoutoimplementwhatevertradingstrategyyouwant,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_symbolThebeautyofthisisthatyoucandowhatevertheheckyouwantinthatcustomentryfunction,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:ShortBotOCOordersSellingonsignalsTrailingStopLossMultipleEntriesModulesThislibraryimplementsthefollowingmodules:
BotControllerAtpyjuque/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,ayaspinspinnerusedforloggingYoucanalsoaccessthefollowingfunctions
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)whichallowsyoutogetallopenordersExchangeConnectorsImplementingmultipleexchangeswithccxt.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}ComingSoonMoreExchangesBinanceFutures,Bitmex,Bitfinex,FTX,Bybit.MarginTrading,MarketMaking,HyperParameterTuning.
ContributingTocontributesimplyforktherepo,writeyourdesiredfeatureinyourownforkandmakeapullrequestuponfinishing.Writingtestsisalsoappreciated.
评论