Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat: stop trading conditions #245

Merged
merged 22 commits into from
Apr 12, 2024
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ packages/valory/protocols/tendermint
.env
.1env
keys.json
keys_json/
leak_report

agent/
Expand Down
19 changes: 10 additions & 9 deletions packages/packages.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,16 @@
"contract/valory/realitio_proxy/0.1.0": "bafybeidx37xzjjmapwacedgzhum6grfzhp5vhouz4zu3pvpgdy5pgb2fr4",
"contract/valory/conditional_tokens/0.1.0": "bafybeigucumqbsk74nj4rpm4p2cpiky4dj6uws7nfmgpimuviaxcamwqnu",
"contract/valory/agent_registry/0.1.0": "bafybeibedc7ehebk3ikr4cowjbvgpxqpu65nforgqmraxqxiq5jv6rboqe",
"contract/valory/service_staking_token/0.1.0": "bafybeibpe24zfvpipaut77tsutmednncjviqeoekxltsndovdz3ugek7bu",
"contract/valory/service_staking_token/0.1.0": "bafybeid44l7qekvkwkvmfl4kcqchnaktttacp7lbx464mzqqs5cnefj35e",
"contract/valory/transfer_nft_condition/0.1.0": "bafybeicgpoag2lymofz3vnen76q7gtig5hzimn32o57php4uerr6t25em4",
"skill/valory/market_manager_abci/0.1.0": "bafybeidygkw7mwhbk3ry3au5c5265vms5eti375v5jthd4be5dfnnoache",
"skill/valory/decision_maker_abci/0.1.0": "bafybeigyrxb6ycg243crte5mmmut2znfhlnc43rqn3mnp3sylvf563teki",
"skill/valory/trader_abci/0.1.0": "bafybeifupwnewnhskanrklryt2vxalc5jkqedr2ywt3ux6fpaugc6kuu6q",
"skill/valory/tx_settlement_multiplexer_abci/0.1.0": "bafybeibl6b5negw35fumbvl6dvcu7dammqmac5x3htapu3p7yf7lkqr73a",
"skill/valory/staking_abci/0.1.0": "bafybeibf565rftitlrlovlvchoe45ng72ctec74fsvrmegp3o4uepu4q2e",
"agent/valory/trader/0.1.0": "bafybeicxc3v3ungi6qindlyayahmngk23xf6carthxilva3jmd3jdkn3mu",
"service/valory/trader/0.1.0": "bafybeibtstpn3x3shp5nujacgbwidmc5nwxdcz55p2qptwufkucnkhgr54"
"skill/valory/decision_maker_abci/0.1.0": "bafybeihl4fyyjj34kvouh3ujmekqm4vsn5eabpfsww7danwyqmfhxxlequ",
"skill/valory/trader_abci/0.1.0": "bafybeiduzcdjahjrxgx4twy4mm6l55kq7skf5g33fmsztqjsw37fzpgmui",
"skill/valory/tx_settlement_multiplexer_abci/0.1.0": "bafybeifmyrqtgp4duq65ag3pnbid2xlgxemefln3mshccs6dnhdtieg4la",
"skill/valory/staking_abci/0.1.0": "bafybeicrp3dbvxcb2wa7kdgpkxu7aqji5fwq6icwcfw7anfcpqv26irsr4",
"skill/valory/check_stop_trading_abci/0.1.0": "bafybeiamwtr56zmm7effymgo7jwgix4nwdbhwjrjix4csrdtlyk3qoky3i",
"agent/valory/trader/0.1.0": "bafybeihfsry4qd7gslcavioe4l6gkxjyhqvhmy6ayih2uxi4fgqav2r3ge",
"service/valory/trader/0.1.0": "bafybeihwwfqhcusr57mxtlottypx7h5qqn7r6zdhmhgtrla5p4ntkfzi7i"
},
"third_party": {
"protocol/open_aea/signing/1.0.0": "bafybeihv62fim3wl2bayavfcg3u5e5cxu3b7brtu4cn5xoxd6lqwachasi",
Expand All @@ -30,7 +31,7 @@
"protocol/valory/ipfs/0.1.0": "bafybeiftxi2qhreewgsc5wevogi7yc5g6hbcbo4uiuaibauhv3nhfcdtvm",
"contract/valory/gnosis_safe_proxy_factory/0.1.0": "bafybeib6podeifufgmawvicm3xyz3uaplbcrsptjzz4unpseh7qtcpar74",
"contract/valory/gnosis_safe/0.1.0": "bafybeibq77mgzhyb23blf2eqmia3kc6io5karedfzhntvpcebeqdzrgyqa",
"contract/valory/mech/0.1.0": "bafybeiejdn3rqqa7smbeiypajy63um7okteimvj6bsud3gezneycmdc6te",
"contract/valory/mech/0.1.0": "bafybeiejkna5d7hllaxm6avsnffxfs6n4nx2lncmjz6iodkt2xhcy3mbva",
"contract/valory/service_registry/0.1.0": "bafybeicbxmbzt757lbmyh6762lrkcrp3oeum6dk3z7pvosixasifsk6xlm",
"contract/valory/multisend/0.1.0": "bafybeig5byt5urg2d2bsecufxe5ql7f4mezg3mekfleeh32nmuusx66p4y",
"contract/valory/erc20/0.1.0": "bafybeigvftdxjgnlsoemst5d57cor36idywk7bwcfj2bjqijxdxo3xpurq",
Expand All @@ -45,6 +46,6 @@
"skill/valory/abstract_round_abci/0.1.0": "bafybeih3enhagoql7kzpeyzzu2scpkif6y3ubakpralfnwxcvxexdyvy5i",
"skill/valory/transaction_settlement_abci/0.1.0": "bafybeigtzlk4uakmd54rxnznorcrstsr52kta474lgrnvx5ovr546vj7sq",
"skill/valory/termination_abci/0.1.0": "bafybeihq6qtbwt6i53ayqym63vhjexkcppy26gguzhhjqywfmiuqghvv44",
"skill/valory/mech_interact_abci/0.1.0": "bafybeig2kvyn52kskydyono5wmjsfwtzeq5pcsrtn7p72rfesjatzwgrnq"
"skill/valory/mech_interact_abci/0.1.0": "bafybeihovtfa2oocrx32pdq2af6ey37om7q7b2gy3kkd3azv6mjrclohsy"
}
}
18 changes: 10 additions & 8 deletions packages/valory/agents/trader/aea-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,13 @@ contracts:
- valory/gnosis_safe_proxy_factory:0.1.0:bafybeib6podeifufgmawvicm3xyz3uaplbcrsptjzz4unpseh7qtcpar74
- valory/service_registry:0.1.0:bafybeicbxmbzt757lbmyh6762lrkcrp3oeum6dk3z7pvosixasifsk6xlm
- valory/market_maker:0.1.0:bafybeihyi42hkmu2knrunfdbunjh6j3ibfrnwj7rmqw7mm7pmerzcwzfiq
- valory/erc20:0.1.0:bafybeigvftdxjgnlsoemst5d57cor36idywk7bwcfj2bjqijxdxo3xpurq
- valory/multisend:0.1.0:bafybeig5byt5urg2d2bsecufxe5ql7f4mezg3mekfleeh32nmuusx66p4y
- valory/mech:0.1.0:bafybeiejdn3rqqa7smbeiypajy63um7okteimvj6bsud3gezneycmdc6te
- valory/mech:0.1.0:bafybeiejkna5d7hllaxm6avsnffxfs6n4nx2lncmjz6iodkt2xhcy3mbva
- valory/conditional_tokens:0.1.0:bafybeigucumqbsk74nj4rpm4p2cpiky4dj6uws7nfmgpimuviaxcamwqnu
- valory/realitio:0.1.0:bafybeic5ie4oodetj4krdogydvbfxg4qggc3matpiflocah626tpevpreq
- valory/realitio_proxy:0.1.0:bafybeidx37xzjjmapwacedgzhum6grfzhp5vhouz4zu3pvpgdy5pgb2fr4
- valory/agent_registry:0.1.0:bafybeibedc7ehebk3ikr4cowjbvgpxqpu65nforgqmraxqxiq5jv6rboqe
- valory/service_staking_token:0.1.0:bafybeibpe24zfvpipaut77tsutmednncjviqeoekxltsndovdz3ugek7bu
- valory/service_staking_token:0.1.0:bafybeid44l7qekvkwkvmfl4kcqchnaktttacp7lbx464mzqqs5cnefj35e
- valory/transfer_nft_condition:0.1.0:bafybeicgpoag2lymofz3vnen76q7gtig5hzimn32o57php4uerr6t25em4
protocols:
- open_aea/signing:1.0.0:bafybeihv62fim3wl2bayavfcg3u5e5cxu3b7brtu4cn5xoxd6lqwachasi
Expand All @@ -44,12 +43,13 @@ skills:
- valory/reset_pause_abci:0.1.0:bafybeidw4mbx3os3hmv7ley7b3g3gja7ydpitr7mxbjpwzxin2mzyt5yam
- valory/termination_abci:0.1.0:bafybeihq6qtbwt6i53ayqym63vhjexkcppy26gguzhhjqywfmiuqghvv44
- valory/transaction_settlement_abci:0.1.0:bafybeigtzlk4uakmd54rxnznorcrstsr52kta474lgrnvx5ovr546vj7sq
- valory/tx_settlement_multiplexer_abci:0.1.0:bafybeibl6b5negw35fumbvl6dvcu7dammqmac5x3htapu3p7yf7lkqr73a
- valory/tx_settlement_multiplexer_abci:0.1.0:bafybeifmyrqtgp4duq65ag3pnbid2xlgxemefln3mshccs6dnhdtieg4la
- valory/market_manager_abci:0.1.0:bafybeidygkw7mwhbk3ry3au5c5265vms5eti375v5jthd4be5dfnnoache
- valory/decision_maker_abci:0.1.0:bafybeigyrxb6ycg243crte5mmmut2znfhlnc43rqn3mnp3sylvf563teki
- valory/trader_abci:0.1.0:bafybeifupwnewnhskanrklryt2vxalc5jkqedr2ywt3ux6fpaugc6kuu6q
- valory/staking_abci:0.1.0:bafybeibf565rftitlrlovlvchoe45ng72ctec74fsvrmegp3o4uepu4q2e
- valory/mech_interact_abci:0.1.0:bafybeig2kvyn52kskydyono5wmjsfwtzeq5pcsrtn7p72rfesjatzwgrnq
- valory/decision_maker_abci:0.1.0:bafybeihl4fyyjj34kvouh3ujmekqm4vsn5eabpfsww7danwyqmfhxxlequ
- valory/trader_abci:0.1.0:bafybeiduzcdjahjrxgx4twy4mm6l55kq7skf5g33fmsztqjsw37fzpgmui
- valory/staking_abci:0.1.0:bafybeicrp3dbvxcb2wa7kdgpkxu7aqji5fwq6icwcfw7anfcpqv26irsr4
- valory/check_stop_trading_abci:0.1.0:bafybeiamwtr56zmm7effymgo7jwgix4nwdbhwjrjix4csrdtlyk3qoky3i
- valory/mech_interact_abci:0.1.0:bafybeihovtfa2oocrx32pdq2af6ey37om7q7b2gy3kkd3azv6mjrclohsy
customs:
- valory/mike_strat:0.1.0:bafybeihjiol7f4ch4piwfikurdtfwzsh6qydkbsztpbwbwb2yrqdqf726m
- valory/bet_amount_per_threshold:0.1.0:bafybeihufqu2ra7vud4h6g2nwahx7mvdido7ff6prwnib2tdlc4np7dw24
Expand Down Expand Up @@ -213,6 +213,8 @@ models:
"0x0000000000000000000000000000000000000000"], ["order_address", "0xc7751eff5396a846e7bc83ac31d3cb7d37cb49e4"],
["price", "1000000000000000000"]]}
staking_contract_address: ${str:0x2Ef503950Be67a98746F484DA0bBAdA339DF3326}
disable_trading: ${bool:false}
stop_trading_if_staking_kpi_met: ${bool:true}
agent_balance_threshold: ${int:10000000000000000}
refill_check_interval: ${int:10}
tool_punishment_multiplier: ${int:1}
Expand Down
22 changes: 22 additions & 0 deletions packages/valory/contracts/service_staking_token/contract.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,28 @@ def get_next_checkpoint_ts(
ts = contract.functions.getNextRewardCheckpointTimestamp().call()
return dict(data=ts)

@classmethod
def ts_checkpoint(
cls,
ledger_api: LedgerApi,
contract_address: str,
) -> JSONLike:
"""Retrieve the checkpoint's timestamp."""
contract = cls.get_instance(ledger_api, contract_address)
ts_checkpoint = contract.functions.tsCheckpoint().call()
return dict(data=ts_checkpoint)

@classmethod
def liveness_ratio(
cls,
ledger_api: LedgerApi,
contract_address: str,
) -> JSONLike:
"""Retrieve the liveness ratio."""
contract = cls.get_instance(ledger_api, contract_address)
liveness_ratio = contract.functions.livenessRatio().call()
return dict(data=liveness_ratio)

@classmethod
def get_liveness_period(
cls,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ aea_version: '>=1.0.0, <2.0.0'
fingerprint:
__init__.py: bafybeid3wfzglolebuo6jrrsopswzu4lk77bm76mvw3euizlsjtnt3wmgu
build/ServiceStakingToken.json: bafybeib6frfpqtr4dfyxuylehqmic2iawofydx7u24t7j5zbrsc4m4ijoi
contract.py: bafybeicxwbqmiohfmbikc76cxlt5sext6ly2wmvemysr53alnp5qjq6jmm
contract.py: bafybeihtnccnhtqyiwqomythtuey6vdbsj5swufxl5pcu3ptepmiaolxy4
fingerprint_ignore_patterns: []
contracts: []
class_name: ServiceStakingTokenContract
Expand Down
12 changes: 7 additions & 5 deletions packages/valory/services/trader/service.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ license: Apache-2.0
fingerprint:
README.md: bafybeigtuothskwyvrhfosps2bu6suauycolj67dpuxqvnicdrdu7yhtvq
fingerprint_ignore_patterns: []
agent: valory/trader:0.1.0:bafybeicxc3v3ungi6qindlyayahmngk23xf6carthxilva3jmd3jdkn3mu
agent: valory/trader:0.1.0:bafybeihfsry4qd7gslcavioe4l6gkxjyhqvhmy6ayih2uxi4fgqav2r3ge
number_of_agents: 4
deployment: {}
---
Expand Down Expand Up @@ -79,7 +79,7 @@ type: skill
languages: ${LANGUAGES:list:["en_US"]}
average_block_time: ${ABT:int:5}
abt_error_mult: ${ABT_ERROR_MULT:int:5}
mech_contract_address: ${MECH_CONTRACT_ADDRESS:str:0x77af31de935740567cf4ff1986d04b2c964a786a}
mech_contract_address: ${MECH_CONTRACT_ADDRESS:str:0x77af31De935740567Cf4fF1986D04B2c964A786a}
request_price: ${REQUEST_PRICE:int:null}
sample_bets_closing_days: ${SAMPLE_BETS_CLOSING_DAYS:int:10}
trading_strategy: ${TRADING_STRATEGY:str:kelly_criterion}
Expand Down Expand Up @@ -108,6 +108,8 @@ type: skill
"stabilityai-stable-diffusion-xl-beta-v2-2-2", "stabilityai-stable-diffusion-512-v2-1",
"stabilityai-stable-diffusion-768-v2-1"]}
staking_contract_address: ${STAKING_CONTRACT_ADDRESS:str:0x2Ef503950Be67a98746F484DA0bBAdA339DF3326}
disable_trading: ${DISABLE_TRADING:bool:false}
stop_trading_if_staking_kpi_met: ${STOP_TRADING_IF_STAKING_KPI_MET:bool:true}
agent_balance_threshold: ${AGENT_BALANCE_THRESHOLD:int:10000000000000000}
refill_check_interval: ${REFILL_CHECK_INTERVAL:int:10}
tool_punishment_multiplier: ${TOOL_PUNISHMENT_MULTIPLIER:int:1}
Expand Down Expand Up @@ -176,7 +178,7 @@ type: skill
languages: ${LANGUAGES:list:["en_US"]}
average_block_time: ${ABT:int:5}
abt_error_mult: ${ABT_ERROR_MULT:int:5}
mech_contract_address: ${MECH_CONTRACT_ADDRESS:str:0x77af31de935740567cf4ff1986d04b2c964a786a}
mech_contract_address: ${MECH_CONTRACT_ADDRESS:str:0x77af31De935740567Cf4fF1986D04B2c964A786a}
request_price: ${REQUEST_PRICE:int:null}
sample_bets_closing_days: ${SAMPLE_BETS_CLOSING_DAYS:int:10}
trading_strategy: ${TRADING_STRATEGY:str:kelly_criterion}
Expand Down Expand Up @@ -271,7 +273,7 @@ type: skill
languages: ${LANGUAGES:list:["en_US"]}
average_block_time: ${ABT:int:5}
abt_error_mult: ${ABT_ERROR_MULT:int:5}
mech_contract_address: ${MECH_CONTRACT_ADDRESS:str:0x77af31de935740567cf4ff1986d04b2c964a786a}
mech_contract_address: ${MECH_CONTRACT_ADDRESS:str:0x77af31De935740567Cf4fF1986D04B2c964A786a}
request_price: ${REQUEST_PRICE:int:null}
sample_bets_closing_days: ${SAMPLE_BETS_CLOSING_DAYS:int:10}
trading_strategy: ${TRADING_STRATEGY:str:kelly_criterion}
Expand Down Expand Up @@ -366,7 +368,7 @@ type: skill
languages: ${LANGUAGES:list:["en_US"]}
average_block_time: ${ABT:int:5}
abt_error_mult: ${ABT_ERROR_MULT:int:5}
mech_contract_address: ${MECH_CONTRACT_ADDRESS:str:0x77af31de935740567cf4ff1986d04b2c964a786a}
mech_contract_address: ${MECH_CONTRACT_ADDRESS:str:0x77af31De935740567Cf4fF1986D04B2c964A786a}
request_price: ${REQUEST_PRICE:int:null}
sample_bets_closing_days: ${SAMPLE_BETS_CLOSING_DAYS:int:10}
trading_strategy: ${TRADING_STRATEGY:str:kelly_criterion}
Expand Down
5 changes: 5 additions & 0 deletions packages/valory/skills/check_stop_trading_abci/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Check stop trading abci

## Description

This module contains the check stop trading skill for an AEA.
jmoreira-valory marked this conversation as resolved.
Show resolved Hide resolved
25 changes: 25 additions & 0 deletions packages/valory/skills/check_stop_trading_abci/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
#
# Copyright 2024 Valory AG
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# ------------------------------------------------------------------------------

"""This module contains the check stop trading skill for an AEA."""

from aea.configurations.base import PublicId


PUBLIC_ID = PublicId.from_str("valory/check_stop_trading_abci:0.1.0")
156 changes: 156 additions & 0 deletions packages/valory/skills/check_stop_trading_abci/behaviours.py
jmoreira-valory marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
#
# Copyright 2024 Valory AG
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# ------------------------------------------------------------------------------

"""This module contains the behaviours for the check stop trading skill."""

import math
from typing import Any, Generator, Set, Type, cast

from packages.valory.contracts.mech.contract import Mech as MechContract
from packages.valory.skills.abstract_round_abci.base import get_name
from packages.valory.skills.abstract_round_abci.behaviour_utils import BaseBehaviour
from packages.valory.skills.abstract_round_abci.behaviours import AbstractRoundBehaviour
from packages.valory.skills.check_stop_trading_abci.models import CheckStopTradingParams
from packages.valory.skills.check_stop_trading_abci.payloads import CheckStopTradingPayload
from packages.valory.skills.check_stop_trading_abci.rounds import (
CheckStopTradingRound,
CheckStopTradingAbciApp,
)
from packages.valory.skills.staking_abci.behaviours import (
StakingInteractBaseBehaviour,
WaitableConditionType,
)


class CheckStopTradingBehaviour(StakingInteractBaseBehaviour):
"""A behaviour that checks stop trading conditions."""

matching_round = CheckStopTradingRound

def __init__(self, **kwargs: Any) -> None:
"""Initialize the behaviour."""
super().__init__(**kwargs)

@property
def mech_request_count(self) -> int:
"""Get the liveness period."""
return self._mech_request_count

@mech_request_count.setter
def mech_request_count(self, mech_request_count: int) -> None:
"""Set the liveness period."""
self._mech_request_count = mech_request_count

def _get_mech_request_count(self) -> WaitableConditionType:
"""Get the mech request count."""
status = yield from self.contract_interact(
contract_address=self.params.mech_contract_address,
contract_public_id=MechContract.contract_id,
contract_callable="get_requests_count",
data_key="requests_count",
placeholder=get_name(CheckStopTradingBehaviour.mech_request_count),
address=self.synchronized_data.safe_contract_address,
)
return status

@property
def is_first_period(self) -> bool:
"""Return whether it is the first period of the service."""
return self.synchronized_data.period_count == 0

@property
def params(self) -> CheckStopTradingParams:
"""Return the params."""
return cast(CheckStopTradingParams, self.context.params)

def is_staking_kpi_met(self) -> WaitableConditionType:
Adamantios marked this conversation as resolved.
Show resolved Hide resolved
"""Return whether the staking KPI has been met."""

yield from self.wait_for_condition_with_sleep(self._get_mech_request_count)
mech_request_count = self.mech_request_count
self.context.logger.info(f"{self.mech_request_count=}")

yield from self.wait_for_condition_with_sleep(self._get_service_info)
mech_request_count_on_last_checkpoint = self.service_info[2][1]
self.context.logger.info(f"{mech_request_count_on_last_checkpoint=}")

yield from self.wait_for_condition_with_sleep(self._get_ts_checkpoint)
last_ts_checkpoint = self.ts_checkpoint
self.context.logger.info(f"{last_ts_checkpoint=}")

yield from self.wait_for_condition_with_sleep(self._get_liveness_period)
liveness_period = self.liveness_period
self.context.logger.info(f"{liveness_period=}")

yield from self.wait_for_condition_with_sleep(self._get_liveness_ratio)
liveness_ratio = self.liveness_ratio
self.context.logger.info(f"{liveness_ratio=}")

mech_requests_since_last_cp = mech_request_count - mech_request_count_on_last_checkpoint
self.context.logger.info(f"{mech_requests_since_last_cp=}")

current_timestamp = self.synced_timestamp
self.context.logger.info(f"{current_timestamp=}")

required_mech_requests = math.ceil(max(
(current_timestamp - last_ts_checkpoint) * liveness_ratio / 10**18,
(liveness_period) * liveness_ratio / 10**18
)) + 1
Adamantios marked this conversation as resolved.
Show resolved Hide resolved
jmoreira-valory marked this conversation as resolved.
Show resolved Hide resolved
self.context.logger.info(f"{required_mech_requests=}")

if mech_requests_since_last_cp >= required_mech_requests:
return True
return False

def async_act(self) -> Generator:
"""Do the action."""
with self.context.benchmark_tool.measure(self.behaviour_id).local():

# This is a "hacky" way of getting required data initialized on
# the Trader: On first period, the FSM needs to initialize some
# data on the trading branch so that it is available in the
# cross-period persistent keys.
if self.is_first_period:
stop_trading = False
jmoreira-valory marked this conversation as resolved.
Show resolved Hide resolved
else:
disable_trading = self.params.disable_trading
self.context.logger.info(f"{disable_trading=}")

staking_kpi_met = yield from self.is_staking_kpi_met()
self.context.logger.info(f"{staking_kpi_met=}")

stop_trading = any([disable_trading, staking_kpi_met])

self.context.logger.info(f"{stop_trading=}")
payload = CheckStopTradingPayload(
self.context.agent_address, stop_trading
)

with self.context.benchmark_tool.measure(self.behaviour_id).consensus():
yield from self.send_a2a_transaction(payload)
yield from self.wait_until_round_end()
self.set_done()


class CheckStopTradingRoundBehaviour(AbstractRoundBehaviour):
"""This behaviour manages the consensus stages for the check stop trading behaviour."""

initial_behaviour_cls = CheckStopTradingBehaviour
abci_app_cls = CheckStopTradingAbciApp
behaviours: Set[Type[BaseBehaviour]] = {CheckStopTradingBehaviour} # type: ignore
Loading
Loading