code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def data_prediction_fn(self, x, t):
"""
Return the data prediction model (with thresholding).
"""
noise = self.noise_prediction_fn(x, t)
dims = x.dim()
alpha_t, sigma_t = self.noise_schedule.marginal_alpha(t), self.noise_schedule.marginal_std(t)
x0 = (x - expand_d... |
Return the data prediction model (with thresholding).
| data_prediction_fn | python | ali-vilab/videocomposer | artist/ops/dpm_solver.py | https://github.com/ali-vilab/videocomposer/blob/master/artist/ops/dpm_solver.py | MIT |
def model_fn(self, x, t):
"""
Convert the model to the noise prediction model or the data prediction model.
"""
if self.algorithm_type == "dpmsolver++":
return self.data_prediction_fn(x, t)
else:
return self.noise_prediction_fn(x, t) |
Convert the model to the noise prediction model or the data prediction model.
| model_fn | python | ali-vilab/videocomposer | artist/ops/dpm_solver.py | https://github.com/ali-vilab/videocomposer/blob/master/artist/ops/dpm_solver.py | MIT |
def get_time_steps(self, skip_type, t_T, t_0, N, device):
"""Compute the intermediate time steps for sampling.
Args:
skip_type: A `str`. The type for the spacing of the time steps. We support three types:
- 'logSNR': uniform logSNR for the time steps.
- 'time... | Compute the intermediate time steps for sampling.
Args:
skip_type: A `str`. The type for the spacing of the time steps. We support three types:
- 'logSNR': uniform logSNR for the time steps.
- 'time_uniform': uniform time for the time steps. (**Recommended for high-r... | get_time_steps | python | ali-vilab/videocomposer | artist/ops/dpm_solver.py | https://github.com/ali-vilab/videocomposer/blob/master/artist/ops/dpm_solver.py | MIT |
def get_orders_and_timesteps_for_singlestep_solver(self, steps, order, skip_type, t_T, t_0, device):
"""
Get the order of each step for sampling by the singlestep DPM-Solver.
We combine both DPM-Solver-1,2,3 to use all the function evaluations, which is named as "DPM-Solver-fast".
Given... |
Get the order of each step for sampling by the singlestep DPM-Solver.
We combine both DPM-Solver-1,2,3 to use all the function evaluations, which is named as "DPM-Solver-fast".
Given a fixed number of function evaluations by `steps`, the sampling procedure by DPM-Solver-fast is:
- ... | get_orders_and_timesteps_for_singlestep_solver | python | ali-vilab/videocomposer | artist/ops/dpm_solver.py | https://github.com/ali-vilab/videocomposer/blob/master/artist/ops/dpm_solver.py | MIT |
def dpm_solver_first_update(self, x, s, t, model_s=None, return_intermediate=False):
"""
DPM-Solver-1 (equivalent to DDIM) from time `s` to time `t`.
Args:
x: A pytorch tensor. The initial value at time `s`.
s: A pytorch tensor. The starting time, with the shape (1,).
... |
DPM-Solver-1 (equivalent to DDIM) from time `s` to time `t`.
Args:
x: A pytorch tensor. The initial value at time `s`.
s: A pytorch tensor. The starting time, with the shape (1,).
t: A pytorch tensor. The ending time, with the shape (1,).
model_s: A pyto... | dpm_solver_first_update | python | ali-vilab/videocomposer | artist/ops/dpm_solver.py | https://github.com/ali-vilab/videocomposer/blob/master/artist/ops/dpm_solver.py | MIT |
def singlestep_dpm_solver_second_update(self, x, s, t, r1=0.5, model_s=None, return_intermediate=False, solver_type='dpmsolver'):
"""
Singlestep solver DPM-Solver-2 from time `s` to time `t`.
Args:
x: A pytorch tensor. The initial value at time `s`.
s: A pytorch tensor. ... |
Singlestep solver DPM-Solver-2 from time `s` to time `t`.
Args:
x: A pytorch tensor. The initial value at time `s`.
s: A pytorch tensor. The starting time, with the shape (1,).
t: A pytorch tensor. The ending time, with the shape (1,).
r1: A `float`. The... | singlestep_dpm_solver_second_update | python | ali-vilab/videocomposer | artist/ops/dpm_solver.py | https://github.com/ali-vilab/videocomposer/blob/master/artist/ops/dpm_solver.py | MIT |
def singlestep_dpm_solver_third_update(self, x, s, t, r1=1./3., r2=2./3., model_s=None, model_s1=None, return_intermediate=False, solver_type='dpmsolver'):
"""
Singlestep solver DPM-Solver-3 from time `s` to time `t`.
Args:
x: A pytorch tensor. The initial value at time `s`.
... |
Singlestep solver DPM-Solver-3 from time `s` to time `t`.
Args:
x: A pytorch tensor. The initial value at time `s`.
s: A pytorch tensor. The starting time, with the shape (1,).
t: A pytorch tensor. The ending time, with the shape (1,).
r1: A `float`. The... | singlestep_dpm_solver_third_update | python | ali-vilab/videocomposer | artist/ops/dpm_solver.py | https://github.com/ali-vilab/videocomposer/blob/master/artist/ops/dpm_solver.py | MIT |
def multistep_dpm_solver_second_update(self, x, model_prev_list, t_prev_list, t, solver_type="dpmsolver"):
"""
Multistep solver DPM-Solver-2 from time `t_prev_list[-1]` to time `t`.
Args:
x: A pytorch tensor. The initial value at time `s`.
model_prev_list: A list of pyto... |
Multistep solver DPM-Solver-2 from time `t_prev_list[-1]` to time `t`.
Args:
x: A pytorch tensor. The initial value at time `s`.
model_prev_list: A list of pytorch tensor. The previous computed model values.
t_prev_list: A list of pytorch tensor. The previous times,... | multistep_dpm_solver_second_update | python | ali-vilab/videocomposer | artist/ops/dpm_solver.py | https://github.com/ali-vilab/videocomposer/blob/master/artist/ops/dpm_solver.py | MIT |
def multistep_dpm_solver_third_update(self, x, model_prev_list, t_prev_list, t, solver_type='dpmsolver'):
"""
Multistep solver DPM-Solver-3 from time `t_prev_list[-1]` to time `t`.
Args:
x: A pytorch tensor. The initial value at time `s`.
model_prev_list: A list of pytor... |
Multistep solver DPM-Solver-3 from time `t_prev_list[-1]` to time `t`.
Args:
x: A pytorch tensor. The initial value at time `s`.
model_prev_list: A list of pytorch tensor. The previous computed model values.
t_prev_list: A list of pytorch tensor. The previous times,... | multistep_dpm_solver_third_update | python | ali-vilab/videocomposer | artist/ops/dpm_solver.py | https://github.com/ali-vilab/videocomposer/blob/master/artist/ops/dpm_solver.py | MIT |
def singlestep_dpm_solver_update(self, x, s, t, order, return_intermediate=False, solver_type='dpmsolver', r1=None, r2=None):
"""
Singlestep DPM-Solver with the order `order` from time `s` to time `t`.
Args:
x: A pytorch tensor. The initial value at time `s`.
s: A pytorc... |
Singlestep DPM-Solver with the order `order` from time `s` to time `t`.
Args:
x: A pytorch tensor. The initial value at time `s`.
s: A pytorch tensor. The starting time, with the shape (1,).
t: A pytorch tensor. The ending time, with the shape (1,).
orde... | singlestep_dpm_solver_update | python | ali-vilab/videocomposer | artist/ops/dpm_solver.py | https://github.com/ali-vilab/videocomposer/blob/master/artist/ops/dpm_solver.py | MIT |
def multistep_dpm_solver_update(self, x, model_prev_list, t_prev_list, t, order, solver_type='dpmsolver'):
"""
Multistep DPM-Solver with the order `order` from time `t_prev_list[-1]` to time `t`.
Args:
x: A pytorch tensor. The initial value at time `s`.
model_prev_list: ... |
Multistep DPM-Solver with the order `order` from time `t_prev_list[-1]` to time `t`.
Args:
x: A pytorch tensor. The initial value at time `s`.
model_prev_list: A list of pytorch tensor. The previous computed model values.
t_prev_list: A list of pytorch tensor. The p... | multistep_dpm_solver_update | python | ali-vilab/videocomposer | artist/ops/dpm_solver.py | https://github.com/ali-vilab/videocomposer/blob/master/artist/ops/dpm_solver.py | MIT |
def add_noise(self, x, t, noise=None):
"""
Compute the noised input xt = alpha_t * x + sigma_t * noise.
Args:
x: A `torch.Tensor` with shape `(batch_size, *shape)`.
t: A `torch.Tensor` with shape `(t_size,)`.
Returns:
xt with shape `(t_size, batch_si... |
Compute the noised input xt = alpha_t * x + sigma_t * noise.
Args:
x: A `torch.Tensor` with shape `(batch_size, *shape)`.
t: A `torch.Tensor` with shape `(t_size,)`.
Returns:
xt with shape `(t_size, batch_size, *shape)`.
| add_noise | python | ali-vilab/videocomposer | artist/ops/dpm_solver.py | https://github.com/ali-vilab/videocomposer/blob/master/artist/ops/dpm_solver.py | MIT |
def inverse(self, x, steps=20, t_start=None, t_end=None, order=2, skip_type='time_uniform',
method='multistep', lower_order_final=True, denoise_to_zero=False, solver_type='dpmsolver',
atol=0.0078, rtol=0.05, return_intermediate=False):
"""
Inverse the sample `x` from time `t_start` to `t... |
Inverse the sample `x` from time `t_start` to `t_end` by DPM-Solver.
For discrete-time DPMs, we use `t_start=1/N`, where `N` is the total time steps during training.
| inverse | python | ali-vilab/videocomposer | artist/ops/dpm_solver.py | https://github.com/ali-vilab/videocomposer/blob/master/artist/ops/dpm_solver.py | MIT |
def sample(self, x, steps=20, t_start=None, t_end=None, order=2, skip_type='time_uniform',
method='multistep', lower_order_final=True, denoise_to_zero=False, solver_type='dpmsolver',
atol=0.0078, rtol=0.05):
"""
Compute the sample at time `t_end` by DPM-Solver, given the initial `x` at t... |
Compute the sample at time `t_end` by DPM-Solver, given the initial `x` at time `t_start`.
=====================================================
We support the following algorithms for both noise prediction model and data prediction model:
- 'singlestep':
Singleste... | sample | python | ali-vilab/videocomposer | artist/ops/dpm_solver.py | https://github.com/ali-vilab/videocomposer/blob/master/artist/ops/dpm_solver.py | MIT |
def interpolate_fn(x, xp, yp):
"""
A piecewise linear function y = f(x), using xp and yp as keypoints.
We implement f(x) in a differentiable way (i.e. applicable for autograd).
The function f(x) is well-defined for all x-axis. (For x beyond the bounds of xp, we use the outmost points of xp to define the... |
A piecewise linear function y = f(x), using xp and yp as keypoints.
We implement f(x) in a differentiable way (i.e. applicable for autograd).
The function f(x) is well-defined for all x-axis. (For x beyond the bounds of xp, we use the outmost points of xp to define the linear function.)
Args:
... | interpolate_fn | python | ali-vilab/videocomposer | artist/ops/dpm_solver.py | https://github.com/ali-vilab/videocomposer/blob/master/artist/ops/dpm_solver.py | MIT |
def inverse_indices(indices):
r"""Inverse map of indices.
E.g., if A[indices] == B, then B[inv_indices] == A.
"""
inv_indices = torch.empty_like(indices)
inv_indices[indices] = torch.arange(len(indices)).to(indices)
return inv_indices | Inverse map of indices.
E.g., if A[indices] == B, then B[inv_indices] == A.
| inverse_indices | python | ali-vilab/videocomposer | artist/ops/utils.py | https://github.com/ali-vilab/videocomposer/blob/master/artist/ops/utils.py | MIT |
def rope(x):
r"""Apply rotary position embedding on x of shape [B, *(spatial dimensions), C].
"""
# reshape
shape = x.shape
x = x.view(x.size(0), -1, x.size(-1))
l, c = x.shape[-2:]
assert c % 2 == 0
half = c // 2
# apply rotary position embedding on x
sinusoid = torch.outer(
... | Apply rotary position embedding on x of shape [B, *(spatial dimensions), C].
| rope | python | ali-vilab/videocomposer | artist/ops/utils.py | https://github.com/ali-vilab/videocomposer/blob/master/artist/ops/utils.py | MIT |
def breakup_grid(img, grid_size):
r"""The inverse operator of ``torchvision.utils.make_grid``.
"""
# params
nrow = img.height // grid_size
ncol = img.width // grid_size
wrow = wcol = 2 # NOTE: use default values here
# collect grids
grids = []
for i in range(nrow):
for j in... | The inverse operator of ``torchvision.utils.make_grid``.
| breakup_grid | python | ali-vilab/videocomposer | artist/ops/utils.py | https://github.com/ali-vilab/videocomposer/blob/master/artist/ops/utils.py | MIT |
def step(self, closure=None):
"""
Performs a single optimization step
Arguments:
closure (callable, optional): A closure that reevaluates the model
and returns the loss.
"""
loss = None
if closure is not None:
loss = closure()
... |
Performs a single optimization step
Arguments:
closure (callable, optional): A closure that reevaluates the model
and returns the loss.
| step | python | ali-vilab/videocomposer | artist/optim/adafactor.py | https://github.com/ali-vilab/videocomposer/blob/master/artist/optim/adafactor.py | MIT |
def beta_schedule(schedule, num_timesteps=1000, init_beta=None, last_beta=None):
'''
This code defines a function beta_schedule that generates a sequence of beta values based on the given input parameters. These beta values can be used in video diffusion processes. The function has the following parameters:
... |
This code defines a function beta_schedule that generates a sequence of beta values based on the given input parameters. These beta values can be used in video diffusion processes. The function has the following parameters:
schedule(str): Determines the type of beta schedule to be generated. It can be 'lin... | beta_schedule | python | ali-vilab/videocomposer | tools/videocomposer/inference_multi.py | https://github.com/ali-vilab/videocomposer/blob/master/tools/videocomposer/inference_multi.py | MIT |
def find_free_port():
""" https://stackoverflow.com/questions/1365265/on-localhost-how-do-i-pick-a-free-port-number """
import socket
from contextlib import closing
with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s:
s.bind(('', 0))
s.setsockopt(socket.SOL_SOCKET, socke... | ERROR: type should be string, got " https://stackoverflow.com/questions/1365265/on-localhost-how-do-i-pick-a-free-port-number " | find_free_port | python | ali-vilab/videocomposer | tools/videocomposer/inference_multi.py | https://github.com/ali-vilab/videocomposer/blob/master/tools/videocomposer/inference_multi.py | MIT |
def all_gather(tensors):
"""
All gathers the provided tensors from all processes across machines.
Args:
tensors (list): tensors to perform all gather across all processes in
all machines.
"""
gather_list = []
output_tensor = []
world_size = dist.get_world_size()
for tens... |
All gathers the provided tensors from all processes across machines.
Args:
tensors (list): tensors to perform all gather across all processes in
all machines.
| all_gather | python | ali-vilab/videocomposer | utils/distributed.py | https://github.com/ali-vilab/videocomposer/blob/master/utils/distributed.py | MIT |
def all_reduce(tensors, average=True):
"""
All reduce the provided tensors from all processes across machines.
Args:
tensors (list): tensors to perform all reduce across all processes in
all machines.
average (bool): scales the reduced tensor by the number of overall
processe... |
All reduce the provided tensors from all processes across machines.
Args:
tensors (list): tensors to perform all reduce across all processes in
all machines.
average (bool): scales the reduced tensor by the number of overall
processes across all machines.
| all_reduce | python | ali-vilab/videocomposer | utils/distributed.py | https://github.com/ali-vilab/videocomposer/blob/master/utils/distributed.py | MIT |
def init_process_group(
local_rank,
local_world_size,
shard_id,
num_shards,
init_method,
dist_backend="nccl",
):
"""
Initializes the default process group.
Args:
local_rank (int): the rank on the current local machine.
local_world_size (int): the world size (number of... |
Initializes the default process group.
Args:
local_rank (int): the rank on the current local machine.
local_world_size (int): the world size (number of processes running) on
the current local machine.
shard_id (int): the shard index (machine rank) of the current machine.
... | init_process_group | python | ali-vilab/videocomposer | utils/distributed.py | https://github.com/ali-vilab/videocomposer/blob/master/utils/distributed.py | MIT |
def is_master_proc(num_gpus=8):
"""
Determines if the current process is the master process.
"""
if torch.distributed.is_initialized():
return dist.get_rank() % num_gpus == 0
else:
return True |
Determines if the current process is the master process.
| is_master_proc | python | ali-vilab/videocomposer | utils/distributed.py | https://github.com/ali-vilab/videocomposer/blob/master/utils/distributed.py | MIT |
def get_world_size():
"""
Get the size of the world.
"""
if not dist.is_available():
return 1
if not dist.is_initialized():
return 1
return dist.get_world_size() |
Get the size of the world.
| get_world_size | python | ali-vilab/videocomposer | utils/distributed.py | https://github.com/ali-vilab/videocomposer/blob/master/utils/distributed.py | MIT |
def get_rank():
"""
Get the rank of the current process.
"""
if not dist.is_available():
return 0
if not dist.is_initialized():
return 0
return dist.get_rank() |
Get the rank of the current process.
| get_rank | python | ali-vilab/videocomposer | utils/distributed.py | https://github.com/ali-vilab/videocomposer/blob/master/utils/distributed.py | MIT |
def synchronize():
"""
Helper function to synchronize (barrier) among all processes when
using distributed training
"""
if not dist.is_available():
return
if not dist.is_initialized():
return
world_size = dist.get_world_size()
if world_size == 1:
return
dist.b... |
Helper function to synchronize (barrier) among all processes when
using distributed training
| synchronize | python | ali-vilab/videocomposer | utils/distributed.py | https://github.com/ali-vilab/videocomposer/blob/master/utils/distributed.py | MIT |
def _get_global_gloo_group():
"""
Return a process group based on gloo backend, containing all the ranks
The result is cached.
Returns:
(group): pytorch dist group.
"""
if dist.get_backend() == "nccl":
return dist.new_group(backend="gloo")
else:
return dist.group.WORL... |
Return a process group based on gloo backend, containing all the ranks
The result is cached.
Returns:
(group): pytorch dist group.
| _get_global_gloo_group | python | ali-vilab/videocomposer | utils/distributed.py | https://github.com/ali-vilab/videocomposer/blob/master/utils/distributed.py | MIT |
def _serialize_to_tensor(data, group):
"""
Seriialize the tensor to ByteTensor. Note that only `gloo` and `nccl`
backend is supported.
Args:
data (data): data to be serialized.
group (group): pytorch dist group.
Returns:
tensor (ByteTensor): tensor that serialized.
""... |
Seriialize the tensor to ByteTensor. Note that only `gloo` and `nccl`
backend is supported.
Args:
data (data): data to be serialized.
group (group): pytorch dist group.
Returns:
tensor (ByteTensor): tensor that serialized.
| _serialize_to_tensor | python | ali-vilab/videocomposer | utils/distributed.py | https://github.com/ali-vilab/videocomposer/blob/master/utils/distributed.py | MIT |
def _pad_to_largest_tensor(tensor, group):
"""
Padding all the tensors from different GPUs to the largest ones.
Args:
tensor (tensor): tensor to pad.
group (group): pytorch dist group.
Returns:
list[int]: size of the tensor, on each rank
Tensor: padded tensor that has the... |
Padding all the tensors from different GPUs to the largest ones.
Args:
tensor (tensor): tensor to pad.
group (group): pytorch dist group.
Returns:
list[int]: size of the tensor, on each rank
Tensor: padded tensor that has the max size
| _pad_to_largest_tensor | python | ali-vilab/videocomposer | utils/distributed.py | https://github.com/ali-vilab/videocomposer/blob/master/utils/distributed.py | MIT |
def all_gather_unaligned(data, group=None):
"""
Run all_gather on arbitrary picklable data (not necessarily tensors).
Args:
data: any picklable object
group: a torch process group. By default, will use a group which
contains all ranks on gloo backend.
Returns:
list[... |
Run all_gather on arbitrary picklable data (not necessarily tensors).
Args:
data: any picklable object
group: a torch process group. By default, will use a group which
contains all ranks on gloo backend.
Returns:
list[data]: list of data gathered from each rank
| all_gather_unaligned | python | ali-vilab/videocomposer | utils/distributed.py | https://github.com/ali-vilab/videocomposer/blob/master/utils/distributed.py | MIT |
def init_distributed_training(cfg):
"""
Initialize variables needed for distributed training.
"""
if cfg.NUM_GPUS <= 1:
return
num_gpus_per_machine = cfg.NUM_GPUS
num_machines = dist.get_world_size() // num_gpus_per_machine
for i in range(num_machines):
ranks_on_i = list(
... |
Initialize variables needed for distributed training.
| init_distributed_training | python | ali-vilab/videocomposer | utils/distributed.py | https://github.com/ali-vilab/videocomposer/blob/master/utils/distributed.py | MIT |
def get_local_rank() -> int:
"""
Returns:
The rank of the current process within the local (per-machine) process group.
"""
if not dist.is_available():
return 0
if not dist.is_initialized():
return 0
assert _LOCAL_PROCESS_GROUP is not None
return dist.get_rank(group=_... |
Returns:
The rank of the current process within the local (per-machine) process group.
| get_local_rank | python | ali-vilab/videocomposer | utils/distributed.py | https://github.com/ali-vilab/videocomposer/blob/master/utils/distributed.py | MIT |
def _suppress_print():
"""
Suppresses printing from the current process.
"""
def print_pass(*objects, sep=" ", end="\n", file=sys.stdout, flush=False):
pass
builtins.print = print_pass |
Suppresses printing from the current process.
| _suppress_print | python | ali-vilab/videocomposer | utils/logging.py | https://github.com/ali-vilab/videocomposer/blob/master/utils/logging.py | MIT |
def setup_logging(cfg, log_file):
"""
Sets up the logging for multiple processes. Only enable the logging for the
master process, and suppress logging for the non-master processes.
"""
if du.is_master_proc():
# Enable logging for the master process.
logging.root.handlers = []
els... |
Sets up the logging for multiple processes. Only enable the logging for the
master process, and suppress logging for the non-master processes.
| setup_logging | python | ali-vilab/videocomposer | utils/logging.py | https://github.com/ali-vilab/videocomposer/blob/master/utils/logging.py | MIT |
def log_json_stats(stats):
"""
Logs json stats.
Args:
stats (dict): a dictionary of statistical information to log.
"""
stats = {
k: decimal.Decimal("{:.6f}".format(v)) if isinstance(v, float) else v
for k, v in stats.items()
}
json_stats = simplejson.dumps(stats, sor... |
Logs json stats.
Args:
stats (dict): a dictionary of statistical information to log.
| log_json_stats | python | ali-vilab/videocomposer | utils/logging.py | https://github.com/ali-vilab/videocomposer/blob/master/utils/logging.py | MIT |
def _init_ml_signal_listener(self):
"""Initialize a listener for ML signals from the MQTT broker"""
try:
normalized_pair = self.config.trading_pair.replace("-", "_").lower()
topic = f"{self.config.topic}/{normalized_pair}/ML_SIGNALS"
self._ml_signal_listener = Externa... | Initialize a listener for ML signals from the MQTT broker | _init_ml_signal_listener | python | hummingbot/hummingbot | controllers/directional_trading/ai_livestream.py | https://github.com/hummingbot/hummingbot/blob/master/controllers/directional_trading/ai_livestream.py | Apache-2.0 |
def get_executor_config(self, trade_type: TradeType, price: Decimal, amount: Decimal):
"""
Get the executor config based on the trade_type, price and amount. This method can be overridden by the
subclasses if required.
"""
return PositionExecutorConfig(
timestamp=self... |
Get the executor config based on the trade_type, price and amount. This method can be overridden by the
subclasses if required.
| get_executor_config | python | hummingbot/hummingbot | controllers/directional_trading/ai_livestream.py | https://github.com/hummingbot/hummingbot/blob/master/controllers/directional_trading/ai_livestream.py | Apache-2.0 |
def determine_executor_actions(self) -> List[ExecutorAction]:
"""
Determine actions based on the provided executor handler report.
"""
actions = []
actions.extend(self.create_actions_proposal())
actions.extend(self.stop_actions_proposal())
return actions |
Determine actions based on the provided executor handler report.
| determine_executor_actions | python | hummingbot/hummingbot | controllers/generic/pmm.py | https://github.com/hummingbot/hummingbot/blob/master/controllers/generic/pmm.py | Apache-2.0 |
def create_actions_proposal(self) -> List[ExecutorAction]:
"""
Create actions proposal based on the current state of the controller.
"""
create_actions = []
# Check if a position reduction executor for TP/SL is already sent
reduction_executor_exists = any(
ex... |
Create actions proposal based on the current state of the controller.
| create_actions_proposal | python | hummingbot/hummingbot | controllers/generic/pmm.py | https://github.com/hummingbot/hummingbot/blob/master/controllers/generic/pmm.py | Apache-2.0 |
def stop_actions_proposal(self) -> List[ExecutorAction]:
"""
Create a list of actions to stop the executors based on order refresh and early stop conditions.
"""
stop_actions = []
stop_actions.extend(self.executors_to_refresh())
stop_actions.extend(self.executors_to_early... |
Create a list of actions to stop the executors based on order refresh and early stop conditions.
| stop_actions_proposal | python | hummingbot/hummingbot | controllers/generic/pmm.py | https://github.com/hummingbot/hummingbot/blob/master/controllers/generic/pmm.py | Apache-2.0 |
def executors_to_early_stop(self) -> List[ExecutorAction]:
"""
Get the executors to early stop based on the current state of market data. This method can be overridden to
implement custom behavior.
"""
executors_to_early_stop = self.filter_executors(
executors=self.ex... |
Get the executors to early stop based on the current state of market data. This method can be overridden to
implement custom behavior.
| executors_to_early_stop | python | hummingbot/hummingbot | controllers/generic/pmm.py | https://github.com/hummingbot/hummingbot/blob/master/controllers/generic/pmm.py | Apache-2.0 |
async def update_processed_data(self):
"""
Update the processed data for the controller. This method should be reimplemented to modify the reference price
and spread multiplier based on the market data. By default, it will update the reference price as mid price and
the spread multiplier... |
Update the processed data for the controller. This method should be reimplemented to modify the reference price
and spread multiplier based on the market data. By default, it will update the reference price as mid price and
the spread multiplier as 1.
| update_processed_data | python | hummingbot/hummingbot | controllers/generic/pmm.py | https://github.com/hummingbot/hummingbot/blob/master/controllers/generic/pmm.py | Apache-2.0 |
def get_executor_config(self, level_id: str, price: Decimal, amount: Decimal):
"""
Get the executor config for a given level id.
"""
trade_type = self.get_trade_type_from_level_id(level_id)
level_multiplier = self.get_level_from_level_id(level_id) + 1
return PositionExecu... |
Get the executor config for a given level id.
| get_executor_config | python | hummingbot/hummingbot | controllers/generic/pmm.py | https://github.com/hummingbot/hummingbot/blob/master/controllers/generic/pmm.py | Apache-2.0 |
def get_not_active_levels_ids(self, active_levels_ids: List[str]) -> List[str]:
"""
Get the levels to execute based on the current state of the controller.
"""
buy_ids_missing = [self.get_level_id_from_side(TradeType.BUY, level) for level in range(len(self.config.buy_spreads))
... |
Get the levels to execute based on the current state of the controller.
| get_not_active_levels_ids | python | hummingbot/hummingbot | controllers/generic/pmm.py | https://github.com/hummingbot/hummingbot/blob/master/controllers/generic/pmm.py | Apache-2.0 |
def get_current_candles_price(self) -> Decimal:
"""
Get the current price from the candles data provider.
"""
candles = self.market_data_provider.get_candles_df(self.config.candles_connector_name,
self.config.candles_trading_pair... |
Get the current price from the candles data provider.
| get_current_candles_price | python | hummingbot/hummingbot | controllers/generic/pmm_adjusted.py | https://github.com/hummingbot/hummingbot/blob/master/controllers/generic/pmm_adjusted.py | Apache-2.0 |
def update_portfolio_metrics(self):
"""
Calculate theoretical vs actual portfolio allocations
"""
metrics = {
"theoretical": {},
"actual": {},
"difference": {},
}
# Get real balances and calculate total portfolio value
quote_ba... |
Calculate theoretical vs actual portfolio allocations
| update_portfolio_metrics | python | hummingbot/hummingbot | controllers/generic/quantum_grid_allocator.py | https://github.com/hummingbot/hummingbot/blob/master/controllers/generic/quantum_grid_allocator.py | Apache-2.0 |
def get_active_grids_by_asset(self) -> Dict[str, List[ExecutorInfo]]:
"""Group active grids by asset using filter_executors"""
active_grids = {}
for asset in self.config.portfolio_allocation:
if asset == self.config.quote_asset:
continue
trading_pair = f"{... | Group active grids by asset using filter_executors | get_active_grids_by_asset | python | hummingbot/hummingbot | controllers/generic/quantum_grid_allocator.py | https://github.com/hummingbot/hummingbot/blob/master/controllers/generic/quantum_grid_allocator.py | Apache-2.0 |
def to_format_status(self) -> List[str]:
"""Generate a detailed status report with portfolio, grid, and position information"""
status_lines = []
total_value = self.metrics.get("total_portfolio_value", Decimal("0"))
# Portfolio Status
status_lines.append(f"Total Portfolio Value: ... | Generate a detailed status report with portfolio, grid, and position information | to_format_status | python | hummingbot/hummingbot | controllers/generic/quantum_grid_allocator.py | https://github.com/hummingbot/hummingbot/blob/master/controllers/generic/quantum_grid_allocator.py | Apache-2.0 |
def create_grid_executor(
self,
trading_pair: str,
side: TradeType,
start_price: Decimal,
end_price: Decimal,
grid_value: Decimal,
is_unfavorable: bool = False
) -> CreateExecutorAction:
"""Creates a grid executor with dynamic sizing and range adjustme... | Creates a grid executor with dynamic sizing and range adjustments | create_grid_executor | python | hummingbot/hummingbot | controllers/generic/quantum_grid_allocator.py | https://github.com/hummingbot/hummingbot/blob/master/controllers/generic/quantum_grid_allocator.py | Apache-2.0 |
def update_markets(self, markets: dict) -> dict:
"""Update markets dictionary with both trading pairs"""
# Add dominant pair
if self.connector_pair_dominant.connector_name not in markets:
markets[self.connector_pair_dominant.connector_name] = set()
markets[self.connector_pair... | Update markets dictionary with both trading pairs | update_markets | python | hummingbot/hummingbot | controllers/generic/stat_arb.py | https://github.com/hummingbot/hummingbot/blob/master/controllers/generic/stat_arb.py | Apache-2.0 |
def determine_executor_actions(self) -> List[ExecutorAction]:
"""
The execution logic for the statistical arbitrage strategy.
Market Data Conditions: Signal is generated based on the z-score of the spread between the two assets.
If signal == 1 --> long dominant/sh... |
The execution logic for the statistical arbitrage strategy.
Market Data Conditions: Signal is generated based on the z-score of the spread between the two assets.
If signal == 1 --> long dominant/short hedge
If signal == -1 --> short domin... | determine_executor_actions | python | hummingbot/hummingbot | controllers/generic/stat_arb.py | https://github.com/hummingbot/hummingbot/blob/master/controllers/generic/stat_arb.py | Apache-2.0 |
def get_executors_to_quote(self) -> List[ExecutorAction]:
"""
Get Order Executor to quote from the dominant and hedge markets.
"""
actions: List[ExecutorAction] = []
trade_type_dominant = TradeType.BUY if self.processed_data["signal"] == 1 else TradeType.SELL
trade_type_h... |
Get Order Executor to quote from the dominant and hedge markets.
| get_executors_to_quote | python | hummingbot/hummingbot | controllers/generic/stat_arb.py | https://github.com/hummingbot/hummingbot/blob/master/controllers/generic/stat_arb.py | Apache-2.0 |
def get_executors_to_reduce_position(self, position: PositionSummary) -> List[ExecutorAction]:
"""
Get Order Executor to reduce position.
"""
if position.amount > Decimal("0"):
# Close position
config = OrderExecutorConfig(
timestamp=self.market_da... |
Get Order Executor to reduce position.
| get_executors_to_reduce_position | python | hummingbot/hummingbot | controllers/generic/stat_arb.py | https://github.com/hummingbot/hummingbot/blob/master/controllers/generic/stat_arb.py | Apache-2.0 |
async def update_processed_data(self):
"""
Update processed data with the latest market information and statistical calculations
needed for the statistical arbitrage strategy.
"""
# Stat arb analysis
spread, z_score = self.get_spread_and_z_score()
# Generate trad... |
Update processed data with the latest market information and statistical calculations
needed for the statistical arbitrage strategy.
| update_processed_data | python | hummingbot/hummingbot | controllers/generic/stat_arb.py | https://github.com/hummingbot/hummingbot/blob/master/controllers/generic/stat_arb.py | Apache-2.0 |
def to_format_status(self) -> List[str]:
"""
Format the status of the controller for display.
"""
status_lines = []
status_lines.append(f"""
Dominant Pair: {self.config.connector_pair_dominant} | Hedge Pair: {self.config.connector_pair_hedge} |
Timeframe: {self.config.interval} |... |
Format the status of the controller for display.
| to_format_status | python | hummingbot/hummingbot | controllers/generic/stat_arb.py | https://github.com/hummingbot/hummingbot/blob/master/controllers/generic/stat_arb.py | Apache-2.0 |
def get_strategy_list() -> List[str]:
"""
Search `hummingbot.strategy` folder for all available strategies
Automatically hide all strategies that starts with "dev" if on master branch
"""
try:
folder = path.realpath(path.join(__file__, "../strategy"))
# Only include valid directories... |
Search `hummingbot.strategy` folder for all available strategies
Automatically hide all strategies that starts with "dev" if on master branch
| get_strategy_list | python | hummingbot/hummingbot | hummingbot/__init__.py | https://github.com/hummingbot/hummingbot/blob/master/hummingbot/__init__.py | Apache-2.0 |
def init_command_tabs(self) -> Dict[str, CommandTab]:
"""
Initiates and returns a CommandTab dictionary with mostly defaults and None values, These values will be
populated later on by HummingbotCLI
"""
command_tabs: Dict[str, CommandTab] = {}
for tab_class in tab_classes... |
Initiates and returns a CommandTab dictionary with mostly defaults and None values, These values will be
populated later on by HummingbotCLI
| init_command_tabs | python | hummingbot/hummingbot | hummingbot/client/hummingbot_application.py | https://github.com/hummingbot/hummingbot/blob/master/hummingbot/client/hummingbot_application.py | Apache-2.0 |
def position_order(open: list, close: list) -> Tuple[Any, Any]:
"""
Pair open position order with close position orders
:param open: a list of orders that may have an open position order
:param close: a list of orders that may have an close position order
:return: A tuple contain... |
Pair open position order with close position orders
:param open: a list of orders that may have an open position order
:param close: a list of orders that may have an close position order
:return: A tuple containing a pair of an open order with a close position order
| position_order | python | hummingbot/hummingbot | hummingbot/client/performance.py | https://github.com/hummingbot/hummingbot/blob/master/hummingbot/client/performance.py | Apache-2.0 |
def aggregate_position_order(buys: list, sells: list) -> Tuple[list, list]:
"""
Aggregate the amount field for orders with multiple fills
:param buys: a list of buy orders
:param sells: a list of sell orders
:return: 2 lists containing aggregated amounts for buy and sell orders.
... |
Aggregate the amount field for orders with multiple fills
:param buys: a list of buy orders
:param sells: a list of sell orders
:return: 2 lists containing aggregated amounts for buy and sell orders.
| aggregate_position_order | python | hummingbot/hummingbot | hummingbot/client/performance.py | https://github.com/hummingbot/hummingbot/blob/master/hummingbot/client/performance.py | Apache-2.0 |
def derivative_pnl(long: list, short: list) -> List[Decimal]:
# It is assumed that the amount and leverage for both open and close orders are the same.
"""
Calculates PnL for a close position
:param long: a list containing pairs of open and closed long position orders
:param shor... |
Calculates PnL for a close position
:param long: a list containing pairs of open and closed long position orders
:param short: a list containing pairs of open and closed short position orders
:return: A list containing PnL for each closed positions
| derivative_pnl | python | hummingbot/hummingbot | hummingbot/client/performance.py | https://github.com/hummingbot/hummingbot/blob/master/hummingbot/client/performance.py | Apache-2.0 |
async def _initialize_metrics(self,
trading_pair: str,
trades: List[Any],
current_balances: Dict[str, Decimal]):
"""
Calculates PnL, fees, Return % and etc...
:param trading_pair: the trading ma... |
Calculates PnL, fees, Return % and etc...
:param trading_pair: the trading market to get performance metrics
:param trades: the list of TradeFill or Trade object
:param current_balances: current user account balance
| _initialize_metrics | python | hummingbot/hummingbot | hummingbot/client/performance.py | https://github.com/hummingbot/hummingbot/blob/master/hummingbot/client/performance.py | Apache-2.0 |
def create_connector_settings(cls):
"""
Iterate over files in specific Python directories to create a dictionary of exchange names to ConnectorSetting.
"""
cls.all_connector_settings = {} # reset
connector_exceptions = ["mock_paper_exchange", "mock_pure_python_paper_exchange", "... |
Iterate over files in specific Python directories to create a dictionary of exchange names to ConnectorSetting.
| create_connector_settings | python | hummingbot/hummingbot | hummingbot/client/settings.py | https://github.com/hummingbot/hummingbot/blob/master/hummingbot/client/settings.py | Apache-2.0 |
def gateway_connector_trading_pairs(connector: str) -> List[str]:
"""
Returns trading pair used by specified gateway connnector.
"""
ret_val = []
for conn, t_pair in requried_connector_trading_pairs.items():
if AllConnectorSettings.get_connector_settings()[conn].uses_gateway_generic_connecto... |
Returns trading pair used by specified gateway connnector.
| gateway_connector_trading_pairs | python | hummingbot/hummingbot | hummingbot/client/settings.py | https://github.com/hummingbot/hummingbot/blob/master/hummingbot/client/settings.py | Apache-2.0 |
def format_decimal(n):
"""
Convert the given float to a string without scientific notation
"""
try:
with decimal.localcontext() as ctx:
if isinstance(n, float):
n = ctx.create_decimal(n)
if isinstance(n, decimal.Decimal):
n = round(n, FLOAT... |
Convert the given float to a string without scientific notation
| format_decimal | python | hummingbot/hummingbot | hummingbot/client/__init__.py | https://github.com/hummingbot/hummingbot/blob/master/hummingbot/client/__init__.py | Apache-2.0 |
def configurable_keys(self, # type: HummingbotApplication
) -> List[str]:
"""
Returns a list of configurable keys - using config command, excluding exchanges api keys
as they are set from connect command.
"""
keys = [
traversal_item.config_p... |
Returns a list of configurable keys - using config command, excluding exchanges api keys
as they are set from connect command.
| configurable_keys | python | hummingbot/hummingbot | hummingbot/client/command/config_command.py | https://github.com/hummingbot/hummingbot/blob/master/hummingbot/client/command/config_command.py | Apache-2.0 |
async def _config_single_key(self, # type: HummingbotApplication
key: str,
input_value):
"""
Configure a single variable only.
Prompt the user to finish all configurations if there are remaining empty configs at the end.
... |
Configure a single variable only.
Prompt the user to finish all configurations if there are remaining empty configs at the end.
| _config_single_key | python | hummingbot/hummingbot | hummingbot/client/command/config_command.py | https://github.com/hummingbot/hummingbot/blob/master/hummingbot/client/command/config_command.py | Apache-2.0 |
async def _check_node_status(self, chain: str, network: str, node_url: str) -> bool:
"""
Verify that the node url is valid. If it is an empty string,
ignore it, but let the user know they cannot connect to the node.
"""
resp = await GatewayHttpClient.get_instance().get_network_s... |
Verify that the node url is valid. If it is an empty string,
ignore it, but let the user know they cannot connect to the node.
| _check_node_status | python | hummingbot/hummingbot | hummingbot/client/command/gateway_api_manager.py | https://github.com/hummingbot/hummingbot/blob/master/hummingbot/client/command/gateway_api_manager.py | Apache-2.0 |
async def _test_node_url(self, chain: str, network: str) -> Optional[str]:
"""
Get the node url from user input, then check that it is valid.
"""
with begin_placeholder_mode(self):
while True:
node_url: str = await self.app.prompt(prompt=f"Enter a node url (wi... |
Get the node url from user input, then check that it is valid.
| _test_node_url | python | hummingbot/hummingbot | hummingbot/client/command/gateway_api_manager.py | https://github.com/hummingbot/hummingbot/blob/master/hummingbot/client/command/gateway_api_manager.py | Apache-2.0 |
async def _test_node_url_from_gateway_config(self, chain: str, network: str, attempt_connection: bool = True) -> bool:
"""
Check if gateway node URL for a chain and network works
"""
# XXX: This should be removed once nodeAPIKey is deprecated from Gateway service
chain_config: Di... |
Check if gateway node URL for a chain and network works
| _test_node_url_from_gateway_config | python | hummingbot/hummingbot | hummingbot/client/command/gateway_api_manager.py | https://github.com/hummingbot/hummingbot/blob/master/hummingbot/client/command/gateway_api_manager.py | Apache-2.0 |
async def _update_gateway_chain_network_node_url(chain: str, network: str, node_url: str):
"""
Update a chain and network's node URL in gateway
"""
await GatewayHttpClient.get_instance().update_config(f"{chain}.networks.{network}.nodeURL", node_url) |
Update a chain and network's node URL in gateway
| _update_gateway_chain_network_node_url | python | hummingbot/hummingbot | hummingbot/client/command/gateway_api_manager.py | https://github.com/hummingbot/hummingbot/blob/master/hummingbot/client/command/gateway_api_manager.py | Apache-2.0 |
async def _get_native_currency_symbol(self, chain: str, network: str) -> Optional[str]:
"""
Get the native currency symbol for a chain and network from gateway config
"""
chain_config: Dict[str, Any] = await GatewayHttpClient.get_instance().get_configuration(chain)
if chain_confi... |
Get the native currency symbol for a chain and network from gateway config
| _get_native_currency_symbol | python | hummingbot/hummingbot | hummingbot/client/command/gateway_api_manager.py | https://github.com/hummingbot/hummingbot/blob/master/hummingbot/client/command/gateway_api_manager.py | Apache-2.0 |
async def ping_gateway_api(self, max_wait: int) -> bool:
"""
Try to reach the gateway API for up to max_wait seconds
"""
now = int(time.time())
gateway_live = await self._get_gateway_instance().ping_gateway()
while not gateway_live:
later = int(time.time())
... |
Try to reach the gateway API for up to max_wait seconds
| ping_gateway_api | python | hummingbot/hummingbot | hummingbot/client/command/gateway_command.py | https://github.com/hummingbot/hummingbot/blob/master/hummingbot/client/command/gateway_command.py | Apache-2.0 |
async def _show_gateway_connector_tokens(
self, # type: HummingbotApplication
connector_chain_network: str = None
):
"""
Display connector tokens that hummingbot will report balances for
"""
if connector_chain_network is None:
gateway_con... |
Display connector tokens that hummingbot will report balances for
| _show_gateway_connector_tokens | python | hummingbot/hummingbot | hummingbot/client/command/gateway_command.py | https://github.com/hummingbot/hummingbot/blob/master/hummingbot/client/command/gateway_command.py | Apache-2.0 |
async def _update_gateway_connector_tokens(
self, # type: HummingbotApplication
connector_chain_network: str,
new_tokens: str,
):
"""
Allow the user to input tokens whose balances they want to monitor are.
These are not tied to a strategy, rather... |
Allow the user to input tokens whose balances they want to monitor are.
These are not tied to a strategy, rather to the connector-chain-network
tuple. This has no influence on what tokens the user can use with a
connector-chain-network and a particular strategy. This is only for
... | _update_gateway_connector_tokens | python | hummingbot/hummingbot | hummingbot/client/command/gateway_command.py | https://github.com/hummingbot/hummingbot/blob/master/hummingbot/client/command/gateway_command.py | Apache-2.0 |
async def _update_gateway_approve_tokens(
self, # type: HummingbotApplication
connector_chain_network: str,
tokens: str,
):
"""
Allow the user to approve tokens for spending.
"""
# get connector specs
conf: Optional[Dict[str, str]... |
Allow the user to approve tokens for spending.
| _update_gateway_approve_tokens | python | hummingbot/hummingbot | hummingbot/client/command/gateway_command.py | https://github.com/hummingbot/hummingbot/blob/master/hummingbot/client/command/gateway_command.py | Apache-2.0 |
async def _get_allowances(self, exchange_name: Optional[str] = None):
"""Get token allowances for Ethereum-based connectors"""
gateway_connections = GatewayConnectionSetting.load()
gateway_instance = GatewayHttpClient.get_instance(self.client_config_map)
self.notify("Checking token allow... | Get token allowances for Ethereum-based connectors | _get_allowances | python | hummingbot/hummingbot | hummingbot/client/command/gateway_command.py | https://github.com/hummingbot/hummingbot/blob/master/hummingbot/client/command/gateway_command.py | Apache-2.0 |
async def calculate_profitability(self, # type: HummingbotApplication
) -> Decimal:
"""
Determines the profitability of the trading bot.
This function is used by the KillSwitch class.
Must be updated if the method of performance report gets updated.... |
Determines the profitability of the trading bot.
This function is used by the KillSwitch class.
Must be updated if the method of performance report gets updated.
| calculate_profitability | python | hummingbot/hummingbot | hummingbot/client/command/history_command.py | https://github.com/hummingbot/hummingbot/blob/master/hummingbot/client/command/history_command.py | Apache-2.0 |
def load_script_class(self):
"""
Imports the script module based on its name (module file name) and returns the loaded script class
:param script_name: name of the module where the script class is defined
"""
script_name = self.strategy_name
config = None
module ... |
Imports the script module based on its name (module file name) and returns the loaded script class
:param script_name: name of the module where the script class is defined
| load_script_class | python | hummingbot/hummingbot | hummingbot/client/command/start_command.py | https://github.com/hummingbot/hummingbot/blob/master/hummingbot/client/command/start_command.py | Apache-2.0 |
def validate_bool(cls, v: str):
"""Used for client-friendly error output."""
if isinstance(v, str):
ret = validate_bool(v)
if ret is not None:
raise ValueError(ret)
return v | Used for client-friendly error output. | validate_bool | python | hummingbot/hummingbot | hummingbot/client/config/client_config_map.py | https://github.com/hummingbot/hummingbot/blob/master/hummingbot/client/config/client_config_map.py | Apache-2.0 |
def _create_v3_keyfile_json(message_to_encrypt, password, kdf="pbkdf2", work_factor=None):
"""
Encrypt message by a given password.
Most of this code is copied from eth_key_file.key_file, removed address and is from json result.
"""
salt = Random.get_random_bytes(16)
if work_factor is None:
... |
Encrypt message by a given password.
Most of this code is copied from eth_key_file.key_file, removed address and is from json result.
| _create_v3_keyfile_json | python | hummingbot/hummingbot | hummingbot/client/config/config_crypt.py | https://github.com/hummingbot/hummingbot/blob/master/hummingbot/client/config/config_crypt.py | Apache-2.0 |
def model_json_schema(
cls,
by_alias: bool = True,
ref_template: str = DEFAULT_REF_TEMPLATE,
schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema,
mode: JsonSchemaMode = 'validation',
) -> dict[str, Any]:
"""Generates a JSON schema for a model class.
... | Generates a JSON schema for a model class.
Args:
by_alias: Whether to use attribute aliases or not.
ref_template: The reference template.
schema_generator: To override the logic used to generate the JSON schema, as a subclass of
... | model_json_schema | python | hummingbot/hummingbot | hummingbot/client/config/config_data_types.py | https://github.com/hummingbot/hummingbot/blob/master/hummingbot/client/config/config_data_types.py | Apache-2.0 |
def traverse(self, secure: bool = True) -> Generator[ConfigTraversalItem, None, None]:
"""The intended use for this function is to simplify config map traversals in the client code.
If the field is missing, its value will be set to `None` and its printable value will be set to
'MISSING_AND_REQU... | The intended use for this function is to simplify config map traversals in the client code.
If the field is missing, its value will be set to `None` and its printable value will be set to
'MISSING_AND_REQUIRED'.
| traverse | python | hummingbot/hummingbot | hummingbot/client/config/config_helpers.py | https://github.com/hummingbot/hummingbot/blob/master/hummingbot/client/config/config_helpers.py | Apache-2.0 |
def get_default_str_repr(self, attr_name: str) -> str:
"""Used to generate default strings for config prompts."""
default = self.get_default(attr_name=attr_name)
if default is None:
default_str = ""
elif isinstance(default, (List, Tuple)):
default_str = ",".join(d... | Used to generate default strings for config prompts. | get_default_str_repr | python | hummingbot/hummingbot | hummingbot/client/config/config_helpers.py | https://github.com/hummingbot/hummingbot/blob/master/hummingbot/client/config/config_helpers.py | Apache-2.0 |
def parse_cvar_value(cvar: ConfigVar, value: Any) -> Any:
"""
Based on the target type specified in `ConfigVar.type_str`, parses a string value into the target type.
:param cvar: ConfigVar object
:param value: User input from running session or from saved `yml` files. Type is usually string.
:return... |
Based on the target type specified in `ConfigVar.type_str`, parses a string value into the target type.
:param cvar: ConfigVar object
:param value: User input from running session or from saved `yml` files. Type is usually string.
:return: value in the correct type
| parse_cvar_value | python | hummingbot/hummingbot | hummingbot/client/config/config_helpers.py | https://github.com/hummingbot/hummingbot/blob/master/hummingbot/client/config/config_helpers.py | Apache-2.0 |
def cvar_json_migration(cvar: ConfigVar, cvar_value: Any) -> Any:
"""
A special function to migrate json config variable when its json type changes, for paper_trade_account_balance
and min_quote_order_amount (deprecated), they were List but change to Dict.
"""
if cvar.key in ("paper_trade_account_ba... |
A special function to migrate json config variable when its json type changes, for paper_trade_account_balance
and min_quote_order_amount (deprecated), they were List but change to Dict.
| cvar_json_migration | python | hummingbot/hummingbot | hummingbot/client/config/config_helpers.py | https://github.com/hummingbot/hummingbot/blob/master/hummingbot/client/config/config_helpers.py | Apache-2.0 |
def parse_cvar_default_value_prompt(cvar: ConfigVar) -> str:
"""
:param cvar: ConfigVar object
:return: text for default value prompt
"""
if cvar.default is None:
default = ""
elif callable(cvar.default):
default = cvar.default()
elif cvar.type == 'bool' and isinstance(cvar.p... |
:param cvar: ConfigVar object
:return: text for default value prompt
| parse_cvar_default_value_prompt | python | hummingbot/hummingbot | hummingbot/client/config/config_helpers.py | https://github.com/hummingbot/hummingbot/blob/master/hummingbot/client/config/config_helpers.py | Apache-2.0 |
async def copy_strategy_template(strategy: str) -> str:
"""
Look up template `.yml` file for a particular strategy in `hummingbot/templates` and copy it to the `conf` folder.
The file name is `conf_{STRATEGY}_strategy_{INDEX}.yml`
:return: The newly created file name
"""
old_path = get_strategy_... |
Look up template `.yml` file for a particular strategy in `hummingbot/templates` and copy it to the `conf` folder.
The file name is `conf_{STRATEGY}_strategy_{INDEX}.yml`
:return: The newly created file name
| copy_strategy_template | python | hummingbot/hummingbot | hummingbot/client/config/config_helpers.py | https://github.com/hummingbot/hummingbot/blob/master/hummingbot/client/config/config_helpers.py | Apache-2.0 |
def _merge_dicts(*args: Dict[str, ConfigVar]) -> OrderedDict:
"""
Helper function to merge a few dictionaries into an ordered dictionary.
"""
result: OrderedDict[any] = OrderedDict()
for d in args:
result.update(d)
return result |
Helper function to merge a few dictionaries into an ordered dictionary.
| _merge_dicts | python | hummingbot/hummingbot | hummingbot/client/config/config_helpers.py | https://github.com/hummingbot/hummingbot/blob/master/hummingbot/client/config/config_helpers.py | Apache-2.0 |
def get_strategy_config_map(
strategy: str
) -> Optional[Union[ClientConfigAdapter, Dict[str, ConfigVar]]]:
"""
Given the name of a strategy, find and load strategy-specific config map.
"""
try:
config_cls = get_strategy_pydantic_config_cls(strategy)
if config_cls is None: # legacy
... |
Given the name of a strategy, find and load strategy-specific config map.
| get_strategy_config_map | python | hummingbot/hummingbot | hummingbot/client/config/config_helpers.py | https://github.com/hummingbot/hummingbot/blob/master/hummingbot/client/config/config_helpers.py | Apache-2.0 |
def get_strategy_starter_file(strategy: str) -> Callable:
"""
Given the name of a strategy, find and load the `start` function in
`hummingbot/strategy/{STRATEGY_NAME}/start.py` file.
"""
if strategy is None:
return lambda: None
try:
strategy_module = __import__(f"hummingbot.strat... |
Given the name of a strategy, find and load the `start` function in
`hummingbot/strategy/{STRATEGY_NAME}/start.py` file.
| get_strategy_starter_file | python | hummingbot/hummingbot | hummingbot/client/config/config_helpers.py | https://github.com/hummingbot/hummingbot/blob/master/hummingbot/client/config/config_helpers.py | Apache-2.0 |
async def read_system_configs_from_yml():
"""
Read global config and selected strategy yml files and save the values to corresponding config map
If a yml file is outdated, it gets reformatted with the new template
"""
await load_yml_into_cm_legacy(
str(TRADE_FEES_CONFIG_PATH), str(TEMPLATE_P... |
Read global config and selected strategy yml files and save the values to corresponding config map
If a yml file is outdated, it gets reformatted with the new template
| read_system_configs_from_yml | python | hummingbot/hummingbot | hummingbot/client/config/config_helpers.py | https://github.com/hummingbot/hummingbot/blob/master/hummingbot/client/config/config_helpers.py | Apache-2.0 |
async def refresh_trade_fees_config(client_config_map: ClientConfigAdapter):
"""
Refresh the trade fees config, after new connectors have been added (e.g. gateway connectors).
"""
init_fee_overrides_config()
save_to_yml(CLIENT_CONFIG_PATH, client_config_map)
save_to_yml_legacy(str(TRADE_FEES_CON... |
Refresh the trade fees config, after new connectors have been added (e.g. gateway connectors).
| refresh_trade_fees_config | python | hummingbot/hummingbot | hummingbot/client/config/config_helpers.py | https://github.com/hummingbot/hummingbot/blob/master/hummingbot/client/config/config_helpers.py | Apache-2.0 |
def save_to_yml_legacy(yml_path: str, cm: Dict[str, ConfigVar]):
"""
Write current config saved a single config map into each a single yml file
"""
try:
with open(yml_path, encoding="utf-8") as stream:
data = yaml_parser.load(stream) or {}
for key in cm:
c... |
Write current config saved a single config map into each a single yml file
| save_to_yml_legacy | python | hummingbot/hummingbot | hummingbot/client/config/config_helpers.py | https://github.com/hummingbot/hummingbot/blob/master/hummingbot/client/config/config_helpers.py | Apache-2.0 |
async def create_yml_files_legacy():
"""
Copy `hummingbot_logs.yml` and `conf_global.yml` templates to the `conf` directory on start up
"""
for fname in listdir(TEMPLATE_PATH):
if "_TEMPLATE" in fname and CONF_POSTFIX not in fname:
stripped_fname = fname.replace("_TEMPLATE", "")
... |
Copy `hummingbot_logs.yml` and `conf_global.yml` templates to the `conf` directory on start up
| create_yml_files_legacy | python | hummingbot/hummingbot | hummingbot/client/config/config_helpers.py | https://github.com/hummingbot/hummingbot/blob/master/hummingbot/client/config/config_helpers.py | Apache-2.0 |
def default_strategy_file_path(strategy: str) -> str:
"""
Find the next available file name.
:return: a default file name - `conf_{short_strategy}_{INDEX}.yml` e.g. 'conf_pure_mm_1.yml'
"""
i = 1
new_fname = f"{CONF_PREFIX}{short_strategy_name(strategy)}_{i}.yml"
new_path = STRATEGIES_CONF_D... |
Find the next available file name.
:return: a default file name - `conf_{short_strategy}_{INDEX}.yml` e.g. 'conf_pure_mm_1.yml'
| default_strategy_file_path | python | hummingbot/hummingbot | hummingbot/client/config/config_helpers.py | https://github.com/hummingbot/hummingbot/blob/master/hummingbot/client/config/config_helpers.py | Apache-2.0 |
def parse_config_default_to_text(config: ConfigVar) -> str:
"""
:param config: ConfigVar object
:return: text for default value prompt
"""
if config.default is None:
default = ""
elif callable(config.default):
default = config.default()
elif config.type == 'bool' and isinstan... |
:param config: ConfigVar object
:return: text for default value prompt
| parse_config_default_to_text | python | hummingbot/hummingbot | hummingbot/client/config/config_helpers.py | https://github.com/hummingbot/hummingbot/blob/master/hummingbot/client/config/config_helpers.py | Apache-2.0 |
def validate_exchange(value: str) -> Optional[str]:
"""
Restrict valid exchanges to the exchange file names
"""
from hummingbot.client.settings import AllConnectorSettings
if value not in AllConnectorSettings.get_exchange_names():
return f"Invalid exchange, please choose value from {AllConne... |
Restrict valid exchanges to the exchange file names
| validate_exchange | python | hummingbot/hummingbot | hummingbot/client/config/config_validators.py | https://github.com/hummingbot/hummingbot/blob/master/hummingbot/client/config/config_validators.py | Apache-2.0 |
def validate_derivative(value: str) -> Optional[str]:
"""
restrict valid derivatives to the derivative file names
"""
from hummingbot.client.settings import AllConnectorSettings
if value not in AllConnectorSettings.get_derivative_names():
return f"Invalid derivative, please choose value from... |
restrict valid derivatives to the derivative file names
| validate_derivative | python | hummingbot/hummingbot | hummingbot/client/config/config_validators.py | https://github.com/hummingbot/hummingbot/blob/master/hummingbot/client/config/config_validators.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.