Best JavaScript code snippet using devicefarmer-stf
ctaEngine.py
Source:ctaEngine.py
...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) ...
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
1test = {2 'name': 'Question 10',3 'points': 1,4 'suites': [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
...12from 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():...
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
...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 Strategy = require('devicefarmer-stf-client').Strategy;2var stf = new Strategy();3var Strategy = require('devicefarmer-stf-client').Strategy;4var stf = new Strategy();5var Strategy = require('devicefarmer-stf-client').Strategy;6var stf = new Strategy();7var Strategy = require('devicefarmer-stf-client').Strategy;8var stf = new Strategy();9var Strategy = require('devicefarmer-stf-client').Strategy;10var stf = new Strategy();11var Strategy = require('devicefarmer-stf-client').Strategy;12var stf = new Strategy();13var Strategy = require('devicefarmer-stf-client').Strategy;14var stf = new Strategy();15var Strategy = require('devicefarmer-stf-client').Strategy;16var stf = new Strategy();17var Strategy = require('devicefarmer-stf-client').Strategy;18var stf = new Strategy();19var Strategy = require('devicefarmer-stf-client').Strategy;20var stf = new Strategy();21var Strategy = require('devicefarmer-stf-client').Strategy;22var stf = new Strategy();23var Strategy = require('devicefarmer-stf-client').Strategy;24var stf = new Strategy();25var Strategy = require('devicefarmer-stf-client').Strategy;26var stf = new Strategy();27var Strategy = require('devicefarmer-stf-client').Strategy;28var stf = new Strategy();29var Strategy = require('devicefar
Using AI Code Generation
1var Strategy = require('devicefarmer-stf').Strategy;2var strategy = new Strategy({3});4strategy.getDevices(function(err, devices) {5 if (err) {6 console.error(err);7 return;8 }9 console.log('Devices: %j', devices);10});11var Strategy = require('devicefarmer-stf').Strategy;12var strategy = new Strategy({13});14strategy.getDevices(function(err, devices) {15 if (err) {16 console.error(err);17 return;18 }19 console.log('Devices: %j', devices);20});21var Strategy = require('devicefarmer-stf').Strategy;22var strategy = new Strategy({23});24strategy.getDevices(function(err, devices) {25 if (err) {26 console.error(err);27 return;28 }29 console.log('Devices: %j', devices);30});31var Strategy = require('devicefarmer-stf').Strategy;32var strategy = new Strategy({33});34strategy.getDevices(function(err, devices) {35 if (err) {36 console.error(err);37 return;38 }39 console.log('Devices: %j', devices);40});41var Strategy = require('devicefarmer-stf').Strategy;42var strategy = new Strategy({43});44strategy.getDevices(function(err, devices) {45 if (err) {46 console.error(err);47 return;48 }49 console.log('Devices: %j', devices);50});51var Strategy = require('devicefarmer-stf').Strategy;52var strategy = new Strategy({53});54strategy.getDevices(function(err, devices) {55 if (err) {56 console.error(err);57 return;58 }59 console.log('Devices: %j', devices);60});
Using AI Code Generation
1var DeviceFarmer = require('devicefarmer-stf-client');2var Strategy = DeviceFarmer.Strategy;3var util = require('util');4var EventEmitter = require('events').EventEmitter;5function Test() {6 var self = this;7 var strategy = new Strategy(stf);8 strategy.on('device', function(device){9 console.log('Device connected');10 device.on('disconnect', function(){11 console.log('Device disconnected');12 self.emit('done');13 });14 device.on('error', function(err){15 console.log('Device error: ' + err);16 self.emit('done');17 });18 device.on('log', function(log){19 console.log('Device log: ' + log);20 });21 device.on('message', function(msg){22 console.log('Device message: ' + msg);23 });24 device.on('ready', function(){25 console.log('Device ready');26 device.startScreenStream(function(err, stream){27 if(err) {28 console.log('Error starting screen stream: ' + err);29 self.emit('done');30 } else {31 stream.on('error', function(err){32 console.log('Error in screen stream: ' + err);33 self.emit('done');34 });35 stream.on('end', function(){36 console.log('Screen stream ended');37 self.emit('done');38 });39 stream.on('data', function(data){40 console.log('Screen stream data: ' + data.length);41 });42 }43 });44 });45 });46 strategy.on('error', function(err){47 console.log('Strategy error: ' + err);48 self.emit('done');49 });50 strategy.on('log', function(log){51 console.log('Strategy log: ' + log);52 });53 strategy.on('message', function(msg){54 console.log('Strategy message: ' + msg);55 });56 strategy.on('ready', function(){57 console.log('Strategy ready');58 });59 strategy.start();60}61util.inherits(Test, EventEmitter);62var test = new Test();63test.on('done', function(){64 console.log('Done');65});
Using AI Code Generation
1var Strategy = require('devicefarmer-stf').Strategy;2var strategy = new Strategy();3strategy.on('device', function(device) {4 console.log('device', device);5});6strategy.on('deviceLost', function(device) {7 console.log('deviceLost', device);8});9strategy.start();10var Strategy = require('devicefarmer-stf').Strategy;11var strategy = new Strategy();12strategy.on('device', function(device) {13 console.log('device', device);14});15strategy.on('deviceLost', function(device) {16 console.log('deviceLost', device);17});18strategy.start();19var Strategy = require('devicefarmer-stf').Strategy;20var strategy = new Strategy();21strategy.on('device', function(device) {22 console.log('device', device);23});24strategy.on('deviceLost', function(device) {25 console.log('deviceLost', device);26});27strategy.start();28var Strategy = require('devicefarmer-stf').Strategy;29var strategy = new Strategy();30strategy.on('device', function(device) {31 console.log('device', device);32});33strategy.on('deviceLost', function(device) {34 console.log('deviceLost', device);35});36strategy.start();37var Strategy = require('devicefarmer-stf').Strategy;38var strategy = new Strategy();39strategy.on('device', function(device) {40 console.log('device', device);41});42strategy.on('deviceLost', function(device) {43 console.log('deviceLost', device);44});45strategy.start();46var Strategy = require('devicefarmer-stf').Strategy;47var strategy = new Strategy();48strategy.on('device', function(device) {49 console.log('device', device);50});
Using AI Code Generation
1var Strategy = require('devicefarmer-stf').Strategy;2strategy.getDevices(function (err, devices) {3 console.log(devices);4});5var Strategy = require('devicefarmer-stf').Strategy;6strategy.getDevices(function (err, devices) {7 console.log(devices);8});9var Strategy = require('devicefarmer-stf').Strategy;10strategy.getDevices(function (err, devices) {11 console.log(devices);12});13var Strategy = require('devicefarmer-stf').Strategy;14strategy.getDevices(function (err, devices) {15 console.log(devices);16});17var Strategy = require('devicefarmer-stf').Strategy;18strategy.getDevices(function (err, devices) {19 console.log(devices);20});21var Strategy = require('devicefarmer-stf').Strategy;22strategy.getDevices(function (err, devices) {23 console.log(devices);24});25var Strategy = require('devicefarmer-stf').Strategy;26strategy.getDevices(function (err, devices) {27 console.log(devices);28});29var Strategy = require('devicefarmer-stf').Strategy;30strategy.getDevices(function (err, devices) {31 console.log(devices);32});33var Strategy = require('devicefarmer-stf').Strategy;
Using AI Code Generation
1var DeviceFarmer = require('devicefarmer-stf-client');2var Strategy = DeviceFarmer.Strategy;3var strategy = new Strategy();4var device = strategy.getDevice();5var DeviceFarmer = require('devicefarmer-stf-client');6var Device = DeviceFarmer.Device;7var device = new Device();8device.getDevice();9getDevice()10getDevice()11getDeviceDetails()12getDeviceStatus()13getDeviceScreenshot()14getDeviceLog()15getDeviceLogcat()16getDeviceProviders()17getDeviceUsage()18getDeviceBrowser()19getDeviceContacts()20getDeviceLocation()21getDeviceNetwork()22getDeviceNotification()23getDeviceSettings()24getDeviceStorage()25getDeviceTelephony()26getDevicePower()27getDeviceVideo()28getDeviceRotation()29getDeviceInput()30getDeviceFile()31getDeviceShell()
Using AI Code Generation
1var Strategy = require('devicefarmer-stf').Strategy;2var strategy = new Strategy();3strategy.start();4strategy.on('device', function(device) {5 console.log('Device connected: ' + device.serial);6 device.on('disconnect', function() {7 console.log('Device disconnected: ' + device.serial);8 });9});
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!!