Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
from otree.api import models
from otree.db.models import Model, ForeignKey
from . import market_environments
from django.utils import timezone
import logging
log = logging.getLogger(__name__)
class TimeAwareInSessionRecord(Model):
timestamp = models.DateTimeField(default=timezone.now)
trigger_event_type = models.CharField()
event_no = models.IntegerField()
subsession_id = models.IntegerField()
market_id = models.IntegerField()
class TraderRecord(TimeAwareInSessionRecord):
csv_meta = (
'timestamp', 'subsession_id', 'market_id', 'player_id', 'trigger_event_type',
'event_no', 'trader_model_name', 'inventory', 'bid', 'offer',
'best_bid_except_me', 'best_offer_except_me',
'delay', 'staged_bid', 'staged_offer', 'implied_bid',
'implied_offer', 'slider_a_x','slider_a_y', 'slider_a_z',
'net_worth', 'cash', 'tax_paid', 'speed_cost', 'midpoint_peg', 'peg_price', 'peg_state')
# timestamp = models.DateTimeField(default=timezone.now)
json_fields = {}
for field in self._meta.get_fields():
if isinstance(field, JSONField):
json_fields[field.attname] = getattr(self, field.attname)
self.__class__._default_manager.filter(pk=self.pk).update(**json_fields)
class Group(BaseGroup):
pass
class Player(BasePlayer):
channel = models.CharField(max_length=255)
consented = models.BooleanField(initial=False)
exchange_host = models.CharField()
exchange_port = models.IntegerField()
# subsession_id = models.CharField()
market_id = models.CharField()
id_in_market = models.IntegerField()
speed_unit_cost = models.IntegerField()
net_worth = models.IntegerField()
cash = models.IntegerField()
cost = models.IntegerField()
speed_cost = models.IntegerField()
tax_paid = models.IntegerField()
reference_price = models.IntegerField()
inventory = models.IntegerField()
bid = models.IntegerField()
offer = models.IntegerField()
staged_bid = models.IntegerField()
staged_offer = models.IntegerField()
'survey_fields': [ # we define two forms here ...
{ # ... this one is shown when player.treatment == 1 ...
'form_name': 'treatment_1_form',
'fields': [
('q_treatment_1', {
'text': 'This is a question for treatment 1: Do you feel tired?',
'field': models.CharField(choices=YESNO_CHOICES, blank=True),
}),
]
},
{ # ... this one is shown when player.treatment == 2 ...
'form_name': 'treatment_2_form', # optional, can be used for CSS styling
'fields': [
('q_treatment_2', {
'text': "This is a question for treatment 2: Don't you feel tired?",
'field': models.CharField(choices=YESNO_CHOICES, blank=True),
}),
]
},
]
},
{
'page_title': 'Survey Questions - Page 6 - Conditional fields and widget adjustments',
'form_help_initial': """
<p>Conditional fields can be made with the <code>condition_javascript</code> parameter,
widget adjustments like custom CSS styles can be controlled via <code>widget_attrs</code>.</p>""",
'survey_fields': [
('q_uses_ebay', {
'text': 'Do you sell things on eBay?',
'field': models.CharField(choices=YESNO_CHOICES),
}),
('q_ebay_member_years', {
from .dispatcher import DispatcherFactory
log = logging.getLogger(__name__)
class Constants(BaseConstants):
name_in_url = 'hft'
players_per_group = None
num_rounds = 3
class Subsession(BaseSubsession):
model_name = models.StringField(initial='subsession')
auction_format = models.StringField()
session_duration = models.IntegerField()
batch_length = models.IntegerField(initial=0)
code = models.CharField(default=random_chars_8)
def creating_session(self):
def create_trade_session(session_format):
trade_session_cls = TradeSessionFactory.get_session(session_format)
dispatcher = DispatcherFactory.get_dispatcher(session_format)
trade_session = trade_session_cls(self, session_format, dispatcher)
environment = market_environments.environments[session_format]
for event_type in environment.exogenous_events:
event_filename = self.session.config[event_type].pop(0)
trade_session.register_exogenous_event(
event_type, event_filename)
return trade_session
session_format = self.session.config['environment']
if self.round_number == 1:
self.session.config = utility.process_configs(
session_format, self.session.config)
try:
process.kill()
except Exception as e:
log.exception(e)
class Subsession(BaseSubsession):
design = models.StringField()
next_available_exchange = models.IntegerField()
players_per_group = models.IntegerField()
round_length = models.IntegerField()
batch_length = models.IntegerField(initial=0)
trade_ended = models.BooleanField(initial=False)
code = models.CharField(default=random_chars_8)
has_trial = models.BooleanField(initial=True)
is_trial = models.BooleanField(initial=False)
trial_length = models.IntegerField(initial=0)
log_file = models.StringField()
first_round = models.IntegerField(initial=1)
last_round = models.IntegerField(initial=0)
total_rounds = models.IntegerField(initial=0)
restore_from = models.CharField()
restore = models.BooleanField(initial=False)
lambda_i = models.FloatField()
lambda_j = models.FloatField()
def init_cache(self):
pairs = {}
session_lock = Constants.lock_key.format(self=self)
pairs[session_lock] = Constants.unlock_value
super().save(*args, **kwargs)
if self.pk is not None:
json_fields = {}
for field in self._meta.get_fields():
if isinstance(field, JSONField):
json_fields[field.attname] = getattr(self, field.attname)
self.__class__._default_manager.filter(pk=self.pk).update(**json_fields)
class Group(BaseGroup):
pass
class Player(BasePlayer):
channel = models.CharField(max_length=255)
consented = models.BooleanField(initial=False)
exchange_host = models.CharField()
exchange_port = models.IntegerField()
# subsession_id = models.CharField()
market_id = models.CharField()
id_in_market = models.IntegerField()
speed_unit_cost = models.IntegerField()
net_worth = models.IntegerField()
cash = models.IntegerField()
cost = models.IntegerField()
speed_cost = models.IntegerField()
tax_paid = models.IntegerField()
reference_price = models.IntegerField()
inventory = models.IntegerField()
bid = models.IntegerField()
offer = models.IntegerField()
# basic state variables
role = models.StringField(initial='OUT')
speed = models.BooleanField(initial=False)
spread = models.IntegerField()
channel = models.CharField(max_length=255)
cost = models.IntegerField(initial=0)
fp = models.IntegerField()
endowment = models.IntegerField()
prev_speed_update = models.BigIntegerField(initial=0)
speed_on = models.IntegerField(initial=0)
speed_unit_cost = models.IntegerField()
max_spread = models.IntegerField()
code = models.CharField(default=random_chars_8)
log_file = models.StringField()
design = models.CharField()
consent = models.BooleanField(initial=True)
final_payoff = models.IntegerField()
total_payoff = models.IntegerField()
def init_cache(self):
pairs = {}
lock_key = Constants.lock_key.format(self=self)
pairs[lock_key] = Constants.unlock_value
orderstore_key = Constants.player_orderstore_key.format(self=self)
pairs[orderstore_key] = OrderStore(self.id, self.id_in_group)
state_key = Constants.player_status_key.format(self=self)
role_key = Constants.player_role_key.format(self=self)
pairs[role_key] = self.role.lower()
kwargs = {k: getattr(self, k, None) for k in Constants.player_fields}
exchange_address = '{}:{}'.format(self.group.exch_host, self.group.exch_port)
kwargs.update({'exchange_address':exchange_address, 'group_id': self.group.id})
json_fields = {}
for field in self._meta.get_fields():
if isinstance(field, JSONField):
json_fields[field.attname] = getattr(self, field.attname)
self.__class__._default_manager.filter(pk=self.pk).update(**json_fields)
translator = new_translator.Translator()
class Group(BaseGroup):
exch_host = models.StringField()
exch_port = models.IntegerField()
investor_file = models.StringField()
jump_file = models.StringField()
is_trading = models.BooleanField(initial=False)
code = models.CharField(default=random_chars_8)
log_file = models.StringField()
def init_cache(self):
pairs = {}
group_lock = Constants.lock_key.format(self=self)
pairs[group_lock] = Constants.unlock_value
in_market_key= Constants.players_in_market_key.format(self=self)
pairs[in_market_key] = {p.id: False for p in self.get_players()}
role_count_key = Constants.role_count_key.format(self=self)
pairs[role_count_key] = {k: getattr(self.subsession, v) if isinstance(v, str) else v
for k, v in Constants.group_role_counts.items()}
for k, v in pairs.items():
cache.set(k, v, timeout=None)
)
if total != ppg:
raise ValueError('total: %d, ppg: %d' % (total, ppg))
def loggy(self):
log_events.convert()
log_events.dump()
class Player(BasePlayer):
# basic state variables
role = models.StringField(initial='OUT')
speed = models.BooleanField(initial=False)
spread = models.IntegerField()
channel = models.CharField(max_length=255)
cost = models.IntegerField(initial=0)
fp = models.IntegerField()
endowment = models.IntegerField()
prev_speed_update = models.BigIntegerField(initial=0)
speed_on = models.IntegerField(initial=0)
speed_unit_cost = models.IntegerField()
max_spread = models.IntegerField()
code = models.CharField(default=random_chars_8)
log_file = models.StringField()
design = models.CharField()
consent = models.BooleanField(initial=True)
final_payoff = models.IntegerField()
total_payoff = models.IntegerField()
def init_cache(self):
pairs = {}
csv_meta = (
'timestamp', 'subsession_id', 'market_id', 'player_id', 'trigger_event_type',
'event_no', 'trader_model_name', 'inventory', 'bid', 'offer',
'best_bid_except_me', 'best_offer_except_me',
'delay', 'staged_bid', 'staged_offer', 'implied_bid',
'implied_offer', 'slider_a_x','slider_a_y', 'slider_a_z',
'net_worth', 'cash', 'tax_paid', 'speed_cost', 'midpoint_peg', 'peg_price', 'peg_state')
# timestamp = models.DateTimeField(default=timezone.now)
# trigger_event_type = models.CharField()
# event_no = models.IntegerField()
# subsession_id = models.IntegerField()
# market_id = models.IntegerField()
player_id = models.IntegerField()
trader_model_name = models.CharField()
delay = models.FloatField()
net_worth = models.IntegerField()
cash = models.IntegerField()
cost = models.IntegerField()
speed_cost = models.IntegerField()
tax_paid = models.IntegerField()
reference_price = models.IntegerField()
inventory = models.IntegerField()
bid = models.IntegerField()
offer = models.IntegerField()
staged_bid = models.IntegerField()
staged_offer = models.IntegerField()
implied_bid = models.IntegerField()
implied_offer = models.IntegerField()
best_bid = models.IntegerField()
best_offer = models.IntegerField()