Best JavaScript code snippet using wpt
ctaEngine.py
Source:ctaEngine.py
1# encoding: UTF-82'''3æ¬æ件ä¸å®ç°äºCTAçç¥å¼æï¼é对CTAç±»åççç¥ï¼æ½è±¡ç®åäºé¨ååºå±æ¥å£çåè½ã4'''5from __future__ import division6import json7import os8import traceback9from collections import OrderedDict10from datetime import datetime, timedelta11from copy import copy12from vnpy.event import Event13from vnpy.trader.vtEvent import *14from vnpy.trader.vtConstant import *15from vnpy.trader.vtObject import VtTickData, VtBarData16from vnpy.trader.vtGateway import VtSubscribeReq, VtOrderReq, VtCancelOrderReq, VtLogData17from vnpy.trader.vtFunction import todayDate, getJsonPath18from .ctaBase import *19from .strategy import STRATEGY_CLASS20########################################################################21class CtaEngine(object):22 """CTAçç¥å¼æ"""23 settingFileName = 'CTA_setting.json'24 settingfilePath = getJsonPath(settingFileName, __file__)25 26 STATUS_FINISHED = set([STATUS_REJECTED, STATUS_CANCELLED, STATUS_ALLTRADED])27 #----------------------------------------------------------------------28 def __init__(self, mainEngine, eventEngine):29 """Constructor"""30 self.mainEngine = mainEngine31 self.eventEngine = eventEngine32 33 # å½åæ¥æ34 self.today = todayDate()35 36 # ä¿åçç¥å®ä¾çåå
¸37 # key为çç¥å称ï¼value为çç¥å®ä¾ï¼æ³¨æçç¥å称ä¸å
许éå¤38 self.strategyDict = {}39 40 # ä¿åvtSymbolåçç¥å®ä¾æ å°çåå
¸ï¼ç¨äºæ¨étickæ°æ®ï¼41 # ç±äºå¯è½å¤ä¸ªstrategy交æåä¸ä¸ªvtSymbolï¼å æ¤key为vtSymbol42 # value为å
å«ææç¸å
³strategy对象çlist43 self.tickStrategyDict = {}44 45 # ä¿åvtOrderIDåstrategy对象æ å°çåå
¸ï¼ç¨äºæ¨éorderåtradeæ°æ®ï¼46 # key为vtOrderIDï¼value为strategy对象47 self.orderStrategyDict = {} 48 49 # æ¬å°åæ¢åç¼å·è®¡æ°50 self.stopOrderCount = 051 # stopOrderID = STOPORDERPREFIX + str(stopOrderCount)52 53 # æ¬å°åæ¢ååå
¸54 # key为stopOrderIDï¼value为stopOrder对象55 self.stopOrderDict = {} # åæ¢åæ¤éåä¸ä¼ä»æ¬åå
¸ä¸å é¤56 self.workingStopOrderDict = {} # åæ¢åæ¤éåä¼ä»æ¬åå
¸ä¸å é¤57 58 # ä¿åçç¥å称åå§æå·å表çåå
¸59 # key为nameï¼value为ä¿åorderIDï¼éä»·+æ¬å°åæ¢ï¼çéå60 self.strategyOrderDict = {}61 62 # æ交å·éåï¼ç¨æ¥è¿æ»¤å·²ç»æ¶å°è¿çæ交æ¨é63 self.tradeSet = set()64 65 # å¼æç±»å为å®ç66 self.engineType = ENGINETYPE_TRADING67 68 # 注åæ¥å¼äºä»¶ç±»å69 self.mainEngine.registerLogEvent(EVENT_CTA_LOG)70 71 # 注åäºä»¶çå¬72 self.registerEvent()73 74 #----------------------------------------------------------------------75 def sendOrder(self, vtSymbol, orderType, price, volume, strategy):76 """åå"""77 contract = self.mainEngine.getContract(vtSymbol)78 79 req = VtOrderReq()80 req.symbol = contract.symbol81 req.exchange = contract.exchange82 req.vtSymbol = contract.vtSymbol83 req.price = self.roundToPriceTick(contract.priceTick, price)84 req.volume = volume85 86 req.productClass = strategy.productClass87 req.currency = strategy.currency 88 89 # 设计为CTAå¼æååºçå§æåªå
许使ç¨éä»·å90 req.priceType = PRICETYPE_LIMITPRICE 91 92 # CTAå§æç±»åæ å°93 if orderType == CTAORDER_BUY:94 req.direction = DIRECTION_LONG95 req.offset = OFFSET_OPEN96 97 elif orderType == CTAORDER_SELL:98 req.direction = DIRECTION_SHORT99 req.offset = OFFSET_CLOSE100 101 elif orderType == CTAORDER_SHORT:102 req.direction = DIRECTION_SHORT103 req.offset = OFFSET_OPEN104 105 elif orderType == CTAORDER_COVER:106 req.direction = DIRECTION_LONG107 req.offset = OFFSET_CLOSE108 109 # å§æ转æ¢110 reqList = self.mainEngine.convertOrderReq(req)111 vtOrderIDList = []112 113 if not reqList:114 return vtOrderIDList115 116 for convertedReq in reqList:117 vtOrderID = self.mainEngine.sendOrder(convertedReq, contract.gatewayName) # åå118 self.orderStrategyDict[vtOrderID] = strategy # ä¿åvtOrderIDåçç¥çæ å°å
³ç³»119 self.strategyOrderDict[strategy.name].add(vtOrderID) # æ·»å å°çç¥å§æå·éåä¸120 vtOrderIDList.append(vtOrderID)121 122 self.writeCtaLog(u'çç¥%såéå§æï¼%sï¼%sï¼%s@%s' 123 %(strategy.name, vtSymbol, req.direction, volume, price))124 125 return vtOrderIDList126 127 #----------------------------------------------------------------------128 def cancelOrder(self, vtOrderID):129 """æ¤å"""130 # æ¥è¯¢æ¥å对象131 order = self.mainEngine.getOrder(vtOrderID)132 133 # å¦ææ¥è¯¢æå134 if order:135 # æ£æ¥æ¯å¦æ¥åè¿ææï¼åªææææ¶æååºæ¤åæ令136 orderFinished = (order.status==STATUS_ALLTRADED or order.status==STATUS_CANCELLED)137 if not orderFinished:138 req = VtCancelOrderReq()139 req.symbol = order.symbol140 req.exchange = order.exchange141 req.frontID = order.frontID142 req.sessionID = order.sessionID143 req.orderID = order.orderID144 self.mainEngine.cancelOrder(req, order.gatewayName) 145 #----------------------------------------------------------------------146 def sendStopOrder(self, vtSymbol, orderType, price, volume, strategy):147 """ååæ¢åï¼æ¬å°å®ç°ï¼"""148 self.stopOrderCount += 1149 stopOrderID = STOPORDERPREFIX + str(self.stopOrderCount)150 151 so = StopOrder()152 so.vtSymbol = vtSymbol153 so.orderType = orderType154 so.price = price155 so.volume = volume156 so.strategy = strategy157 so.stopOrderID = stopOrderID158 so.status = STOPORDER_WAITING159 160 if orderType == CTAORDER_BUY:161 so.direction = DIRECTION_LONG162 so.offset = OFFSET_OPEN163 elif orderType == CTAORDER_SELL:164 so.direction = DIRECTION_SHORT165 so.offset = OFFSET_CLOSE166 elif orderType == CTAORDER_SHORT:167 so.direction = DIRECTION_SHORT168 so.offset = OFFSET_OPEN169 elif orderType == CTAORDER_COVER:170 so.direction = DIRECTION_LONG171 so.offset = OFFSET_CLOSE 172 173 # ä¿åstopOrder对象å°åå
¸ä¸174 self.stopOrderDict[stopOrderID] = so175 self.workingStopOrderDict[stopOrderID] = so176 177 # ä¿åstopOrderIDå°çç¥å§æå·éåä¸178 self.strategyOrderDict[strategy.name].add(stopOrderID)179 180 # æ¨éåæ¢åç¶æ181 strategy.onStopOrder(so)182 183 return [stopOrderID]184 185 #----------------------------------------------------------------------186 def cancelStopOrder(self, stopOrderID):187 """æ¤éåæ¢å"""188 # æ£æ¥åæ¢åæ¯å¦åå¨189 if stopOrderID in self.workingStopOrderDict:190 so = self.workingStopOrderDict[stopOrderID]191 strategy = so.strategy192 193 # æ´æ¹åæ¢åç¶æ为已æ¤é194 so.status = STOPORDER_CANCELLED195 196 # ä»æ´»å¨åæ¢ååå
¸ä¸ç§»é¤197 del self.workingStopOrderDict[stopOrderID]198 199 # ä»çç¥å§æå·éåä¸ç§»é¤200 s = self.strategyOrderDict[strategy.name]201 if stopOrderID in s:202 s.remove(stopOrderID)203 204 # éç¥çç¥205 strategy.onStopOrder(so)206 #----------------------------------------------------------------------207 def processStopOrder(self, tick):208 """æ¶å°è¡æ
åå¤çæ¬å°åæ¢åï¼æ£æ¥æ¯å¦è¦ç«å³ååºï¼"""209 vtSymbol = tick.vtSymbol210 211 # é¦å
æ£æ¥æ¯å¦æçç¥äº¤æ该å约212 if vtSymbol in self.tickStrategyDict:213 # éåçå¾
ä¸çåæ¢åï¼æ£æ¥æ¯å¦ä¼è¢«è§¦å214 for so in self.workingStopOrderDict.values():215 if so.vtSymbol == vtSymbol:216 longTriggered = so.direction==DIRECTION_LONG and tick.lastPrice>=so.price # å¤å¤´åæ¢å被触å217 shortTriggered = so.direction==DIRECTION_SHORT and tick.lastPrice<=so.price # 空头åæ¢å被触å218 219 if longTriggered or shortTriggered:220 # ä¹°å
¥åååºåå«ä»¥æ¶¨åè·åä»·ååï¼æ¨¡æå¸ä»·åï¼221 if so.direction==DIRECTION_LONG:222 price = tick.upperLimit223 else:224 price = tick.lowerLimit225 226 # ååºå¸ä»·å§æ227 self.sendOrder(so.vtSymbol, so.orderType, price, so.volume, so.strategy)228 229 # ä»æ´»å¨åæ¢ååå
¸ä¸ç§»é¤è¯¥åæ¢å230 del self.workingStopOrderDict[so.stopOrderID]231 232 # ä»çç¥å§æå·éåä¸ç§»é¤233 s = self.strategyOrderDict[so.strategy.name]234 if so.stopOrderID in s:235 s.remove(so.stopOrderID)236 237 # æ´æ°åæ¢åç¶æï¼å¹¶éç¥çç¥238 so.status = STOPORDER_TRIGGERED239 so.strategy.onStopOrder(so)240 #----------------------------------------------------------------------241 def processTickEvent(self, event):242 """å¤çè¡æ
æ¨é"""243 tick = event.dict_['data']244 245 tick = copy(tick)246 247 # æ¶å°tickè¡æ
åï¼å
å¤çæ¬å°åæ¢åï¼æ£æ¥æ¯å¦è¦ç«å³ååºï¼248 self.processStopOrder(tick)249 250 # æ¨étickå°å¯¹åºççç¥å®ä¾è¿è¡å¤ç251 if tick.vtSymbol in self.tickStrategyDict:252 # tickæ¶é´å¯è½åºç°å¼å¸¸æ°æ®ï¼ä½¿ç¨try...exceptå®ç°ææåè¿æ»¤253 try:254 # æ·»å datetimeå段255 if not tick.datetime:256 tick.datetime = datetime.strptime(' '.join([tick.date, tick.time]), '%Y%m%d %H:%M:%S.%f')257 except ValueError:258 self.writeCtaLog(traceback.format_exc())259 return260 261 # é个æ¨éå°çç¥å®ä¾ä¸262 l = self.tickStrategyDict[tick.vtSymbol]263 for strategy in l:264 self.callStrategyFunc(strategy, strategy.onTick, tick)265 266 #----------------------------------------------------------------------267 def processOrderEvent(self, event):268 """å¤çå§ææ¨é"""269 order = event.dict_['data']270 271 vtOrderID = order.vtOrderID272 273 if vtOrderID in self.orderStrategyDict:274 strategy = self.orderStrategyDict[vtOrderID] 275 276 # å¦æå§æå·²ç»å®æï¼æåãæ¤éãå
¨æï¼ï¼åä»æ´»å¨å§æéåä¸ç§»é¤277 if order.status in self.STATUS_FINISHED:278 s = self.strategyOrderDict[strategy.name]279 if vtOrderID in s:280 s.remove(vtOrderID)281 282 self.callStrategyFunc(strategy, strategy.onOrder, order)283 284 #----------------------------------------------------------------------285 def processTradeEvent(self, event):286 """å¤çæ交æ¨é"""287 trade = event.dict_['data']288 289 # è¿æ»¤å·²ç»æ¶å°è¿çæ交åæ¥290 if trade.vtTradeID in self.tradeSet:291 return292 self.tradeSet.add(trade.vtTradeID)293 294 # å°æ交æ¨éå°çç¥å¯¹è±¡ä¸295 if trade.vtOrderID in self.orderStrategyDict:296 strategy = self.orderStrategyDict[trade.vtOrderID]297 298 # 计ç®çç¥æä»299 if trade.direction == DIRECTION_LONG:300 strategy.pos += trade.volume301 else:302 strategy.pos -= trade.volume303 304 self.callStrategyFunc(strategy, strategy.onTrade, trade)305 306 # ä¿åçç¥æä»å°æ°æ®åº307 self.saveSyncData(strategy) 308 309 #----------------------------------------------------------------------310 def registerEvent(self):311 """注åäºä»¶çå¬"""312 self.eventEngine.register(EVENT_TICK, self.processTickEvent)313 self.eventEngine.register(EVENT_ORDER, self.processOrderEvent)314 self.eventEngine.register(EVENT_TRADE, self.processTradeEvent)315 # ROBINLIN316 # self.eventEngine.register(EVENT_ACCOUNT, self.processAccountEvent)317 # self.eventEngine.register(EVENT_POSITION, self.processPositionEvent)318 #ROBINLIN----------------------------------------------------------------------319 def processAccountEvent(self,event):320 """è´¦æ·èµéæ´æ°"""321 # self.writeCtaLog("processAccountEvent::è´¦æ·èµéæ´æ°" )322 account = event.dict_['data']323 for name in self.strategyDict.keys():324 strategy = self.strategyDict[name]325 if strategy.inited:326 self.callStrategyFunc(strategy, strategy.onAccountEvent, account)327 #ROBINLIN----------------------------------------------------------------------328 def processPositionEvent(self, event):329 """æä»æ´æ°"""330 # self.writeCtaLog("processPositionEvent::æä»æ´æ°")331 position = event.dict_['data']332 for name in self.strategyDict.keys():333 strategy = self.strategyDict[name]334 if strategy.inited:335 self.callStrategyFunc(strategy, strategy.onPositionEvent, position)336 337 #----------------------------------------------------------------------338 def insertData(self, dbName, collectionName, data):339 """æå
¥æ°æ®å°æ°æ®åºï¼è¿éçdataå¯ä»¥æ¯VtTickDataæè
VtBarDataï¼"""340 self.mainEngine.dbInsert(dbName, collectionName, data.__dict__)341 342 #----------------------------------------------------------------------343 def loadBar(self, dbName, collectionName, days):344 """ä»æ°æ®åºä¸è¯»åBaræ°æ®ï¼startDateæ¯datetime对象"""345 startDate = self.today - timedelta(days)346 347 d = {'datetime':{'$gte':startDate}}348 barData = self.mainEngine.dbQuery(dbName, collectionName, d, 'datetime')349 350 l = []351 for d in barData:352 bar = VtBarData()353 bar.__dict__ = d354 l.append(bar)355 return l356 357 #----------------------------------------------------------------------358 def loadTick(self, dbName, collectionName, days):359 """ä»æ°æ®åºä¸è¯»åTickæ°æ®ï¼startDateæ¯datetime对象"""360 startDate = self.today - timedelta(days)361 362 d = {'datetime':{'$gte':startDate}}363 tickData = self.mainEngine.dbQuery(dbName, collectionName, d, 'datetime')364 365 l = []366 for d in tickData:367 tick = VtTickData()368 tick.__dict__ = d369 l.append(tick)370 return l 371 372 #----------------------------------------------------------------------373 def writeCtaLog(self, content):374 """å¿«éååºCTA模åæ¥å¿äºä»¶"""375 log = VtLogData()376 log.logContent = content377 log.gatewayName = 'CTA_STRATEGY'378 event = Event(type_=EVENT_CTA_LOG)379 event.dict_['data'] = log380 self.eventEngine.put(event) 381 382 #----------------------------------------------------------------------383 def loadStrategy(self, setting):384 """è½½å
¥çç¥"""385 try:386 name = setting['name']387 className = setting['className']388 except Exception:389 msg = traceback.format_exc()390 self.writeCtaLog(u'è½½å
¥çç¥åºéï¼%s' %msg)391 return392 393 # è·åçç¥ç±»394 strategyClass = STRATEGY_CLASS.get(className, None)395 if not strategyClass:396 self.writeCtaLog(u'æ¾ä¸å°çç¥ç±»ï¼%s' %className)397 return398 399 # é²æ¢çç¥éå400 if name in self.strategyDict:401 self.writeCtaLog(u'çç¥å®ä¾éåï¼%s' %name)402 else:403 # å建çç¥å®ä¾404 strategy = strategyClass(self, setting) 405 self.strategyDict[name] = strategy406 407 # å建å§æå·å表408 self.strategyOrderDict[name] = set()409 410 # ä¿åTickæ å°å
³ç³»411 if strategy.vtSymbol in self.tickStrategyDict:412 l = self.tickStrategyDict[strategy.vtSymbol]413 else:414 l = []415 self.tickStrategyDict[strategy.vtSymbol] = l416 l.append(strategy)417 418 #----------------------------------------------------------------------419 def subscribeMarketData(self, strategy):420 """订é
è¡æ
"""421 # 订é
å约422 contract = self.mainEngine.getContract(strategy.vtSymbol)423 if contract:424 req = VtSubscribeReq()425 req.symbol = contract.symbol426 req.exchange = contract.exchange427 428 # 对äºIBæ¥å£è®¢é
è¡æ
æ¶æéçè´§å¸å产åç±»åï¼ä»çç¥å±æ§ä¸è·å429 req.currency = strategy.currency430 req.productClass = strategy.productClass431 432 self.mainEngine.subscribe(req, contract.gatewayName)433 else:434 self.writeCtaLog(u'%sç交æå约%sæ æ³æ¾å°' %(strategy.name, strategy.vtSymbol))435 #----------------------------------------------------------------------436 def initStrategy(self, name):437 """åå§åçç¥"""438 if name in self.strategyDict:439 strategy = self.strategyDict[name]440 441 if not strategy.inited:442 strategy.inited = True443 self.callStrategyFunc(strategy, strategy.onInit)444 self.loadSyncData(strategy) # åå§åå®æåå è½½åæ¥æ°æ®445 self.subscribeMarketData(strategy) # å è½½åæ¥æ°æ®åå订é
è¡æ
446 else:447 self.writeCtaLog(u'请å¿éå¤åå§åçç¥å®ä¾ï¼%s' %name)448 else:449 self.writeCtaLog(u'çç¥å®ä¾ä¸åå¨ï¼%s' %name) 450 #---------------------------------------------------------------------451 def startStrategy(self, name):452 """å¯å¨çç¥"""453 if name in self.strategyDict:454 strategy = self.strategyDict[name]455 456 if strategy.inited and not strategy.trading:457 strategy.trading = True458 self.callStrategyFunc(strategy, strategy.onStart)459 else:460 self.writeCtaLog(u'çç¥å®ä¾ä¸åå¨ï¼%s' %name)461 462 #----------------------------------------------------------------------463 def stopStrategy(self, name):464 """åæ¢çç¥"""465 if name in self.strategyDict:466 strategy = self.strategyDict[name]467 468 if strategy.trading:469 #strategy.trading = False470 self.callStrategyFunc(strategy, strategy.onStop)471 472 # 对该çç¥ååºçææéä»·åè¿è¡æ¤å473 for vtOrderID, s in self.orderStrategyDict.items():474 if s is strategy:475 self.cancelOrder(vtOrderID)476 477 # 对该çç¥ååºçæææ¬å°åæ¢åæ¤å478 for stopOrderID, so in self.workingStopOrderDict.items():479 if so.strategy is strategy:480 self.cancelStopOrder(stopOrderID)481 strategy.trading = False #RL move from front to here, let sync data working482 else:483 self.writeCtaLog(u'çç¥å®ä¾ä¸åå¨ï¼%s' %name) 484 485 #----------------------------------------------------------------------486 def initAll(self):487 """å
¨é¨åå§å"""488 for name in self.strategyDict.keys():489 self.initStrategy(name) 490 491 #----------------------------------------------------------------------492 def startAll(self):493 """å
¨é¨å¯å¨"""494 for name in self.strategyDict.keys():495 self.startStrategy(name)496 497 #----------------------------------------------------------------------498 def stopAll(self):499 """å
¨é¨åæ¢"""500 for name in self.strategyDict.keys():501 self.stopStrategy(name) 502 503 #----------------------------------------------------------------------504 def saveSetting(self):505 """ä¿åçç¥é
ç½®"""506 with open(self.settingfilePath, 'w') as f:507 l = []508 509 for strategy in self.strategyDict.values():510 setting = {}511 for param in strategy.paramList:512 setting[param] = strategy.__getattribute__(param)513 l.append(setting)514 515 jsonL = json.dumps(l, indent=4)516 f.write(jsonL)517 518 #----------------------------------------------------------------------519 def loadSetting(self):520 """读åçç¥é
ç½®"""521 with open(self.settingfilePath) as f:522 l = json.load(f)523 524 for setting in l:525 self.loadStrategy(setting)526 527 #----------------------------------------------------------------------528 def getStrategyVar(self, name):529 """è·åçç¥å½åçåéåå
¸"""530 if name in self.strategyDict:531 strategy = self.strategyDict[name]532 varDict = OrderedDict()533 534 for key in strategy.varList:535 varDict[key] = strategy.__getattribute__(key)536 537 return varDict538 else:539 self.writeCtaLog(u'çç¥å®ä¾ä¸åå¨ï¼' + name) 540 return None541 542 #----------------------------------------------------------------------543 def getStrategyParam(self, name):544 """è·åçç¥çåæ°åå
¸"""545 if name in self.strategyDict:546 strategy = self.strategyDict[name]547 paramDict = OrderedDict()548 549 for key in strategy.paramList: 550 paramDict[key] = strategy.__getattribute__(key)551 552 return paramDict553 else:554 self.writeCtaLog(u'çç¥å®ä¾ä¸åå¨ï¼' + name) 555 return None556 557 #----------------------------------------------------------------------558 def getStrategyNames(self):559 """æ¥è¯¢ææçç¥å称"""560 return self.strategyDict.keys() 561 562 #----------------------------------------------------------------------563 def putStrategyEvent(self, name):564 """触åçç¥ç¶æååäºä»¶ï¼é常ç¨äºéç¥GUIæ´æ°ï¼"""565 strategy = self.strategyDict[name]566 d = {k:strategy.__getattribute__(k) for k in strategy.varList}567 568 event = Event(EVENT_CTA_STRATEGY+name)569 event.dict_['data'] = d570 self.eventEngine.put(event)571 572 d2 = {k:str(v) for k,v in d.items()}573 d2['name'] = name574 event2 = Event(EVENT_CTA_STRATEGY)575 event2.dict_['data'] = d2576 self.eventEngine.put(event2) 577 578 #----------------------------------------------------------------------579 def callStrategyFunc(self, strategy, func, params=None):580 """è°ç¨çç¥çå½æ°ï¼è¥è§¦åå¼å¸¸åææ"""581 try:582 if params:583 func(params)584 else:585 func()586 except Exception:587 # åæ¢çç¥ï¼ä¿®æ¹ç¶æ为æªåå§å588 strategy.trading = False589 strategy.inited = False590 591 # ååºæ¥å¿592 content = '\n'.join([u'çç¥%s触åå¼å¸¸å·²åæ¢' %strategy.name,593 traceback.format_exc()])594 self.writeCtaLog(content)595 596 #----------------------------------------------------------------------597 def saveSyncData(self, strategy):598 """ä¿åçç¥çæä»æ
åµå°æ°æ®åº"""599 flt = {'name': strategy.name,600 'vtSymbol': strategy.vtSymbol}601 602 d = copy(flt)603 for key in strategy.syncList:604 d[key] = strategy.__getattribute__(key)605 606 self.mainEngine.dbUpdate(POSITION_DB_NAME, strategy.className,607 d, flt, True)608 609 content = u'çç¥%såæ¥æ°æ®ä¿åæåï¼å½åæä»%s' %(strategy.name, strategy.pos)610 #self.writeCtaLog(content)611 612 #----------------------------------------------------------------------613 def loadSyncData(self, strategy):614 """ä»æ°æ®åºè½½å
¥çç¥çæä»æ
åµ"""615 flt = {'name': strategy.name,616 'vtSymbol': strategy.vtSymbol}617 syncData = self.mainEngine.dbQuery(POSITION_DB_NAME, strategy.className, flt)618 619 if not syncData:620 return621 622 d = syncData[0]623 624 for key in strategy.syncList:625 if key in d:626 strategy.__setattr__(key, d[key])627 628 #----------------------------------------------------------------------629 def roundToPriceTick(self, priceTick, price):630 """åæ´ä»·æ ¼å°å约æå°ä»·æ ¼åå¨"""631 if not priceTick:632 return price633 634 newPrice = round(price/priceTick, 0) * priceTick635 return newPrice 636 637 #----------------------------------------------------------------------638 def stop(self):639 """åæ¢"""640 pass641 642 #----------------------------------------------------------------------643 def cancelAll(self, name):644 """å
¨é¨æ¤å"""645 s = self.strategyOrderDict[name]646 647 # éåå表ï¼å
¨é¨æ¤å648 # è¿éä¸è½ç´æ¥éåéåsï¼å 为æ¤åæ¶ä¼ä¿®æ¹sä¸çå
容ï¼å¯¼è´åºé649 for orderID in list(s):650 if STOPORDERPREFIX in orderID:651 self.cancelStopOrder(orderID)652 else:...
credentials.test.js
Source:credentials.test.js
1"use strict";2const rewire = require("rewire");3const should = require("should");4const sinon = require("sinon");5const {6 BadRequestError,7 Request,8 SizeLimitError,9} = require("../../../../index");10const KuzzleMock = require("../../../mocks/kuzzle.mock");11const SecurityController = rewire(12 "../../../../lib/api/controllers/securityController"13);14describe("Test: security controller - credentials", () => {15 let kuzzle;16 let request;17 let securityController;18 beforeEach(() => {19 kuzzle = new KuzzleMock();20 securityController = new SecurityController();21 kuzzle.pluginsManager.listStrategies.returns(["someStrategy"]);22 });23 describe("#createCredentials", () => {24 it("should call the plugin create method", () => {25 const methodStub = sinon.stub().resolves({ foo: "bar" });26 request = new Request({27 controller: "security",28 action: "createCredentials",29 strategy: "someStrategy",30 body: {31 some: "credentials",32 },33 _id: "someUserId",34 });35 kuzzle.pluginsManager.getStrategyMethod.returns(methodStub);36 return securityController.createCredentials(request).then((result) => {37 should(result).be.deepEqual({ foo: "bar" });38 should(kuzzle.pluginsManager.getStrategyMethod).be.calledTwice();39 should(40 kuzzle.pluginsManager.getStrategyMethod.firstCall.args[0]41 ).be.eql("someStrategy");42 should(43 kuzzle.pluginsManager.getStrategyMethod.firstCall.args[1]44 ).be.eql("validate");45 should(46 kuzzle.pluginsManager.getStrategyMethod.secondCall.args[0]47 ).be.eql("someStrategy");48 should(49 kuzzle.pluginsManager.getStrategyMethod.secondCall.args[1]50 ).be.eql("create");51 should(methodStub).be.calledTwice();52 should(methodStub.firstCall.args[0]).be.eql(request);53 should(methodStub.firstCall.args[1]).be.deepEqual({54 some: "credentials",55 });56 should(methodStub.firstCall.args[2]).be.eql("someUserId");57 should(methodStub.firstCall.args[3]).be.eql("someStrategy");58 should(methodStub.secondCall.args[0]).be.eql(request);59 should(methodStub.secondCall.args[1]).be.deepEqual({60 some: "credentials",61 });62 should(methodStub.secondCall.args[2]).be.eql("someUserId");63 should(methodStub.secondCall.args[3]).be.eql("someStrategy");64 });65 });66 it("should throw if the user does not already exist", () => {67 request = new Request({68 controller: "security",69 action: "createCredentials",70 strategy: "someStrategy",71 body: {72 some: "credentials",73 },74 _id: "someUserId",75 });76 const error = new Error("foo");77 kuzzle.ask78 .withArgs("core:security:user:get", "someUserId")79 .rejects(error);80 return should(securityController.createCredentials(request)).rejectedWith(81 error82 );83 });84 });85 describe("#updateCredentials", () => {86 it("should call the plugin update method", () => {87 const methodStub = sinon.stub().resolves({ foo: "bar" });88 request = new Request({89 controller: "security",90 action: "createCredentials",91 strategy: "someStrategy",92 body: {93 some: "credentials",94 },95 _id: "someUserId",96 });97 kuzzle.pluginsManager.getStrategyMethod.returns(methodStub);98 return securityController.updateCredentials(request).then((result) => {99 should(result).be.deepEqual({ foo: "bar" });100 should(kuzzle.pluginsManager.getStrategyMethod).be.calledTwice();101 should(102 kuzzle.pluginsManager.getStrategyMethod.firstCall.args[0]103 ).be.eql("someStrategy");104 should(105 kuzzle.pluginsManager.getStrategyMethod.firstCall.args[1]106 ).be.eql("validate");107 should(108 kuzzle.pluginsManager.getStrategyMethod.secondCall.args[0]109 ).be.eql("someStrategy");110 should(111 kuzzle.pluginsManager.getStrategyMethod.secondCall.args[1]112 ).be.eql("update");113 should(methodStub).be.calledTwice();114 should(methodStub.firstCall.args[0]).be.eql(request);115 should(methodStub.firstCall.args[1]).be.deepEqual({116 some: "credentials",117 });118 should(methodStub.firstCall.args[2]).be.eql("someUserId");119 should(methodStub.firstCall.args[3]).be.eql("someStrategy");120 should(methodStub.secondCall.args[0]).be.eql(request);121 should(methodStub.secondCall.args[1]).be.deepEqual({122 some: "credentials",123 });124 should(methodStub.secondCall.args[2]).be.eql("someUserId");125 should(methodStub.secondCall.args[3]).be.eql("someStrategy");126 });127 });128 it("should throw if the user does not already exist", () => {129 request = new Request({130 controller: "security",131 action: "updateCredentials",132 strategy: "someStrategy",133 body: {134 some: "credentials",135 },136 _id: "someUserId",137 });138 const error = new Error("foo");139 kuzzle.ask140 .withArgs("core:security:user:get", "someUserId")141 .rejects(error);142 return should(securityController.updateCredentials(request)).rejectedWith(143 error144 );145 });146 });147 describe("#hasCredentials", () => {148 it("should call the plugin exists method", () => {149 const methodStub = sinon.stub().resolves({ foo: "bar" });150 request = new Request({151 controller: "security",152 action: "hasCredentials",153 strategy: "someStrategy",154 _id: "someUserId",155 });156 kuzzle.pluginsManager.getStrategyMethod.returns(methodStub);157 return securityController.hasCredentials(request).then((result) => {158 should(result).be.deepEqual({ foo: "bar" });159 should(kuzzle.pluginsManager.getStrategyMethod).be.calledOnce();160 should(161 kuzzle.pluginsManager.getStrategyMethod.firstCall.args[0]162 ).be.eql("someStrategy");163 should(164 kuzzle.pluginsManager.getStrategyMethod.firstCall.args[1]165 ).be.eql("exists");166 should(methodStub).be.calledOnce();167 should(methodStub.firstCall.args[0]).be.eql(request);168 should(methodStub.firstCall.args[1]).be.eql("someUserId");169 should(methodStub.firstCall.args[2]).be.eql("someStrategy");170 });171 });172 });173 describe("#validateCredentials", () => {174 it("should call the plugin validate method", () => {175 const methodStub = sinon.stub().resolves({ foo: "bar" });176 request = new Request({177 controller: "security",178 action: "validateCredentials",179 strategy: "someStrategy",180 body: {181 some: "credentials",182 },183 _id: "someUserId",184 });185 kuzzle.pluginsManager.getStrategyMethod.returns(methodStub);186 return securityController.validateCredentials(request).then((result) => {187 should(result).be.deepEqual({ foo: "bar" });188 should(kuzzle.pluginsManager.getStrategyMethod).be.calledOnce();189 should(190 kuzzle.pluginsManager.getStrategyMethod.firstCall.args[0]191 ).be.eql("someStrategy");192 should(193 kuzzle.pluginsManager.getStrategyMethod.firstCall.args[1]194 ).be.eql("validate");195 should(methodStub).be.calledOnce();196 should(methodStub.firstCall.args[0]).be.eql(request);197 should(methodStub.firstCall.args[1]).be.deepEqual({198 some: "credentials",199 });200 should(methodStub.firstCall.args[2]).be.eql("someUserId");201 should(methodStub.firstCall.args[3]).be.eql("someStrategy");202 });203 });204 });205 describe("#deleteCredentials", () => {206 it("should call the plugin delete method", () => {207 const methodStub = sinon.stub().resolves({ foo: "bar" });208 request = new Request({209 controller: "security",210 action: "deleteCredentials",211 strategy: "someStrategy",212 _id: "someUserId",213 });214 kuzzle.pluginsManager.getStrategyMethod.returns(methodStub);215 return securityController.deleteCredentials(request).then((result) => {216 should(result).be.deepEqual({ acknowledged: true });217 should(kuzzle.pluginsManager.getStrategyMethod).be.calledOnce();218 should(219 kuzzle.pluginsManager.getStrategyMethod.firstCall.args[0]220 ).be.eql("someStrategy");221 should(222 kuzzle.pluginsManager.getStrategyMethod.firstCall.args[1]223 ).be.eql("delete");224 should(methodStub).be.calledOnce();225 should(methodStub.firstCall.args[0]).be.eql(request);226 should(methodStub.firstCall.args[1]).be.eql("someUserId");227 should(methodStub.firstCall.args[2]).be.eql("someStrategy");228 });229 });230 });231 describe("#searchUsersByCredentials", () => {232 let query;233 let methodStub;234 let stubResult;235 beforeEach(() => {236 query = {237 bool: {238 must: [239 {240 match: {241 credentials: "test@test.com",242 },243 },244 ],245 },246 };247 request = new Request({248 controller: "security",249 action: "searchUsersByCredentials",250 strategy: "someStrategy",251 body: { query },252 });253 securityController.translateKoncorde = sinon.stub().resolves();254 stubResult = {255 hits: [{ credentials: "test@test.com", kuid: "kuid" }],256 total: 1,257 };258 methodStub = sinon.stub().resolves(stubResult);259 kuzzle.pluginsManager.getStrategyMethod.returns(methodStub);260 });261 it("should return the result of the appropriate method from the right strategy plugin", async () => {262 const result = await securityController.searchUsersByCredentials(request);263 should(securityController.translateKoncorde).not.be.called();264 should(kuzzle.pluginsManager.getStrategyMethod).be.calledOnce();265 should(kuzzle.pluginsManager.getStrategyMethod).be.calledWith(266 "someStrategy",267 "search"268 );269 should(methodStub).be.calledOnce();270 should(methodStub.firstCall.args[0]).be.eql({ query });271 should(result).be.deepEqual(stubResult);272 });273 it("should throw if the optional method search has not been implemented", () => {274 kuzzle.pluginsManager.getStrategyMethod.returns(undefined);275 return should(276 securityController.searchUsersByCredentials(request)277 ).rejectedWith({ id: "plugin.strategy.missing_optional_method" });278 });279 it("should reject if the size argument exceeds server configuration", () => {280 kuzzle.config.limits.documentsFetchCount = 1;281 request.input.args.size = 10;282 return should(283 securityController.searchUsersByCredentials(request)284 ).rejectedWith(SizeLimitError, {285 id: "services.storage.get_limit_exceeded",286 });287 });288 it('should reject if the "lang" is not supported', () => {289 request.input.args.lang = "turkish";290 return should(291 securityController.searchUsersByCredentials(request)292 ).rejectedWith(BadRequestError, { id: "api.assert.invalid_argument" });293 });294 it('should call the "translateKoncorde" method if "lang" is "koncorde"', async () => {295 request.input.body = {296 query: { equals: { credentials: "test@test.com" } },297 };298 request.input.args.lang = "koncorde";299 await securityController.searchUsersByCredentials(request);300 should(securityController.translateKoncorde).be.calledWith({301 equals: { credentials: "test@test.com" },302 });303 });304 });305 describe("#getCredentials", () => {306 it("should call the plugin getInfo method if it is provided", () => {307 const methodStub = sinon.stub().resolves({ foo: "bar" });308 request = new Request({309 controller: "security",310 action: "getCredentials",311 strategy: "someStrategy",312 _id: "someUserId",313 });314 kuzzle.pluginsManager.hasStrategyMethod.returns(true);315 kuzzle.pluginsManager.getStrategyMethod.returns(methodStub);316 return securityController.getCredentials(request).then((result) => {317 should(result).be.deepEqual({ foo: "bar" });318 should(kuzzle.pluginsManager.hasStrategyMethod).be.calledOnce();319 should(320 kuzzle.pluginsManager.hasStrategyMethod.firstCall.args[0]321 ).be.eql("someStrategy");322 should(323 kuzzle.pluginsManager.hasStrategyMethod.firstCall.args[1]324 ).be.eql("getInfo");325 should(kuzzle.pluginsManager.getStrategyMethod).be.calledOnce();326 should(327 kuzzle.pluginsManager.getStrategyMethod.firstCall.args[0]328 ).be.eql("someStrategy");329 should(330 kuzzle.pluginsManager.getStrategyMethod.firstCall.args[1]331 ).be.eql("getInfo");332 should(methodStub).be.calledOnce();333 should(methodStub.firstCall.args[0]).be.eql(request);334 should(methodStub.firstCall.args[1]).be.eql("someUserId");335 should(methodStub.firstCall.args[2]).be.eql("someStrategy");336 });337 });338 it("should resolve to an empty object if getInfo method is not provided", () => {339 const methodStub = sinon.stub().resolves({ foo: "bar" });340 request = new Request({341 controller: "security",342 action: "getCredentials",343 strategy: "someStrategy",344 _id: "someUserId",345 });346 kuzzle.pluginsManager.hasStrategyMethod.returns(false);347 kuzzle.pluginsManager.getStrategyMethod.returns(methodStub);348 return securityController.getCredentials(request).then((result) => {349 should(result).be.deepEqual({});350 should(kuzzle.pluginsManager.hasStrategyMethod).be.calledOnce();351 should(352 kuzzle.pluginsManager.hasStrategyMethod.firstCall.args[0]353 ).be.eql("someStrategy");354 should(355 kuzzle.pluginsManager.hasStrategyMethod.firstCall.args[1]356 ).be.eql("getInfo");357 should(kuzzle.pluginsManager.getStrategyMethod.callCount).be.eql(0);358 });359 });360 });361 describe("#getCredentialsById", () => {362 it("should call the plugin getById method if it is provided", () => {363 const methodStub = sinon.stub().resolves({ foo: "bar" });364 request = new Request({365 controller: "security",366 action: "getCredentials",367 strategy: "someStrategy",368 _id: "someUserId",369 });370 kuzzle.pluginsManager.hasStrategyMethod.returns(true);371 kuzzle.pluginsManager.getStrategyMethod.returns(methodStub);372 return securityController.getCredentialsById(request).then((result) => {373 should(result).be.deepEqual({ foo: "bar" });374 should(kuzzle.pluginsManager.hasStrategyMethod).be.calledOnce();375 should(376 kuzzle.pluginsManager.hasStrategyMethod.firstCall.args[0]377 ).be.eql("someStrategy");378 should(379 kuzzle.pluginsManager.hasStrategyMethod.firstCall.args[1]380 ).be.eql("getById");381 should(kuzzle.pluginsManager.getStrategyMethod).be.calledOnce();382 should(383 kuzzle.pluginsManager.getStrategyMethod.firstCall.args[0]384 ).be.eql("someStrategy");385 should(386 kuzzle.pluginsManager.getStrategyMethod.firstCall.args[1]387 ).be.eql("getById");388 should(methodStub).be.calledOnce();389 should(methodStub.firstCall.args[0]).be.eql(request);390 should(methodStub.firstCall.args[1]).be.eql("someUserId");391 should(methodStub.firstCall.args[2]).be.eql("someStrategy");392 });393 });394 it("should resolve to an empty object if getById method is not provided", () => {395 const methodStub = sinon.stub().resolves({ foo: "bar" });396 request = new Request({397 controller: "security",398 action: "getCredentials",399 strategy: "someStrategy",400 _id: "someUserId",401 });402 kuzzle.pluginsManager.hasStrategyMethod.returns(false);403 kuzzle.pluginsManager.getStrategyMethod.returns(methodStub);404 return securityController.getCredentialsById(request).then((result) => {405 should(result).be.deepEqual({});406 should(kuzzle.pluginsManager.hasStrategyMethod).be.calledOnce();407 should(408 kuzzle.pluginsManager.hasStrategyMethod.firstCall.args[0]409 ).be.eql("someStrategy");410 should(411 kuzzle.pluginsManager.hasStrategyMethod.firstCall.args[1]412 ).be.eql("getById");413 should(kuzzle.pluginsManager.getStrategyMethod.callCount).be.eql(0);414 });415 });416 });417 describe("#getCredentialFields", () => {418 it("should return the list of a strategy's fields", () => {419 request = new Request({420 controller: "security",421 action: "getCredentialFields",422 strategy: "someStrategy",423 });424 kuzzle.pluginsManager.getStrategyFields.returns([425 "aField",426 "anotherField",427 ]);428 return securityController.getCredentialFields(request).then((result) => {429 should(result).be.deepEqual(["aField", "anotherField"]);430 should(kuzzle.pluginsManager.getStrategyFields).be.calledOnce();431 should(432 kuzzle.pluginsManager.getStrategyFields.firstCall.args[0]433 ).be.eql("someStrategy");434 });435 });436 });437 describe("#getAllCredentialFields", () => {438 it("should return the list of all strategies' fields", () => {439 request = new Request({440 controller: "security",441 action: "getAllCredentialFields",442 strategy: "someStrategy",443 });444 kuzzle.pluginsManager.listStrategies.returns([445 "someStrategy",446 "someOtherStrategy",447 ]);448 kuzzle.pluginsManager.getStrategyFields.returns([449 "aField",450 "anotherField",451 ]);452 return securityController453 .getAllCredentialFields(request)454 .then((result) => {455 should(result).be.deepEqual({456 someStrategy: ["aField", "anotherField"],457 someOtherStrategy: ["aField", "anotherField"],458 });459 should(kuzzle.pluginsManager.getStrategyFields).be.calledTwice();460 should(461 kuzzle.pluginsManager.getStrategyFields.firstCall.args[0]462 ).be.eql("someStrategy");463 should(464 kuzzle.pluginsManager.getStrategyFields.secondCall.args[0]465 ).be.eql("someOtherStrategy");466 });467 });468 });...
10.py
Source:10.py
...5 {6 'cases': [7 {8 'code': r"""9 >>> bacon_strategy(0, 9, cutoff=8, num_rolls=5)10 511 """,12 'hidden': False,13 'locked': False14 },15 {16 'code': r"""17 >>> bacon_strategy(9, 0, cutoff=6, num_rolls=5)18 019 """,20 'hidden': False,21 'locked': False22 },23 {24 'code': r"""25 >>> bacon_strategy(50, 2, cutoff=7, num_rolls=5)26 027 """,28 'hidden': False,29 'locked': False30 },31 {32 'code': r"""33 >>> bacon_strategy(32, 0, cutoff=8, num_rolls=4)34 435 """,36 'hidden': False,37 'locked': False38 },39 {40 'code': r"""41 >>> bacon_strategy(20, 1, cutoff=1, num_rolls=4)42 043 """,44 'hidden': False,45 'locked': False46 },47 {48 'code': r"""49 >>> from tests.check_strategy import check_strategy50 >>> check_strategy(bacon_strategy)51 """,52 'hidden': False,53 'locked': False54 }55 ],56 'scored': True,57 'setup': r"""58 >>> from hog import *59 """,60 'teardown': '',61 'type': 'doctest'62 },63 {64 'cases': [65 {66 'code': r"""67 >>> bacon_strategy(44, 47, 0, 4)68 069 """,70 'hidden': False,71 'locked': False72 },73 {74 'code': r"""75 >>> bacon_strategy(37, 12, 8, 10)76 077 """,78 'hidden': False,79 'locked': False80 },81 {82 'code': r"""83 >>> bacon_strategy(40, 15, 13, 9)84 985 """,86 'hidden': False,87 'locked': False88 },89 {90 'code': r"""91 >>> bacon_strategy(24, 3, 8, 1)92 193 """,94 'hidden': False,95 'locked': False96 },97 {98 'code': r"""99 >>> bacon_strategy(46, 55, 5, 2)100 0101 """,102 'hidden': False,103 'locked': False104 },105 {106 'code': r"""107 >>> bacon_strategy(99, 78, 15, 7)108 7109 """,110 'hidden': False,111 'locked': False112 },113 {114 'code': r"""115 >>> bacon_strategy(10, 73, 3, 5)116 0117 """,118 'hidden': False,119 'locked': False120 },121 {122 'code': r"""123 >>> bacon_strategy(47, 68, 3, 4)124 0125 """,126 'hidden': False,127 'locked': False128 },129 {130 'code': r"""131 >>> bacon_strategy(67, 84, 17, 10)132 10133 """,134 'hidden': False,135 'locked': False136 },137 {138 'code': r"""139 >>> bacon_strategy(92, 54, 1, 7)140 0141 """,142 'hidden': False,143 'locked': False144 },145 {146 'code': r"""147 >>> bacon_strategy(9, 15, 0, 2)148 0149 """,150 'hidden': False,151 'locked': False152 },153 {154 'code': r"""155 >>> bacon_strategy(25, 63, 16, 2)156 2157 """,158 'hidden': False,159 'locked': False160 },161 {162 'code': r"""163 >>> bacon_strategy(75, 27, 6, 2)164 0165 """,166 'hidden': False,167 'locked': False168 },169 {170 'code': r"""171 >>> bacon_strategy(82, 48, 10, 1)172 1173 """,174 'hidden': False,175 'locked': False176 },177 {178 'code': r"""179 >>> bacon_strategy(88, 12, 7, 10)180 0181 """,182 'hidden': False,183 'locked': False184 },185 {186 'code': r"""187 >>> bacon_strategy(72, 12, 5, 8)188 0189 """,190 'hidden': False,191 'locked': False192 },193 {194 'code': r"""195 >>> bacon_strategy(41, 69, 1, 5)196 0197 """,198 'hidden': False,199 'locked': False200 },201 {202 'code': r"""203 >>> bacon_strategy(15, 6, 16, 7)204 7205 """,206 'hidden': False,207 'locked': False208 },209 {210 'code': r"""211 >>> bacon_strategy(42, 19, 5, 2)212 0213 """,214 'hidden': False,215 'locked': False216 },217 {218 'code': r"""219 >>> bacon_strategy(93, 98, 8, 4)220 0221 """,222 'hidden': False,223 'locked': False224 },225 {226 'code': r"""227 >>> bacon_strategy(99, 90, 15, 10)228 10229 """,230 'hidden': False,231 'locked': False232 },233 {234 'code': r"""235 >>> bacon_strategy(73, 79, 4, 1)236 0237 """,238 'hidden': False,239 'locked': False240 },241 {242 'code': r"""243 >>> bacon_strategy(4, 44, 0, 5)244 0245 """,246 'hidden': False,247 'locked': False248 },249 {250 'code': r"""251 >>> bacon_strategy(83, 40, 9, 7)252 7253 """,254 'hidden': False,255 'locked': False256 },257 {258 'code': r"""259 >>> bacon_strategy(34, 3, 0, 8)260 0261 """,262 'hidden': False,263 'locked': False264 },265 {266 'code': r"""267 >>> bacon_strategy(4, 62, 15, 7)268 7269 """,270 'hidden': False,271 'locked': False272 },273 {274 'code': r"""275 >>> bacon_strategy(53, 62, 6, 1)276 0277 """,278 'hidden': False,279 'locked': False280 },281 {282 'code': r"""283 >>> bacon_strategy(19, 56, 8, 9)284 0285 """,286 'hidden': False,287 'locked': False288 },289 {290 'code': r"""291 >>> bacon_strategy(1, 5, 0, 4)292 0293 """,294 'hidden': False,295 'locked': False296 },297 {298 'code': r"""299 >>> bacon_strategy(85, 34, 8, 1)300 0301 """,302 'hidden': False,303 'locked': False304 },305 {306 'code': r"""307 >>> bacon_strategy(37, 37, 13, 5)308 5309 """,310 'hidden': False,311 'locked': False312 },313 {314 'code': r"""315 >>> bacon_strategy(82, 87, 16, 3)316 3317 """,318 'hidden': False,319 'locked': False320 },321 {322 'code': r"""323 >>> bacon_strategy(87, 43, 5, 7)324 0325 """,326 'hidden': False,327 'locked': False328 },329 {330 'code': r"""331 >>> bacon_strategy(20, 7, 2, 3)332 0333 """,334 'hidden': False,335 'locked': False336 },337 {338 'code': r"""339 >>> bacon_strategy(33, 85, 4, 4)340 4341 """,342 'hidden': False,343 'locked': False344 },345 {346 'code': r"""347 >>> bacon_strategy(73, 15, 12, 8)348 8349 """,350 'hidden': False,351 'locked': False352 },353 {354 'code': r"""355 >>> bacon_strategy(5, 98, 8, 2)356 0357 """,358 'hidden': False,359 'locked': False360 },361 {362 'code': r"""363 >>> bacon_strategy(15, 76, 3, 4)364 0365 """,366 'hidden': False,367 'locked': False368 },369 {370 'code': r"""371 >>> bacon_strategy(33, 75, 19, 5)372 5373 """,374 'hidden': False,375 'locked': False376 },377 {378 'code': r"""379 >>> bacon_strategy(9, 41, 0, 5)380 0381 """,382 'hidden': False,383 'locked': False384 },385 {386 'code': r"""387 >>> bacon_strategy(70, 91, 7, 6)388 6389 """,390 'hidden': False,391 'locked': False392 },393 {394 'code': r"""395 >>> bacon_strategy(64, 35, 12, 3)396 3397 """,398 'hidden': False,399 'locked': False400 },401 {402 'code': r"""403 >>> bacon_strategy(51, 92, 14, 8)404 8405 """,406 'hidden': False,407 'locked': False408 },409 {410 'code': r"""411 >>> bacon_strategy(68, 64, 17, 6)412 6413 """,414 'hidden': False,415 'locked': False416 },417 {418 'code': r"""419 >>> bacon_strategy(20, 35, 17, 4)420 4421 """,422 'hidden': False,423 'locked': False424 },425 {426 'code': r"""427 >>> bacon_strategy(75, 30, 3, 1)428 0429 """,430 'hidden': False,431 'locked': False432 },433 {434 'code': r"""435 >>> bacon_strategy(61, 69, 8, 5)436 0437 """,438 'hidden': False,439 'locked': False440 },441 {442 'code': r"""443 >>> bacon_strategy(7, 6, 7, 9)444 9445 """,446 'hidden': False,447 'locked': False448 },449 {450 'code': r"""451 >>> bacon_strategy(0, 51, 17, 5)452 5453 """,454 'hidden': False,455 'locked': False456 },457 {458 'code': r"""459 >>> bacon_strategy(42, 45, 8, 6)460 0461 """,462 'hidden': False,463 'locked': False464 },465 {466 'code': r"""467 >>> bacon_strategy(48, 96, 11, 2)468 2469 """,470 'hidden': False,471 'locked': False472 },473 {474 'code': r"""475 >>> bacon_strategy(57, 96, 9, 6)476 0477 """,478 'hidden': False,479 'locked': False480 },481 {482 'code': r"""483 >>> bacon_strategy(28, 11, 13, 8)484 8485 """,486 'hidden': False,487 'locked': False488 },489 {490 'code': r"""491 >>> bacon_strategy(25, 29, 5, 7)492 0493 """,494 'hidden': False,495 'locked': False496 },497 {498 'code': r"""499 >>> bacon_strategy(69, 2, 15, 8)500 8501 """,502 'hidden': False,503 'locked': False504 },505 {506 'code': r"""507 >>> bacon_strategy(77, 26, 7, 9)508 0509 """,510 'hidden': False,511 'locked': False512 },513 {514 'code': r"""515 >>> bacon_strategy(85, 15, 0, 3)516 0517 """,518 'hidden': False,519 'locked': False520 },521 {522 'code': r"""523 >>> bacon_strategy(79, 86, 5, 7)524 0525 """,526 'hidden': False,527 'locked': False528 },529 {530 'code': r"""531 >>> bacon_strategy(35, 32, 14, 6)532 6533 """,534 'hidden': False,535 'locked': False536 },537 {538 'code': r"""539 >>> bacon_strategy(49, 44, 13, 8)540 8541 """,542 'hidden': False,543 'locked': False544 },545 {546 'code': r"""547 >>> bacon_strategy(77, 65, 6, 4)548 4549 """,550 'hidden': False,551 'locked': False552 },553 {554 'code': r"""555 >>> bacon_strategy(99, 18, 2, 1)556 0557 """,558 'hidden': False,559 'locked': False560 },561 {562 'code': r"""563 >>> bacon_strategy(18, 24, 17, 10)564 10565 """,566 'hidden': False,567 'locked': False568 },569 {570 'code': r"""571 >>> bacon_strategy(44, 11, 18, 1)572 1573 """,574 'hidden': False,575 'locked': False576 },577 {578 'code': r"""579 >>> bacon_strategy(68, 38, 17, 5)580 5581 """,582 'hidden': False,583 'locked': False584 },585 {586 'code': r"""587 >>> bacon_strategy(46, 63, 8, 6)588 6589 """,590 'hidden': False,591 'locked': False592 },593 {594 'code': r"""595 >>> bacon_strategy(20, 60, 19, 6)596 6597 """,598 'hidden': False,599 'locked': False600 },601 {602 'code': r"""603 >>> bacon_strategy(67, 53, 10, 6)604 6605 """,606 'hidden': False,607 'locked': False608 },609 {610 'code': r"""611 >>> bacon_strategy(63, 39, 4, 1)612 0613 """,614 'hidden': False,615 'locked': False616 },617 {618 'code': r"""619 >>> bacon_strategy(54, 75, 9, 8)620 0621 """,622 'hidden': False,623 'locked': False624 },625 {626 'code': r"""627 >>> bacon_strategy(78, 86, 18, 9)628 9629 """,630 'hidden': False,631 'locked': False632 },633 {634 'code': r"""635 >>> bacon_strategy(45, 11, 8, 9)636 0637 """,638 'hidden': False,639 'locked': False640 },641 {642 'code': r"""643 >>> bacon_strategy(88, 19, 14, 6)644 6645 """,646 'hidden': False,647 'locked': False648 },649 {650 'code': r"""651 >>> bacon_strategy(22, 18, 14, 1)652 1653 """,654 'hidden': False,655 'locked': False656 },657 {658 'code': r"""659 >>> bacon_strategy(30, 91, 9, 10)660 10661 """,662 'hidden': False,663 'locked': False664 },665 {666 'code': r"""667 >>> bacon_strategy(19, 81, 8, 1)668 0669 """,670 'hidden': False,671 'locked': False672 },673 {674 'code': r"""675 >>> bacon_strategy(33, 7, 0, 2)676 0677 """,678 'hidden': False,679 'locked': False680 },681 {682 'code': r"""683 >>> bacon_strategy(87, 95, 11, 6)684 6685 """,686 'hidden': False,687 'locked': False688 },689 {690 'code': r"""691 >>> bacon_strategy(69, 86, 8, 10)692 10693 """,694 'hidden': False,695 'locked': False696 },697 {698 'code': r"""699 >>> bacon_strategy(87, 61, 10, 4)700 4701 """,702 'hidden': False,703 'locked': False704 },705 {706 'code': r"""707 >>> bacon_strategy(47, 60, 6, 4)708 0709 """,710 'hidden': False,711 'locked': False712 },713 {714 'code': r"""715 >>> bacon_strategy(67, 65, 14, 4)716 4717 """,718 'hidden': False,719 'locked': False720 },721 {722 'code': r"""723 >>> bacon_strategy(3, 66, 3, 7)724 0725 """,726 'hidden': False,727 'locked': False728 },729 {730 'code': r"""731 >>> bacon_strategy(82, 23, 8, 8)732 8733 """,734 'hidden': False,735 'locked': False736 },737 {738 'code': r"""739 >>> bacon_strategy(42, 89, 14, 1)740 1741 """,742 'hidden': False,743 'locked': False744 },745 {746 'code': r"""747 >>> bacon_strategy(32, 13, 4, 4)748 0749 """,750 'hidden': False,751 'locked': False752 },753 {754 'code': r"""755 >>> bacon_strategy(20, 96, 12, 4)756 4757 """,758 'hidden': False,759 'locked': False760 },761 {762 'code': r"""763 >>> bacon_strategy(77, 59, 15, 7)764 7765 """,766 'hidden': False,767 'locked': False768 },769 {770 'code': r"""771 >>> bacon_strategy(88, 32, 15, 2)772 2773 """,774 'hidden': False,775 'locked': False776 },777 {778 'code': r"""779 >>> bacon_strategy(19, 30, 4, 7)780 0781 """,782 'hidden': False,783 'locked': False784 },785 {786 'code': r"""787 >>> bacon_strategy(91, 29, 18, 4)788 4789 """,790 'hidden': False,791 'locked': False792 },793 {794 'code': r"""795 >>> bacon_strategy(50, 46, 10, 3)796 3797 """,798 'hidden': False,799 'locked': False800 },801 {802 'code': r"""803 >>> bacon_strategy(42, 67, 18, 7)804 7805 """,806 'hidden': False,807 'locked': False808 },809 {810 'code': r"""811 >>> bacon_strategy(37, 91, 4, 9)812 0813 """,814 'hidden': False,815 'locked': False816 },817 {818 'code': r"""819 >>> bacon_strategy(59, 82, 0, 6)820 0821 """,822 'hidden': False,823 'locked': False824 },825 {826 'code': r"""827 >>> bacon_strategy(22, 41, 19, 7)828 7829 """,830 'hidden': False,831 'locked': False832 },833 {834 'code': r"""835 >>> bacon_strategy(84, 90, 6, 5)836 0837 """,838 'hidden': False,839 'locked': False840 },841 {842 'code': r"""843 >>> bacon_strategy(90, 35, 9, 4)844 0845 """,846 'hidden': False,847 'locked': False848 },849 {850 'code': r"""851 >>> bacon_strategy(90, 42, 1, 5)852 0853 """,854 'hidden': False,855 'locked': False856 },857 {858 'code': r"""859 >>> bacon_strategy(1, 35, 8, 10)860 0861 """,862 'hidden': False,863 'locked': False864 }865 ],866 'scored': True,867 'setup': r"""868 >>> from hog import *869 """,870 'teardown': '',871 'type': 'doctest'872 }873 ]...
test_strategy.py
Source:test_strategy.py
...9from freqtrade.strategy import import_strategy10from freqtrade.strategy.default_strategy import DefaultStrategy11from freqtrade.strategy.interface import IStrategy12from freqtrade.resolvers import StrategyResolver13def test_import_strategy(caplog):14 caplog.set_level(logging.DEBUG)15 default_config = {}16 strategy = DefaultStrategy(default_config)17 strategy.some_method = lambda *args, **kwargs: 4218 assert strategy.__module__ == 'freqtrade.strategy.default_strategy'19 assert strategy.some_method() == 4220 imported_strategy = import_strategy(strategy, default_config)21 assert dir(strategy) == dir(imported_strategy)22 assert imported_strategy.__module__ == 'freqtrade.strategy'23 assert imported_strategy.some_method() == 4224 assert (25 'freqtrade.strategy',26 logging.DEBUG,27 'Imported strategy freqtrade.strategy.default_strategy.DefaultStrategy '28 'as freqtrade.strategy.DefaultStrategy',29 ) in caplog.record_tuples30def test_search_strategy():31 default_config = {}32 default_location = Path(__file__).parent.parent.joinpath('strategy').resolve()33 assert isinstance(34 StrategyResolver._search_object(35 directory=default_location,36 object_type=IStrategy,37 kwargs={'config': default_config},38 object_name='DefaultStrategy'39 ),40 IStrategy41 )42 assert StrategyResolver._search_object(43 directory=default_location,44 object_type=IStrategy,45 kwargs={'config': default_config},46 object_name='NotFoundStrategy'47 ) is None48def test_load_strategy(result):49 resolver = StrategyResolver({'strategy': 'TestStrategy'})50 metadata = {'pair': 'ETH/BTC'}51 assert 'adx' in resolver.strategy.advise_indicators(result, metadata=metadata)52def test_load_strategy_byte64(result):53 with open("freqtrade/tests/strategy/test_strategy.py", "r") as file:54 encoded_string = urlsafe_b64encode(file.read().encode("utf-8")).decode("utf-8")55 resolver = StrategyResolver({'strategy': 'TestStrategy:{}'.format(encoded_string)})56 assert 'adx' in resolver.strategy.advise_indicators(result, 'ETH/BTC')57def test_load_strategy_invalid_directory(result, caplog):58 resolver = StrategyResolver()59 extra_dir = path.join('some', 'path')60 resolver._load_strategy('TestStrategy', config={}, extra_dir=extra_dir)61 assert (62 'freqtrade.resolvers.strategy_resolver',63 logging.WARNING,64 'Path "{}" does not exist'.format(extra_dir),65 ) in caplog.record_tuples66 assert 'adx' in resolver.strategy.advise_indicators(result, {'pair': 'ETH/BTC'})67def test_load_not_found_strategy():68 strategy = StrategyResolver()69 with pytest.raises(ImportError,70 match=r"Impossible to load Strategy 'NotFoundStrategy'."71 r" This class does not exist or contains Python code errors"):72 strategy._load_strategy(strategy_name='NotFoundStrategy', config={})73def test_strategy(result):74 config = {'strategy': 'DefaultStrategy'}75 resolver = StrategyResolver(config)76 metadata = {'pair': 'ETH/BTC'}77 assert resolver.strategy.minimal_roi[0] == 0.0478 assert config["minimal_roi"]['0'] == 0.0479 assert resolver.strategy.stoploss == -0.1080 assert config['stoploss'] == -0.1081 assert resolver.strategy.ticker_interval == '5m'82 assert config['ticker_interval'] == '5m'83 df_indicators = resolver.strategy.advise_indicators(result, metadata=metadata)84 assert 'adx' in df_indicators85 dataframe = resolver.strategy.advise_buy(df_indicators, metadata=metadata)86 assert 'buy' in dataframe.columns87 dataframe = resolver.strategy.advise_sell(df_indicators, metadata=metadata)...
BackTestContainer.js
Source:BackTestContainer.js
1import React, { Component } from "react";2import { Query } from "react-apollo";3import * as math from "mathjs";4import { GET_GLOBAL_VARIABLES } from "apollo/queries";5import BackTestPresenter from "./BackTestPresenter";6import { assetCodeList, getAssetShortName } from "utils/data";7import { dateList, firstDateOfMonth, firtDateOfWeek } from "priceData";8import { BackTest, BackTestArgsHandler } from "utils/simulation";9// import { BackTest as backTesting, main, strategyStore } from "backtesting";10class BackTestContainer extends Component {11 render() {12 return (13 <Query query={GET_GLOBAL_VARIABLES}>14 {({ loading, error, data, client }) => {15 return (16 <BackTestPresenter17 rootComp={this}18 data={data}19 client={client}20 columns={this.columns}21 dataSource={this.state.dataSource}22 func={{ runSimulation: this.runSimulation }}23 resultList={this.state.resultList}24 selectPortfolioHandler={this.selectPortfolioHandler}25 selectedPortfolio={this.state.selectedPortfolio}26 refreshHandler={this.refreshHandler}27 setLogScale={this.setLogScale}28 isLogScale={this.state.logScale}29 batchSelection={this.batchSelection}30 />31 );32 }}33 </Query>34 );35 }36 constructor(props) {37 super(props);38 const columns = [39 {40 title: "name",41 dataIndex: "name",42 editable: true43 }44 ];45 assetCodeList.forEach(code => {46 columns.push({47 title: getAssetShortName(code),48 dataIndex: code,49 editable: true50 });51 });52 this.columns = columns;53 const dataSource = {54 dataSource: [],55 count: 056 };57 this.state = {58 dataSource,59 resultList: [],60 selectedPortfolio: null,61 logScale: false62 };63 }64 runSimulation = (65 variables,66 weightsList,67 name,68 rebalanceType = "none",69 strategyType = "none",70 strategyArg1 = "none",71 strategyArg2 = "none",72 strategyArg3 = "none",73 selectedAsset = "none"74 ) => {75 const { startDate, endDate } = variables;76 let newAllocation = weightsList;77 // EF LINE ì ìí¥ì 미침78 newAllocation = newAllocation.map(value => math.floor(value));79 const remainWieght = 100 - math.sum(newAllocation);80 newAllocation[newAllocation.length - 1] += remainWieght;81 const backTestArgsHandler = new BackTestArgsHandler();82 backTestArgsHandler.replaceAllocation(newAllocation);83 backTestArgsHandler.setDateRange(startDate, endDate);84 if (rebalanceType === "none") {85 backTestArgsHandler.setRebalanceDateList([]);86 } else if (rebalanceType === "daily") {87 backTestArgsHandler.setRebalanceDateList(dateList);88 } else if (rebalanceType === "weekly") {89 backTestArgsHandler.setRebalanceDateList(firtDateOfWeek);90 } else if (rebalanceType === "monthly") {91 backTestArgsHandler.setRebalanceDateList(firstDateOfMonth);92 }93 const testArgs = backTestArgsHandler.getArgs();94 const backTest = new BackTest();95 backTest.init(testArgs);96 const backTestArgs = {97 strategyType,98 strategyArg1,99 strategyArg2,100 strategyArg3,101 selectedAsset102 };103 executeBacktest(backTest, backTestArgs);104 backTest.createMetaData();105 const result = backTest.result();106 console.log(result);107 this.setState({ resultList: [...this.state.resultList, { result, name }] });108 };109 // runSimulation2 = (110 // variables,111 // weightsList,112 // name,113 // rebalanceType = "none",114 // strategyType = "none",115 // strategyArg1 = "none",116 // strategyArg2 = "none",117 // strategyArg3 = "none",118 // selectedAsset = "none"119 // ) => {120 // const { startDate, endDate } = variables;121 // const strategy = strategyStore["momentum"];122 // const context = {123 // startDate,124 // endDate,125 // rebalanceType: rebalanceType,126 // taxRate: 0,127 // commissionRate: 0.00015,128 // strategyArgs: {129 // momentumWindow: 80,130 // top: 2131 // }132 // };133 // let backtest = new backTesting(context, strategy);134 // backtest.run();135 // const result = backtest.result();136 // this.setState({ resultList: [...this.state.resultList, { result, name }] });137 // };138 refreshSimulations = (139 variables,140 weightsList,141 name,142 rebalanceType = "none",143 strategyType = "none",144 strategyArg1 = "none",145 strategyArg2 = "none",146 strategyArg3 = "none",147 selectedAsset = "none"148 ) => {149 const { startDate, endDate } = variables;150 let newAllocation = weightsList;151 // EF LINE ì ìí¥ì 미침152 newAllocation = newAllocation.map(value => math.floor(value));153 const remainWieght = 100 - math.sum(newAllocation);154 newAllocation[newAllocation.length - 1] += remainWieght;155 const backTestArgsHandler = new BackTestArgsHandler();156 backTestArgsHandler.replaceAllocation(newAllocation);157 backTestArgsHandler.setDateRange(startDate, endDate);158 if (rebalanceType === "none") {159 backTestArgsHandler.setRebalanceDateList([]);160 } else if (rebalanceType === "daily") {161 backTestArgsHandler.setRebalanceDateList(dateList);162 } else if (rebalanceType === "weekly") {163 backTestArgsHandler.setRebalanceDateList(firtDateOfWeek);164 } else if (rebalanceType === "monthly") {165 backTestArgsHandler.setRebalanceDateList(firstDateOfMonth);166 }167 const testArgs = backTestArgsHandler.getArgs();168 const backTest = new BackTest();169 backTest.init(testArgs);170 const backTestArgs = {171 strategyType,172 strategyArg1,173 strategyArg2,174 strategyArg3,175 selectedAsset176 };177 executeBacktest(backTest, backTestArgs);178 backTest.createMetaData();179 const result = backTest.result();180 return { result, name };181 };182 selectPortfolioHandler = (portName, selectedDate) => {183 this.setState({184 selectedPortfolio: { name: portName, date: selectedDate }185 });186 };187 refreshHandler = variables => {188 const { dataSource } = this.state.dataSource;189 const resultList = this.state.resultList;190 const numOfPreSimulation = resultList.length;191 const newResultList = [];192 for (let i = 0; i < numOfPreSimulation; i++) {193 const data = dataSource[i];194 const weightsList = [];195 assetCodeList.forEach(code => {196 weightsList.push(data[code]);197 });198 weightsList.push(0);199 const {200 name,201 rebalanceType,202 strategyType,203 strategyArg1,204 strategyArg2,205 strategyArg3,206 selectedAsset207 } = data;208 const result = this.refreshSimulations(209 variables,210 weightsList,211 name,212 rebalanceType,213 strategyType,214 strategyArg1,215 strategyArg2,216 strategyArg3,217 selectedAsset218 );219 newResultList.push(result);220 }221 this.setState({222 resultList: newResultList223 });224 };225 setLogScale = () => {226 this.setState({227 logScale: !this.state.logScale228 });229 };230 batchSelection = (column, newValue) => {231 // column ì¢
ë¥ : rebalanceType, strategyType, strategyArg1, strategyArg2, strategyArg3, selectedAsset232 const { dataSource } = this.state.dataSource;233 const newDataSource = dataSource.map(port => {234 port[column] = newValue;235 return port;236 });237 this.setState({238 dataSource: newDataSource239 });240 };241}242const executeBacktest = (backTest, backTestArgs) => {243 const {244 strategyType,245 strategyArg1,246 strategyArg2,247 strategyArg3,248 selectedAsset249 } = backTestArgs;250 if (strategyType === "none") {251 backTest.run();252 } else if (strategyType === "momentum") {253 const simulationArgs = { momentumWindow: strategyArg1 };254 backTest.run2(simulationArgs);255 } else if (strategyType === "momentum2") {256 const simulationArgs = {257 top: strategyArg1,258 momentumWindow: strategyArg2259 };260 backTest.run3(simulationArgs);261 } else if (strategyType === "momentum3") {262 backTest.run4(backTestArgs);263 } else if (strategyType === "momentum4") {264 const momentumWindow = strategyArg1;265 backTest.run5(backTestArgs);266 } else if (strategyType === "momentum5") {267 const topLimit = strategyArg1;268 backTest.run6(topLimit);269 } else if (strategyType === "momentum6") {270 const momentumWindow = strategyArg1;271 const absScore = strategyArg2 / 100;272 backTest.run7(momentumWindow, absScore);273 } else if (strategyType === "momentum7") {274 const topLimit = strategyArg1;275 const momentumWindow = strategyArg2;276 backTest.run8(topLimit, momentumWindow);277 } else if (strategyType === "momentum8") {278 const momentumWindow = strategyArg1;279 const asset = selectedAsset;280 backTest.run9(momentumWindow, asset);281 } else if (strategyType === "momentum9") {282 const momentumWindow = strategyArg1;283 const top = strategyArg2;284 backTest.run10(momentumWindow, top);285 } else if (strategyType === "momentum10") {286 const momentumWindow = strategyArg1;287 backTest.run11(momentumWindow);288 } else if (strategyType === "momentum11") {289 const top = strategyArg1;290 const momentumWindow = strategyArg2;291 backTest.run12(top, momentumWindow);292 } else if (strategyType === "momentum12") {293 const momentumWindow = strategyArg1;294 const top = strategyArg2;295 const stockWeight = strategyArg3;296 const asset = selectedAsset;297 backTest.run13(momentumWindow, top, stockWeight, asset);298 } else if (strategyType === "momentum13") {299 backTest.run14(backTestArgs);300 } else if (strategyType === "momentum14") {301 const momentumWindow = strategyArg1;302 const top = strategyArg2;303 backTest.run15(momentumWindow, top);304 }305};...
snake-naming-strategy.test.ts
Source:snake-naming-strategy.test.ts
1import { SnakeNamingStrategy } from "../../../../packages/core-database/src/utils/snake-naming-strategy";2describe("SnakeNamingStrategy.tableName", () => {3 it("should convert class name to snake-case table name", () => {4 const snakeNamingStrategy = new SnakeNamingStrategy();5 const snakeName = snakeNamingStrategy.tableName("MyClass", "");6 expect(snakeName).toEqual("my_class");7 });8 it("should return custom name if provided", () => {9 const snakeNamingStrategy = new SnakeNamingStrategy();10 const snakeName = snakeNamingStrategy.tableName("MyClass", "MYCLASSTABLE");11 expect(snakeName).toEqual("MYCLASSTABLE");12 });13});14describe("SnakeNamingStrategy.columnName", () => {15 it("should convert class property to snake-case column name", () => {16 const snakeNamingStrategy = new SnakeNamingStrategy();17 const snakeName = snakeNamingStrategy.columnName("myProperty", "", []);18 expect(snakeName).toEqual("my_property");19 });20 it("should return custom name if provided", () => {21 const snakeNamingStrategy = new SnakeNamingStrategy();22 const snakeName = snakeNamingStrategy.columnName("myProperty", "MYPROPERTYCOLUMN", []);23 expect(snakeName).toEqual("MYPROPERTYCOLUMN");24 });25});26describe("SnakeNamingStrategy.relationName", () => {27 it("should convert class property to snake-case column name", () => {28 const snakeNamingStrategy = new SnakeNamingStrategy();29 const snakeName = snakeNamingStrategy.relationName("myProperty");30 expect(snakeName).toEqual("my_property");31 });32});33describe("SnakeNamingStrategy.joinColumnName", () => {34 it("should convert class property to snake-case column name", () => {35 const snakeNamingStrategy = new SnakeNamingStrategy();36 const snakeName = snakeNamingStrategy.joinColumnName("MyClass", "myProperty");37 expect(snakeName).toEqual("my_class_my_property");38 });39});40describe("SnakeNamingStrategy.joinTableName", () => {41 it("should convert class and property to snake-case table name", () => {42 const snakeNamingStrategy = new SnakeNamingStrategy();43 const snakeName = snakeNamingStrategy.joinTableName("MyClass", "MyOtherClass", "myProperty", "myOtherProperty");44 expect(snakeName).toEqual("my_class_my_property__my_other_class");45 });46});47describe("SnakeNamingStrategy.joinTableColumnName", () => {48 it("should convert class and property to snake-case column name", () => {49 const snakeNamingStrategy = new SnakeNamingStrategy();50 const snakeName = snakeNamingStrategy.joinTableColumnName("MyClass", "myProperty", "");51 expect(snakeName).toEqual("my_class_my_property");52 });53 it("should convert class and column to snake-case column name", () => {54 const snakeNamingStrategy = new SnakeNamingStrategy();55 const snakeName = snakeNamingStrategy.joinTableColumnName("MyClass", "myProperty", "my_property_column");56 expect(snakeName).toEqual("my_class_my_property_column");57 });58});59describe("SnakeNamingStrategy.classTableInheritanceParentColumnName", () => {60 it("should convert parent table and column to column name", () => {61 const snakeNamingStrategy = new SnakeNamingStrategy();62 const snakeName = snakeNamingStrategy.classTableInheritanceParentColumnName("my_class", "id");63 expect(snakeName).toEqual("my_class_id");64 });65});66describe("SnakeNamingStrategy.eagerJoinRelationAlias", () => {67 it("should convert property path to alias", () => {68 const snakeNamingStrategy = new SnakeNamingStrategy();69 const snakeName = snakeNamingStrategy.eagerJoinRelationAlias("my_table_alias", "some.property");70 expect(snakeName).toEqual("my_table_alias__some_property");71 });...
bindStrategy.unit.js
Source:bindStrategy.unit.js
1import BindStrategy from 'handsontable-pro/plugins/bindRowsWithHeaders/bindStrategy';2describe('BindRowsWithHeaders -> BindStrategy', () => {3 it('should throw error when used strategy is not exists', () => {4 const strategy = new BindStrategy();5 expect(() => {6 strategy.setStrategy('test2');7 }).toThrow();8 });9 it('should create a map based on `length` argument', () => {10 const strategyMock = { _arrayMap: [] };11 const strategy = new BindStrategy();12 strategy.strategy = strategyMock;13 strategy.createMap(4);14 expect(strategy.strategy._arrayMap[0]).toBe(0);15 expect(strategy.strategy._arrayMap[1]).toBe(1);16 expect(strategy.strategy._arrayMap[2]).toBe(2);17 expect(strategy.strategy._arrayMap[3]).toBe(3);18 expect(strategy.strategy._arrayMap[4]).toBe(void 0);19 });20 it('should re-create a map based on current map length', () => {21 const strategyMock = { _arrayMap: [] };22 const strategy = new BindStrategy();23 strategy.strategy = strategyMock;24 strategy.strategy._arrayMap[0] = 4;25 strategy.strategy._arrayMap[1] = 5;26 strategy.strategy._arrayMap[2] = 6;27 strategy.createMap();28 expect(strategy.strategy._arrayMap[0]).toBe(0);29 expect(strategy.strategy._arrayMap[1]).toBe(1);30 expect(strategy.strategy._arrayMap[2]).toBe(2);31 expect(strategy.strategy._arrayMap[3]).toBe(void 0);32 });33 it('should forward `createRow` method call to the strategy object', () => {34 const strategyMock = { createRow() {} };35 const createRowSpy = jest.spyOn(strategyMock, 'createRow');36 const strategy = new BindStrategy();37 strategy.strategy = { createRow: createRowSpy };38 strategy.createRow(1, 1);39 expect(createRowSpy).toHaveBeenCalledTimes(1);40 expect(createRowSpy).toHaveBeenCalledWith(1, 1);41 strategy.createRow(3);42 expect(createRowSpy).toHaveBeenCalledTimes(2);43 expect(createRowSpy).toHaveBeenCalledWith(3);44 });45 it('should forward `removeRow` method call to the strategy object', () => {46 const strategyMock = { removeRow() {} };47 const removeRowSpy = jest.spyOn(strategyMock, 'removeRow');48 const strategy = new BindStrategy();49 strategy.strategy = { removeRow: removeRowSpy };50 strategy.removeRow(1, 1);51 expect(removeRowSpy).toHaveBeenCalledTimes(1);52 expect(removeRowSpy).toHaveBeenCalledWith(1, 1);53 strategy.removeRow(3);54 expect(removeRowSpy).toHaveBeenCalledTimes(2);55 expect(removeRowSpy).toHaveBeenCalledWith(3);56 });57 it('should forward `translate` method call to the strategy object', () => {58 const strategyMock = { getValueByIndex() {} };59 const getValueByIndexSpy = jest.spyOn(strategyMock, 'getValueByIndex');60 const strategy = new BindStrategy();61 strategy.strategy = { getValueByIndex: getValueByIndexSpy };62 strategy.translate(1);63 expect(getValueByIndexSpy).toHaveBeenCalledTimes(1);64 expect(getValueByIndexSpy).toHaveBeenCalledWith(1);65 });66 it('should forward `clearMap` method call to the strategy object', () => {67 const strategyMock = { clearMap() {} };68 const clearMapSpy = jest.spyOn(strategyMock, 'clearMap');69 const strategy = new BindStrategy();70 strategy.strategy = { clearMap: clearMapSpy };71 strategy.clearMap();72 expect(clearMapSpy).toHaveBeenCalledTimes(1);73 expect(clearMapSpy).toHaveBeenCalledWith();74 });75 it('should destroy object after call `destroy` method', () => {76 const strategyMock = { destroy() {} };77 const destroySpy = jest.spyOn(strategyMock, 'destroy');78 const strategy = new BindStrategy();79 strategy.strategy = { destroy: destroySpy };80 strategy.destroy();81 expect(destroySpy).toHaveBeenCalledTimes(1);82 expect(destroySpy).toHaveBeenCalledWith();83 expect(strategy.strategy).toBeNull();84 });...
backoff_strategy.js
Source:backoff_strategy.js
1/*2 * Copyright (c) 2012 Mathieu Turcotte3 * Licensed under the MIT license.4 */5var sinon = require('sinon');6var util = require('util');7var BackoffStrategy = require('../lib/strategy/strategy');8function SampleBackoffStrategy(options) {9 BackoffStrategy.call(this, options);10}11util.inherits(SampleBackoffStrategy, BackoffStrategy);12SampleBackoffStrategy.prototype.next_ = function() {13 return this.getInitialDelay();14};15SampleBackoffStrategy.prototype.reset_ = function() {};16exports["BackoffStrategy"] = {17 setUp: function(callback) {18 this.random = sinon.stub(Math, 'random');19 callback();20 },21 tearDown: function(callback) {22 this.random.restore();23 callback();24 },25 "the randomisation factor should be between 0 and 1": function(test) {26 test.throws(function() {27 new BackoffStrategy({28 randomisationFactor: -0.129 });30 });31 test.throws(function() {32 new BackoffStrategy({33 randomisationFactor: 1.134 });35 });36 test.doesNotThrow(function() {37 new BackoffStrategy({38 randomisationFactor: 0.539 });40 });41 test.done();42 },43 "the raw delay should be randomized based on the randomisation factor": function(test) {44 var strategy = new SampleBackoffStrategy({45 randomisationFactor: 0.5,46 initialDelay: 100047 });48 this.random.returns(0.5);49 var backoffDelay = strategy.next();50 test.equals(backoffDelay, 1000 + (1000 * 0.5 * 0.5));51 test.done();52 },53 "the initial backoff delay should be greater than 0": function(test) {54 test.throws(function() {55 new BackoffStrategy({56 initialDelay: -157 });58 });59 test.throws(function() {60 new BackoffStrategy({61 initialDelay: 062 });63 });64 test.doesNotThrow(function() {65 new BackoffStrategy({66 initialDelay: 167 });68 });69 test.done();70 },71 "the maximal backoff delay should be greater than 0": function(test) {72 test.throws(function() {73 new BackoffStrategy({74 maxDelay: -175 });76 });77 test.throws(function() {78 new BackoffStrategy({79 maxDelay: 080 });81 });82 test.done();83 },84 "the maximal backoff delay should be greater than the initial backoff delay": function(test) {85 test.throws(function() {86 new BackoffStrategy({87 initialDelay: 10,88 maxDelay: 1089 });90 });91 test.doesNotThrow(function() {92 new BackoffStrategy({93 initialDelay: 10,94 maxDelay: 1195 });96 });97 test.done();98 }...
Using AI Code Generation
1var wpt = require('webpagetest');2var test = new wpt('www.webpagetest.org');3 if (err) return console.error(err);4 console.log(data);5 test.getTestStatus(data.data.testId, function(err, data) {6 if (err) return console.error(err);7 console.log(data);8 });9});10var wpt = require('webpagetest');11var test = new wpt('www.webpagetest.org');12 if (err) return console.error(err);13 console.log(data);14});15var wpt = require('webpagetest');16var test = new wpt('www.webpagetest.org');17test.getTestStatus('140308_6W_1', function(err, data) {18 if (err) return console.error(err);19 console.log(data);20});21var wpt = require('webpagetest');22var test = new wpt('www.webpagetest.org');23test.getTestResults('140308_6W_1', function(err, data) {24 if (err) return console.error(err);25 console.log(data);26});27var wpt = require('webpagetest');28var test = new wpt('www.webpagetest.org');29test.getLocations(function(err, data) {30 if (err) return console.error(err);31 console.log(data);32});33var wpt = require('webpagetest');34var test = new wpt('www.webpagetest.org');35test.getTesters(function(err, data) {36 if (err) return console.error(err);37 console.log(data);38});39var wpt = require('webpagetest');40var test = new wpt('www.webpagetest.org');41test.getTesters(function(err, data) {42 if (
Using AI Code Generation
1const wptoolkit = require('wptoolkit');2const fs = require('fs');3const path = require('path');4const { exec } = require('child_process');5const { promisify } = require('util');6const execAsync = promisify(exec);7const { Strategy } = require('wptoolkit');
Using AI Code Generation
1var wpt = require('wpt');2var WPT = wpt();3WPT.runTest(url, function(err, data) {4 if (err) {5 return console.log(err);6 }7 console.log(data);8});
Using AI Code Generation
1const wpt = require('wptoolkit');2let wpt = new wpt();3let strategy = wpt.strategy;4let strategy = new strategy();5let strategy = new wpt.strategy();6let strategy = new wpt.strategy();7let strategy = new wpt.strategy();8const wpt = require('wptoolkit');9let wpt = new wpt();10let strategy = wpt.strategy;11let strategy = new strategy();12let strategy = new wpt.strategy();13let strategy = new wpt.strategy();14let strategy = new wpt.strategy();15const wpt = require('wptoolkit');16let wpt = new wpt();17let strategy = wpt.strategy;18let strategy = new strategy();19let strategy = new wpt.strategy();20let strategy = new wpt.strategy();21let strategy = new wpt.strategy();
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!