Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
class CSVRowMixIn:
@classmethod
def from_csv_row(cls, csv_row:list, csv_headers:list, **kwargs):
instance = cls.objects.create(**kwargs)
for ix, fieldname in enumerate(csv_headers):
fieldvalue = csv_row[ix]
setattr(instance, fieldname, fieldvalue)
return instance
class ExogenousOrderRecord(Model, CSVRowMixIn):
submitted_file = ForeignKey(ExogenousEventFile, on_delete=models.CASCADE)
arrival_time = models.FloatField()
market_id_in_subsession = models.StringField()
price = models.IntegerField()
time_in_force = models.IntegerField()
buy_sell_indicator = models.StringField()
class ExternalFeedRecord(Model, CSVRowMixIn):
submitted_file = ForeignKey(ExogenousEventFile, on_delete=models.CASCADE)
arrival_time = models.FloatField()
market_id_in_subsession = models.StringField()
e_best_bid = models.IntegerField()
e_best_offer = models.IntegerField()
e_signed_volume = models.FloatField()
def handle_exogenous_event_file(filename, filelike, record_cls, record_type):
both_cooperate_payoff = c(200)
both_defect_payoff = c(100)
class Subsession(BaseSubsession):
pass
class Group(BaseGroup):
def set_payoffs(self):
for p in self.get_players():
p.set_payoff()
class Player(BasePlayer):
decision = models.StringField(
choices=[['Cooperate', 'Cooperate'], ['Defect', 'Defect']],
doc="""This player's decision""",
widget=widgets.RadioSelect,
)
def other_player(self):
return self.get_others_in_group()[0]
def set_payoff(self):
payoff_matrix = dict(
Cooperate=dict(
Cooperate=Constants.both_cooperate_payoff,
Defect=Constants.betrayed_payoff,
),
Defect=dict(
Cooperate=Constants.betray_payoff, Defect=Constants.both_defect_payoff
num_rounds = 1
class Subsession(BaseSubsession):
pass
class Group(BaseGroup):
pass
class Player(BasePlayer):
age = models.IntegerField(label='What is your age?', min=13, max=125)
gender = models.StringField(
choices=[['Male', 'Male'], ['Female', 'Female']],
label='What is your gender?',
widget=widgets.RadioSelect,
)
crt_bat = models.IntegerField(
label='''
A bat and a ball cost 22 dollars in total.
The bat costs 20 dollars more than the ball.
How many dollars does the ball cost?'''
)
crt_widget = models.IntegerField(
label='''
"If it takes 5 machines 5 minutes to make 5 widgets,
how many minutes would it take 100 machines to make 100 widgets?"
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
ready_groups = Constants.groups_ready_key.format(self=self)
pairs[ready_groups] = {g.id: False for g in self.get_groups()}
for k, v in pairs.items():
cache.set(k, v, timeout=None)
from . import market_environments
from django.utils import timezone
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']
class ExogenousEventModelFactory:
@staticmethod
def get_model(event_type_name, market):
if event_type_name == 'investor_arrivals':
return InvestorFactory.get_model(market)
else:
log.warning('no in-memory model for event type %s' % event_type_name)
class ExogenousEventFile(Model):
upload_time = models.DateTimeField(auto_now_add=True)
upload_name = models.StringField()
code = models.CharField(primary_key=True, default=random_chars_8, editable=False,
null=False)
record_type = models.StringField()
class CSVRowMixIn:
@classmethod
def from_csv_row(cls, csv_row:list, csv_headers:list, **kwargs):
instance = cls.objects.create(**kwargs)
for ix, fieldname in enumerate(csv_headers):
fieldvalue = csv_row[ix]
setattr(instance, fieldname, fieldvalue)
return instance
class ExogenousOrderRecord(Model, CSVRowMixIn):
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)
# def set_exchange_host(self):
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)
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)
mismatcher.is_winner = False
else:
matcher.is_winner = False
mismatcher.is_winner = True
for player in [mismatcher, matcher]:
if (
self.subsession.round_number == self.session.vars['paying_round']
and player.is_winner
):
player.payoff = Constants.stakes
else:
player.payoff = c(0)
class Player(BasePlayer):
penny_side = models.StringField(
choices=[['Heads', 'Heads'], ['Tails', 'Tails']], widget=widgets.RadioSelect
)
is_winner = models.BooleanField()
def role(self):
if self.id_in_group == 1:
return 'Mismatcher'
if self.id_in_group == 2:
return 'Matcher'