INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Aroon Down. Formula: AROONDWN = (((PERIOD) - (PERIODS SINCE PERIOD LOW)) / (PERIOD)) * 100
def aroon_down(data, period): """ Aroon Down. Formula: AROONDWN = (((PERIOD) - (PERIODS SINCE PERIOD LOW)) / (PERIOD)) * 100 """ catch_errors.check_for_period_error(data, period) period = int(period) a_down = [((period - list(reversed(data[idx+1-period:idx+1])).index(np.min(data[idx+1-period:idx+1]))) / float(period)) * 100 for idx in range(period-1, len(data))] a_down = fill_for_noncomputable_vals(data, a_down) return a_down
Momentum. Formula: DATA[i] - DATA[i - period]
def momentum(data, period): """ Momentum. Formula: DATA[i] - DATA[i - period] """ catch_errors.check_for_period_error(data, period) momentum = [data[idx] - data[idx+1-period] for idx in range(period-1, len(data))] momentum = fill_for_noncomputable_vals(data, momentum) return momentum
Upper Price Channel. Formula: upc = EMA(t) * (1 + upper_percent / 100)
def upper_price_channel(data, period, upper_percent): """ Upper Price Channel. Formula: upc = EMA(t) * (1 + upper_percent / 100) """ catch_errors.check_for_period_error(data, period) emas = ema(data, period) upper_channel = [val * (1+float(upper_percent)/100) for val in emas] return upper_channel
Lower Price Channel. Formula: lpc = EMA(t) * (1 - lower_percent / 100)
def lower_price_channel(data, period, lower_percent): """ Lower Price Channel. Formula: lpc = EMA(t) * (1 - lower_percent / 100) """ catch_errors.check_for_period_error(data, period) emas = ema(data, period) lower_channel = [val * (1-float(lower_percent)/100) for val in emas] return lower_channel
Exponential Moving Average. Formula: p0 + (1 - w) * p1 + (1 - w)^2 * p2 + (1 + w)^3 * p3 +... / 1 + (1 - w) + (1 - w)^2 + (1 - w)^3 +... where: w = 2 / (N + 1)
def exponential_moving_average(data, period): """ Exponential Moving Average. Formula: p0 + (1 - w) * p1 + (1 - w)^2 * p2 + (1 + w)^3 * p3 +... / 1 + (1 - w) + (1 - w)^2 + (1 - w)^3 +... where: w = 2 / (N + 1) """ catch_errors.check_for_period_error(data, period) emas = [exponential_moving_average_helper( data[idx - period + 1:idx + 1], period) for idx in range(period - 1, len(data))] emas = fill_for_noncomputable_vals(data, emas) return emas
Commodity Channel Index. Formula: CCI = (TP - SMA(TP)) / (0.015 * Mean Deviation)
def commodity_channel_index(close_data, high_data, low_data, period): """ Commodity Channel Index. Formula: CCI = (TP - SMA(TP)) / (0.015 * Mean Deviation) """ catch_errors.check_for_input_len_diff(close_data, high_data, low_data) catch_errors.check_for_period_error(close_data, period) tp = typical_price(close_data, high_data, low_data) cci = ((tp - sma(tp, period)) / (0.015 * np.mean(np.absolute(tp - np.mean(tp))))) return cci
Moving Average Convergence Divergence. Formula: EMA(DATA, P1) - EMA(DATA, P2)
def moving_average_convergence_divergence(data, short_period, long_period): """ Moving Average Convergence Divergence. Formula: EMA(DATA, P1) - EMA(DATA, P2) """ catch_errors.check_for_period_error(data, short_period) catch_errors.check_for_period_error(data, long_period) macd = ema(data, short_period) - ema(data, long_period) return macd
Williams %R. Formula: wr = (HighestHigh - close / HighestHigh - LowestLow) * -100
def williams_percent_r(close_data): """ Williams %R. Formula: wr = (HighestHigh - close / HighestHigh - LowestLow) * -100 """ highest_high = np.max(close_data) lowest_low = np.min(close_data) wr = [((highest_high - close) / (highest_high - lowest_low)) * -100 for close in close_data] return wr
Money Flow Index. Formula: MFI = 100 - (100 / (1 + PMF / NMF))
def money_flow_index(close_data, high_data, low_data, volume, period): """ Money Flow Index. Formula: MFI = 100 - (100 / (1 + PMF / NMF)) """ catch_errors.check_for_input_len_diff( close_data, high_data, low_data, volume ) catch_errors.check_for_period_error(close_data, period) mf = money_flow(close_data, high_data, low_data, volume) tp = typical_price(close_data, high_data, low_data) flow = [tp[idx] > tp[idx-1] for idx in range(1, len(tp))] pf = [mf[idx] if flow[idx] else 0 for idx in range(0, len(flow))] nf = [mf[idx] if not flow[idx] else 0 for idx in range(0, len(flow))] pmf = [sum(pf[idx+1-period:idx+1]) for idx in range(period-1, len(pf))] nmf = [sum(nf[idx+1-period:idx+1]) for idx in range(period-1, len(nf))] # Dividing by 0 is not an issue, it turns the value into NaN which we would # want in that case with warnings.catch_warnings(): warnings.simplefilter("ignore", category=RuntimeWarning) money_ratio = np.array(pmf) / np.array(nmf) mfi = 100 - (100 / (1 + money_ratio)) mfi = fill_for_noncomputable_vals(close_data, mfi) return mfi
Typical Price. Formula: TPt = (HIGHt + LOWt + CLOSEt) / 3
def typical_price(close_data, high_data, low_data): """ Typical Price. Formula: TPt = (HIGHt + LOWt + CLOSEt) / 3 """ catch_errors.check_for_input_len_diff(close_data, high_data, low_data) tp = [(high_data[idx] + low_data[idx] + close_data[idx]) / 3 for idx in range(0, len(close_data))] return np.array(tp)
True Range. Formula: TRt = MAX(abs(Ht - Lt), abs(Ht - Ct-1), abs(Lt - Ct-1))
def true_range(close_data, period): """ True Range. Formula: TRt = MAX(abs(Ht - Lt), abs(Ht - Ct-1), abs(Lt - Ct-1)) """ catch_errors.check_for_period_error(close_data, period) tr = [np.max([np.max(close_data[idx+1-period:idx+1]) - np.min(close_data[idx+1-period:idx+1]), abs(np.max(close_data[idx+1-period:idx+1]) - close_data[idx-1]), abs(np.min(close_data[idx+1-period:idx+1]) - close_data[idx-1])]) for idx in range(period-1, len(close_data))] tr = fill_for_noncomputable_vals(close_data, tr) return tr
Double Smoothed Stochastic. Formula: dss = 100 * EMA(Close - Lowest Low) / EMA(Highest High - Lowest Low)
def double_smoothed_stochastic(data, period): """ Double Smoothed Stochastic. Formula: dss = 100 * EMA(Close - Lowest Low) / EMA(Highest High - Lowest Low) """ catch_errors.check_for_period_error(data, period) lows = [data[idx] - np.min(data[idx+1-period:idx+1]) for idx in range(period-1, len(data))] sm_lows = ema(ema(lows, period), period) highs = [np.max(data[idx+1-period:idx+1]) - np.min(data[idx+1-period:idx+1]) for idx in range(period-1, len(data))] sm_highs = ema(ema(highs, period), period) dss = (sm_lows / sm_highs) * 100 dss = fill_for_noncomputable_vals(data, dss) return dss
Volume Adjusted Moving Average. Formula: VAMA = SUM(CLOSE * VolumeRatio) / period
def volume_adjusted_moving_average(close_data, volume, period): """ Volume Adjusted Moving Average. Formula: VAMA = SUM(CLOSE * VolumeRatio) / period """ catch_errors.check_for_input_len_diff(close_data, volume) catch_errors.check_for_period_error(close_data, period) avg_vol = np.mean(volume) vol_incr = avg_vol * 0.67 vol_ratio = [val / vol_incr for val in volume] close_vol = np.array(close_data) * vol_ratio vama = [sum(close_vol[idx+1-period:idx+1]) / period for idx in range(period-1, len(close_data))] vama = fill_for_noncomputable_vals(close_data, vama) return vama
Triangular Moving Average. Formula: TMA = SMA(SMA())
def triangular_moving_average(data, period): """ Triangular Moving Average. Formula: TMA = SMA(SMA()) """ catch_errors.check_for_period_error(data, period) tma = sma(sma(data, period), period) return tma
Weighted Moving Average. Formula: (P1 + 2 P2 + 3 P3 + ... + n Pn) / K where K = (1+2+...+n) = n(n+1)/2 and Pn is the most recent price
def weighted_moving_average(data, period): """ Weighted Moving Average. Formula: (P1 + 2 P2 + 3 P3 + ... + n Pn) / K where K = (1+2+...+n) = n(n+1)/2 and Pn is the most recent price """ catch_errors.check_for_period_error(data, period) k = (period * (period + 1)) / 2.0 wmas = [] for idx in range(0, len(data)-period+1): product = [data[idx + period_idx] * (period_idx + 1) for period_idx in range(0, period)] wma = sum(product) / k wmas.append(wma) wmas = fill_for_noncomputable_vals(data, wmas) return wmas
The only real difference between TenkanSen and KijunSen is the period value
def conversion_base_line_helper(data, period): """ The only real difference between TenkanSen and KijunSen is the period value """ catch_errors.check_for_period_error(data, period) cblh = [(np.max(data[idx+1-period:idx+1]) + np.min(data[idx+1-period:idx+1])) / 2 for idx in range(period-1, len(data))] cblh = fill_for_noncomputable_vals(data, cblh) return cblh
Senkou A (Leading Span A) Formula: (TenkanSen + KijunSen) / 2 :: Shift Forward 26 bars
def senkou_a(data): """ Senkou A (Leading Span A) Formula: (TenkanSen + KijunSen) / 2 :: Shift Forward 26 bars """ sa = (tenkansen(data) + kijunsen(data)) / 2 # shift forward shift_by = np.repeat(np.nan, 26) sa = np.append(shift_by, sa) return sa
Senkou B (Leading Span B) Formula: (H + L) / 2 :: default period=52 :: shifted forward 26 bars
def senkou_b(data, period=52): """ Senkou B (Leading Span B) Formula: (H + L) / 2 :: default period=52 :: shifted forward 26 bars """ sb = conversion_base_line_helper(data, period) shift_by = np.repeat(np.nan, 26) sb = np.append(shift_by, sb) return sb
Volatility. Formula: SDt / SVt
def volatility(data, period): """ Volatility. Formula: SDt / SVt """ volatility = sd(data, period) / sv(data, period) return volatility
Chande Momentum Oscillator. Formula: cmo = 100 * ((sum_up - sum_down) / (sum_up + sum_down))
def chande_momentum_oscillator(close_data, period): """ Chande Momentum Oscillator. Formula: cmo = 100 * ((sum_up - sum_down) / (sum_up + sum_down)) """ catch_errors.check_for_period_error(close_data, period) close_data = np.array(close_data) moving_period_diffs = [[(close_data[idx+1-period:idx+1][i] - close_data[idx+1-period:idx+1][i-1]) for i in range(1, len(close_data[idx+1-period:idx+1]))] for idx in range(0, len(close_data))] sum_up = [] sum_down = [] for period_diffs in moving_period_diffs: ups = [val if val > 0 else 0 for val in period_diffs] sum_up.append(sum(ups)) downs = [abs(val) if val < 0 else 0 for val in period_diffs] sum_down.append(sum(downs)) sum_up = np.array(sum_up) sum_down = np.array(sum_down) # numpy is able to handle dividing by zero and makes those calculations # nans which is what we want, so we safely suppress the RuntimeWarning with warnings.catch_warnings(): warnings.simplefilter("ignore", category=RuntimeWarning) cmo = 100 * ((sum_up - sum_down) / (sum_up + sum_down)) return cmo
Price Oscillator. Formula: (short EMA - long EMA / long EMA) * 100
def price_oscillator(data, short_period, long_period): """ Price Oscillator. Formula: (short EMA - long EMA / long EMA) * 100 """ catch_errors.check_for_period_error(data, short_period) catch_errors.check_for_period_error(data, long_period) ema_short = ema(data, short_period) ema_long = ema(data, long_period) po = ((ema_short - ema_long) / ema_long) * 100 return po
Check for Period Error. This method checks if the developer is trying to enter a period that is larger than the data set being entered. If that is the case an exception is raised with a custom message that informs the developer that their period is greater than the data set.
def check_for_period_error(data, period): """ Check for Period Error. This method checks if the developer is trying to enter a period that is larger than the data set being entered. If that is the case an exception is raised with a custom message that informs the developer that their period is greater than the data set. """ period = int(period) data_len = len(data) if data_len < period: raise Exception("Error: data_len < period")
Check for Input Length Difference. This method checks if multiple data sets that are inputted are all the same size. If they are not the same length an error is raised with a custom message that informs the developer that the data set's lengths are not the same.
def check_for_input_len_diff(*args): """ Check for Input Length Difference. This method checks if multiple data sets that are inputted are all the same size. If they are not the same length an error is raised with a custom message that informs the developer that the data set's lengths are not the same. """ arrays_len = [len(arr) for arr in args] if not all(a == arrays_len[0] for a in arrays_len): err_msg = ("Error: mismatched data lengths, check to ensure that all " "input data is the same length and valid") raise Exception(err_msg)
StochRSI. Formula: SRSI = ((RSIt - RSI LOW) / (RSI HIGH - LOW RSI)) * 100
def stochrsi(data, period): """ StochRSI. Formula: SRSI = ((RSIt - RSI LOW) / (RSI HIGH - LOW RSI)) * 100 """ rsi = relative_strength_index(data, period)[period:] stochrsi = [100 * ((rsi[idx] - np.min(rsi[idx+1-period:idx+1])) / (np.max(rsi[idx+1-period:idx+1]) - np.min(rsi[idx+1-period:idx+1]))) for idx in range(period-1, len(rsi))] stochrsi = fill_for_noncomputable_vals(data, stochrsi) return stochrsi
Upper Bollinger Band. Formula: u_bb = SMA(t) + STD(SMA(t-n:t)) * std_mult
def upper_bollinger_band(data, period, std_mult=2.0): """ Upper Bollinger Band. Formula: u_bb = SMA(t) + STD(SMA(t-n:t)) * std_mult """ catch_errors.check_for_period_error(data, period) period = int(period) simple_ma = sma(data, period)[period-1:] upper_bb = [] for idx in range(len(data) - period + 1): std_dev = np.std(data[idx:idx + period]) upper_bb.append(simple_ma[idx] + std_dev * std_mult) upper_bb = fill_for_noncomputable_vals(data, upper_bb) return np.array(upper_bb)
Middle Bollinger Band. Formula: m_bb = sma()
def middle_bollinger_band(data, period, std=2.0): """ Middle Bollinger Band. Formula: m_bb = sma() """ catch_errors.check_for_period_error(data, period) period = int(period) mid_bb = sma(data, period) return mid_bb
Lower Bollinger Band. Formula: u_bb = SMA(t) - STD(SMA(t-n:t)) * std_mult
def lower_bollinger_band(data, period, std=2.0): """ Lower Bollinger Band. Formula: u_bb = SMA(t) - STD(SMA(t-n:t)) * std_mult """ catch_errors.check_for_period_error(data, period) period = int(period) simple_ma = sma(data, period)[period-1:] lower_bb = [] for idx in range(len(data) - period + 1): std_dev = np.std(data[idx:idx + period]) lower_bb.append(simple_ma[idx] - std_dev * std) lower_bb = fill_for_noncomputable_vals(data, lower_bb) return np.array(lower_bb)
Bandwidth. Formula: bw = u_bb - l_bb / m_bb
def bandwidth(data, period, std=2.0): """ Bandwidth. Formula: bw = u_bb - l_bb / m_bb """ catch_errors.check_for_period_error(data, period) period = int(period) bandwidth = ((upper_bollinger_band(data, period, std) - lower_bollinger_band(data, period, std)) / middle_bollinger_band(data, period, std) ) return bandwidth
Range. Formula: bb_range = u_bb - l_bb
def bb_range(data, period, std=2.0): """ Range. Formula: bb_range = u_bb - l_bb """ catch_errors.check_for_period_error(data, period) period = int(period) bb_range = (upper_bollinger_band(data, period, std) - lower_bollinger_band(data, period, std) ) return bb_range
Percent Bandwidth. Formula: %_bw = data() - l_bb() / bb_range()
def percent_bandwidth(data, period, std=2.0): """ Percent Bandwidth. Formula: %_bw = data() - l_bb() / bb_range() """ catch_errors.check_for_period_error(data, period) period = int(period) percent_bandwidth = ((np.array(data) - lower_bollinger_band(data, period, std)) / bb_range(data, period, std) ) return percent_bandwidth
%B. Formula: %B = ((data - lb) / (ub - lb)) * 100
def percent_b(data, period, upper_bb_std=2.0, lower_bb_std=2.0): """ %B. Formula: %B = ((data - lb) / (ub - lb)) * 100 """ lb = lower_bollinger_band(data, period, lower_bb_std) ub = upper_bollinger_band(data, period, upper_bb_std) percent_b = ((np.array(data) - lb) / (ub - lb)) * 100 return percent_b
Standard Deviation. Formula: std = sqrt(avg(abs(x - avg(x))^2))
def standard_deviation(data, period): """ Standard Deviation. Formula: std = sqrt(avg(abs(x - avg(x))^2)) """ catch_errors.check_for_period_error(data, period) stds = [np.std(data[idx+1-period:idx+1], ddof=1) for idx in range(period-1, len(data))] stds = fill_for_noncomputable_vals(data, stds) return stds
Detrended Price Oscillator. Formula: DPO = DATA[i] - Avg(DATA[period/2 + 1])
def detrended_price_oscillator(data, period): """ Detrended Price Oscillator. Formula: DPO = DATA[i] - Avg(DATA[period/2 + 1]) """ catch_errors.check_for_period_error(data, period) period = int(period) dop = [data[idx] - np.mean(data[idx+1-(int(period/2)+1):idx+1]) for idx in range(period-1, len(data))] dop = fill_for_noncomputable_vals(data, dop) return dop
Upper Band. Formula: ub = cb(t) * (1 + env_percentage)
def upper_band(data, period, env_percentage): """ Upper Band. Formula: ub = cb(t) * (1 + env_percentage) """ cb = center_band(data, period) ub = [val * (1 + float(env_percentage)) for val in cb] return ub
Lower Band. Formula: lb = cb * (1 - env_percentage)
def lower_band(data, period, env_percentage): """ Lower Band. Formula: lb = cb * (1 - env_percentage) """ cb = center_band(data, period) lb = [val * (1 - float(env_percentage)) for val in cb] return lb
Smoothed Moving Average. Formula: smma = avg(data(n)) - avg(data(n)/n) + data(t)/n
def smoothed_moving_average(data, period): """ Smoothed Moving Average. Formula: smma = avg(data(n)) - avg(data(n)/n) + data(t)/n """ catch_errors.check_for_period_error(data, period) series = pd.Series(data) return series.ewm(alpha = 1.0/period).mean().values.flatten()
Chaikin Money Flow. Formula: CMF = SUM[(((Cn - Ln) - (Hn - Cn)) / (Hn - Ln)) * V] / SUM(Vn)
def chaikin_money_flow(close_data, high_data, low_data, volume, period): """ Chaikin Money Flow. Formula: CMF = SUM[(((Cn - Ln) - (Hn - Cn)) / (Hn - Ln)) * V] / SUM(Vn) """ catch_errors.check_for_input_len_diff( close_data, high_data, low_data, volume) catch_errors.check_for_period_error(close_data, period) close_data = np.array(close_data) high_data = np.array(high_data) low_data = np.array(low_data) volume = np.array(volume) cmf = [sum((((close_data[idx+1-period:idx+1] - low_data[idx+1-period:idx+1]) - (high_data[idx+1-period:idx+1] - close_data[idx+1-period:idx+1])) / (high_data[idx+1-period:idx+1] - low_data[idx+1-period:idx+1])) * volume[idx+1-period:idx+1]) / sum(volume[idx+1-period:idx+1]) for idx in range(period-1, len(close_data))] cmf = fill_for_noncomputable_vals(close_data, cmf) return cmf
%D. Formula: %D = SMA(%K, 3)
def percent_d(data, period): """ %D. Formula: %D = SMA(%K, 3) """ p_k = percent_k(data, period) percent_d = sma(p_k, 3) return percent_d
Hull Moving Average. Formula: HMA = WMA(2*WMA(n/2) - WMA(n)), sqrt(n)
def hull_moving_average(data, period): """ Hull Moving Average. Formula: HMA = WMA(2*WMA(n/2) - WMA(n)), sqrt(n) """ catch_errors.check_for_period_error(data, period) hma = wma( 2 * wma(data, int(period/2)) - wma(data, period), int(np.sqrt(period)) ) return hma
Standard Variance. Formula: (Ct - AVGt)^2 / N
def standard_variance(data, period): """ Standard Variance. Formula: (Ct - AVGt)^2 / N """ catch_errors.check_for_period_error(data, period) sv = [np.var(data[idx+1-period:idx+1], ddof=1) for idx in range(period-1, len(data))] sv = fill_for_noncomputable_vals(data, sv) return sv
Up Move. Formula: UPMOVE = Ht - Ht-1
def calculate_up_moves(high_data): """ Up Move. Formula: UPMOVE = Ht - Ht-1 """ up_moves = [high_data[idx] - high_data[idx-1] for idx in range(1, len(high_data))] return [np.nan] + up_moves
Down Move. Formula: DWNMOVE = Lt-1 - Lt
def calculate_down_moves(low_data): """ Down Move. Formula: DWNMOVE = Lt-1 - Lt """ down_moves = [low_data[idx-1] - low_data[idx] for idx in range(1, len(low_data))] return [np.nan] + down_moves
Positive Directional Movement (+DM). Formula: +DM: if UPMOVE > DWNMOVE and UPMOVE > 0 then +DM = UPMOVE else +DM = 0
def positive_directional_movement(high_data, low_data): """ Positive Directional Movement (+DM). Formula: +DM: if UPMOVE > DWNMOVE and UPMOVE > 0 then +DM = UPMOVE else +DM = 0 """ catch_errors.check_for_input_len_diff(high_data, low_data) up_moves = calculate_up_moves(high_data) down_moves = calculate_down_moves(low_data) pdm = [] for idx in range(0, len(up_moves)): if up_moves[idx] > down_moves[idx] and up_moves[idx] > 0: pdm.append(up_moves[idx]) else: pdm.append(0) return pdm
Negative Directional Movement (-DM). -DM: if DWNMOVE > UPMOVE and DWNMOVE > 0 then -DM = DWNMOVE else -Dm = 0
def negative_directional_movement(high_data, low_data): """ Negative Directional Movement (-DM). -DM: if DWNMOVE > UPMOVE and DWNMOVE > 0 then -DM = DWNMOVE else -Dm = 0 """ catch_errors.check_for_input_len_diff(high_data, low_data) up_moves = calculate_up_moves(high_data) down_moves = calculate_down_moves(low_data) ndm = [] for idx in range(0, len(down_moves)): if down_moves[idx] > up_moves[idx] and down_moves[idx] > 0: ndm.append(down_moves[idx]) else: ndm.append(0) return ndm
Positive Directional Index (+DI). Formula: +DI = 100 * SMMA(+DM) / ATR
def positive_directional_index(close_data, high_data, low_data, period): """ Positive Directional Index (+DI). Formula: +DI = 100 * SMMA(+DM) / ATR """ catch_errors.check_for_input_len_diff(close_data, high_data, low_data) pdi = (100 * smma(positive_directional_movement(high_data, low_data), period) / atr(close_data, period) ) return pdi
Negative Directional Index (-DI). Formula: -DI = 100 * SMMA(-DM) / ATR
def negative_directional_index(close_data, high_data, low_data, period): """ Negative Directional Index (-DI). Formula: -DI = 100 * SMMA(-DM) / ATR """ catch_errors.check_for_input_len_diff(close_data, high_data, low_data) ndi = (100 * smma(negative_directional_movement(high_data, low_data), period) / atr(close_data, period) ) return ndi
Average Directional Index. Formula: ADX = 100 * SMMA(abs((+DI - -DI) / (+DI + -DI)))
def average_directional_index(close_data, high_data, low_data, period): """ Average Directional Index. Formula: ADX = 100 * SMMA(abs((+DI - -DI) / (+DI + -DI))) """ avg_di = (abs( (positive_directional_index( close_data, high_data, low_data, period) - negative_directional_index( close_data, high_data, low_data, period)) / (positive_directional_index( close_data, high_data, low_data, period) + negative_directional_index( close_data, high_data, low_data, period))) ) adx = 100 * smma(avg_di, period) return adx
Linear Weighted Moving Average. Formula: LWMA = SUM(DATA[i]) * i / SUM(i)
def linear_weighted_moving_average(data, period): """ Linear Weighted Moving Average. Formula: LWMA = SUM(DATA[i]) * i / SUM(i) """ catch_errors.check_for_period_error(data, period) idx_period = list(range(1, period+1)) lwma = [(sum([i * idx_period[data[idx-(period-1):idx+1].index(i)] for i in data[idx-(period-1):idx+1]])) / sum(range(1, len(data[idx+1-period:idx+1])+1)) for idx in range(period-1, len(data))] lwma = fill_for_noncomputable_vals(data, lwma) return lwma
Volume Oscillator. Formula: vo = 100 * (SMA(vol, short) - SMA(vol, long) / SMA(vol, long))
def volume_oscillator(volume, short_period, long_period): """ Volume Oscillator. Formula: vo = 100 * (SMA(vol, short) - SMA(vol, long) / SMA(vol, long)) """ catch_errors.check_for_period_error(volume, short_period) catch_errors.check_for_period_error(volume, long_period) vo = (100 * ((sma(volume, short_period) - sma(volume, long_period)) / sma(volume, long_period))) return vo
Triple Exponential Moving Average. Formula: TEMA = (3*EMA - 3*EMA(EMA)) + EMA(EMA(EMA))
def triple_exponential_moving_average(data, period): """ Triple Exponential Moving Average. Formula: TEMA = (3*EMA - 3*EMA(EMA)) + EMA(EMA(EMA)) """ catch_errors.check_for_period_error(data, period) tema = ((3 * ema(data, period) - (3 * ema(ema(data, period), period))) + ema(ema(ema(data, period), period), period) ) return tema
Money Flow. Formula: MF = VOLUME * TYPICAL PRICE
def money_flow(close_data, high_data, low_data, volume): """ Money Flow. Formula: MF = VOLUME * TYPICAL PRICE """ catch_errors.check_for_input_len_diff( close_data, high_data, low_data, volume ) mf = volume * tp(close_data, high_data, low_data) return mf
Positive Volume Index (PVI). Formula: PVI0 = 1 IF Vt > Vt-1 PVIt = PVIt-1 + (CLOSEt - CLOSEt-1 / CLOSEt-1 * PVIt-1) ELSE: PVIt = PVIt-1
def positive_volume_index(close_data, volume): """ Positive Volume Index (PVI). Formula: PVI0 = 1 IF Vt > Vt-1 PVIt = PVIt-1 + (CLOSEt - CLOSEt-1 / CLOSEt-1 * PVIt-1) ELSE: PVIt = PVIt-1 """ catch_errors.check_for_input_len_diff(close_data, volume) pvi = np.zeros(len(volume)) pvi[0] = 1 for idx in range(1, len(volume)): if volume[idx] > volume[idx-1]: pvi[idx] = volume_index_helper(pvi, idx, close_data) else: pvi[idx] = pvi[idx-1] return pvi
Negative Volume Index (NVI). Formula: NVI0 = 1 IF Vt < Vt-1 NVIt = NVIt-1 + (CLOSEt - CLOSEt-1 / CLOSEt-1 * NVIt-1) ELSE: NVIt = NVIt-1
def negative_volume_index(close_data, volume): """ Negative Volume Index (NVI). Formula: NVI0 = 1 IF Vt < Vt-1 NVIt = NVIt-1 + (CLOSEt - CLOSEt-1 / CLOSEt-1 * NVIt-1) ELSE: NVIt = NVIt-1 """ catch_errors.check_for_input_len_diff(close_data, volume) nvi = np.zeros(len(volume)) nvi[0] = 1 for idx in range(1, len(volume)): if volume[idx] < volume[idx-1]: nvi[idx] = volume_index_helper(nvi, idx, close_data) else: nvi[idx] = nvi[idx-1] return nvi
Logs out and quits the current web driver/selenium session.
def close(self): """Logs out and quits the current web driver/selenium session.""" if not self.driver: return try: self.driver.implicitly_wait(1) self.driver.find_element_by_id('link-logout').click() except NoSuchElementException: pass self.driver.quit() self.driver = None
Performs a request, and checks that the status is OK, and that the content-type matches expectations. Args: url: URL to request method: either 'get' or 'post' expected_content_type: prefix to match response content-type against **kwargs: passed to the request method directly. Raises: RuntimeError if status_code does not match.
def request_and_check(self, url, method='get', expected_content_type=None, **kwargs): """Performs a request, and checks that the status is OK, and that the content-type matches expectations. Args: url: URL to request method: either 'get' or 'post' expected_content_type: prefix to match response content-type against **kwargs: passed to the request method directly. Raises: RuntimeError if status_code does not match. """ assert method in ['get', 'post'] result = self.driver.request(method, url, **kwargs) if result.status_code != requests.codes.ok: raise RuntimeError('Error requesting %r, status = %d' % (url, result.status_code)) if expected_content_type is not None: content_type = result.headers.get('content-type', '') if not re.match(expected_content_type, content_type): raise RuntimeError( 'Error requesting %r, content type %r does not match %r' % (url, content_type, expected_content_type)) return result
Returns the raw JSON transaction data as downloaded from Mint. The JSON transaction data includes some additional information missing from the CSV data, such as whether the transaction is pending or completed, but leaves off the year for current year transactions. Warning: In order to reliably include or exclude duplicates, it is necessary to change the user account property 'hide_duplicates' to the appropriate value. This affects what is displayed in the web interface. Note that the CSV transactions never exclude duplicates.
def get_transactions_json(self, include_investment=False, skip_duplicates=False, start_date=None, id=0): """Returns the raw JSON transaction data as downloaded from Mint. The JSON transaction data includes some additional information missing from the CSV data, such as whether the transaction is pending or completed, but leaves off the year for current year transactions. Warning: In order to reliably include or exclude duplicates, it is necessary to change the user account property 'hide_duplicates' to the appropriate value. This affects what is displayed in the web interface. Note that the CSV transactions never exclude duplicates. """ # Warning: This is a global property for the user that we are changing. self.set_user_property( 'hide_duplicates', 'T' if skip_duplicates else 'F') # Converts the start date into datetime format - must be mm/dd/yy try: start_date = datetime.strptime(start_date, '%m/%d/%y') except (TypeError, ValueError): start_date = None all_txns = [] offset = 0 # Mint only returns some of the transactions at once. To get all of # them, we have to keep asking for more until we reach the end. while 1: url = MINT_ROOT_URL + '/getJsonData.xevent' params = { 'queryNew': '', 'offset': offset, 'comparableType': '8', 'rnd': Mint.get_rnd(), } # Specifying accountId=0 causes Mint to return investment # transactions as well. Otherwise they are skipped by # default. if id > 0 or include_investment: params['id'] = id if include_investment: params['task'] = 'transactions' else: params['task'] = 'transactions,txnfilters' params['filterType'] = 'cash' result = self.request_and_check( url, headers=JSON_HEADER, params=params, expected_content_type='text/json|application/json') data = json.loads(result.text) txns = data['set'][0].get('data', []) if not txns: break if start_date: last_dt = json_date_to_datetime(txns[-1]['odate']) if last_dt < start_date: keep_txns = [ t for t in txns if json_date_to_datetime(t['odate']) >= start_date] all_txns.extend(keep_txns) break all_txns.extend(txns) offset += len(txns) return all_txns
Returns the raw CSV transaction data as downloaded from Mint. If include_investment == True, also includes transactions that Mint classifies as investment-related. You may find that the investment transaction data is not sufficiently detailed to actually be useful, however.
def get_transactions_csv(self, include_investment=False, acct=0): """Returns the raw CSV transaction data as downloaded from Mint. If include_investment == True, also includes transactions that Mint classifies as investment-related. You may find that the investment transaction data is not sufficiently detailed to actually be useful, however. """ # Specifying accountId=0 causes Mint to return investment # transactions as well. Otherwise they are skipped by # default. params = None if include_investment or acct > 0: params = {'accountId': acct} result = self.request_and_check( '{}/transactionDownload.event'.format(MINT_ROOT_URL), params=params, expected_content_type='text/csv') return result.content
Returns the transaction data as a Pandas DataFrame.
def get_transactions(self, include_investment=False): """Returns the transaction data as a Pandas DataFrame.""" assert_pd() s = StringIO(self.get_transactions_csv( include_investment=include_investment)) s.seek(0) df = pd.read_csv(s, parse_dates=['Date']) df.columns = [c.lower().replace(' ', '_') for c in df.columns] df.category = (df.category.str.lower() .replace('uncategorized', pd.np.nan)) return df
Retrieve the payments JSON from this instance's Horizon server. Retrieve the payments JSON response for the account associated with this :class:`Address`. :param cursor: A paging token, specifying where to start returning records from. When streaming this can be set to "now" to stream object created since your request time. :type cursor: int, str :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :param bool sse: Use server side events for streaming responses.
def payments(self, cursor=None, order='asc', limit=10, sse=False): """Retrieve the payments JSON from this instance's Horizon server. Retrieve the payments JSON response for the account associated with this :class:`Address`. :param cursor: A paging token, specifying where to start returning records from. When streaming this can be set to "now" to stream object created since your request time. :type cursor: int, str :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :param bool sse: Use server side events for streaming responses. """ return self.horizon.account_payments(address=self.address, cursor=cursor, order=order, limit=limit, sse=sse)
Retrieve the offers JSON from this instance's Horizon server. Retrieve the offers JSON response for the account associated with this :class:`Address`. :param cursor: A paging token, specifying where to start returning records from. When streaming this can be set to "now" to stream object created since your request time. :type cursor: int, str :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :param bool sse: Use server side events for streaming responses.
def offers(self, cursor=None, order='asc', limit=10, sse=False): """Retrieve the offers JSON from this instance's Horizon server. Retrieve the offers JSON response for the account associated with this :class:`Address`. :param cursor: A paging token, specifying where to start returning records from. When streaming this can be set to "now" to stream object created since your request time. :type cursor: int, str :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :param bool sse: Use server side events for streaming responses. """ return self.horizon.account_offers(self.address, cursor=cursor, order=order, limit=limit, sse=sse)
Retrieve the transactions JSON from this instance's Horizon server. Retrieve the transactions JSON response for the account associated with this :class:`Address`. :param cursor: A paging token, specifying where to start returning records from. When streaming this can be set to "now" to stream object created since your request time. :type cursor: int, str :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :param bool sse: Use server side events for streaming responses.
def transactions(self, cursor=None, order='asc', limit=10, sse=False): """Retrieve the transactions JSON from this instance's Horizon server. Retrieve the transactions JSON response for the account associated with this :class:`Address`. :param cursor: A paging token, specifying where to start returning records from. When streaming this can be set to "now" to stream object created since your request time. :type cursor: int, str :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :param bool sse: Use server side events for streaming responses. """ return self.horizon.account_transactions( self.address, cursor=cursor, order=order, limit=limit, sse=sse)
Retrieve the operations JSON from this instance's Horizon server. Retrieve the operations JSON response for the account associated with this :class:`Address`. :param cursor: A paging token, specifying where to start returning records from. When streaming this can be set to "now" to stream object created since your request time. :type cursor: int, str :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :param bool sse: Use the SSE client for connecting to Horizon.
def operations(self, cursor=None, order='asc', limit=10, sse=False): """Retrieve the operations JSON from this instance's Horizon server. Retrieve the operations JSON response for the account associated with this :class:`Address`. :param cursor: A paging token, specifying where to start returning records from. When streaming this can be set to "now" to stream object created since your request time. :type cursor: int, str :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :param bool sse: Use the SSE client for connecting to Horizon. """ return self.horizon.account_operations( self.address, cursor=cursor, order=order, limit=limit, sse=sse)
Retrieve the trades JSON from this instance's Horizon server. Retrieve the trades JSON response for the account associated with this :class:`Address`. :param cursor: A paging token, specifying where to start returning records from. When streaming this can be set to "now" to stream object created since your request time. :type cursor: int, str :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :param bool sse: Use the SSE client for connecting to Horizon.
def trades(self, cursor=None, order='asc', limit=10, sse=False): """Retrieve the trades JSON from this instance's Horizon server. Retrieve the trades JSON response for the account associated with this :class:`Address`. :param cursor: A paging token, specifying where to start returning records from. When streaming this can be set to "now" to stream object created since your request time. :type cursor: int, str :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :param bool sse: Use the SSE client for connecting to Horizon. """ return self.horizon.account_trades( self.address, cursor=cursor, order=order, limit=limit, sse=sse)
Retrieve the effects JSON from this instance's Horizon server. Retrieve the effects JSON response for the account associated with this :class:`Address`. :param cursor: A paging token, specifying where to start returning records from. When streaming this can be set to "now" to stream object created since your request time. :type cursor: int, str :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :param bool sse: Use the SSE client for connecting to Horizon.
def effects(self, cursor=None, order='asc', limit=10, sse=False): """Retrieve the effects JSON from this instance's Horizon server. Retrieve the effects JSON response for the account associated with this :class:`Address`. :param cursor: A paging token, specifying where to start returning records from. When streaming this can be set to "now" to stream object created since your request time. :type cursor: int, str :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :param bool sse: Use the SSE client for connecting to Horizon. """ return self.horizon.account_effects( self.address, cursor=cursor, order=order, limit=limit, sse=sse)
Submit the transaction using a pooled connection, and retry on failure. `POST /transactions <https://www.stellar.org/developers/horizon/reference/endpoints/transactions-create.html>`_ Uses form-encoded data to send over to Horizon. :return: The JSON response indicating the success/failure of the submitted transaction. :rtype: dict
def submit(self, te): """Submit the transaction using a pooled connection, and retry on failure. `POST /transactions <https://www.stellar.org/developers/horizon/reference/endpoints/transactions-create.html>`_ Uses form-encoded data to send over to Horizon. :return: The JSON response indicating the success/failure of the submitted transaction. :rtype: dict """ params = {'tx': te} url = urljoin(self.horizon_uri, 'transactions/') # POST is not included in Retry's method_whitelist for a good reason. # our custom retry mechanism follows reply = None retry_count = self.num_retries while True: try: reply = self._session.post( url, data=params, timeout=self.request_timeout) return check_horizon_reply(reply.json()) except (RequestException, NewConnectionError, ValueError) as e: if reply is not None: msg = 'Horizon submit exception: {}, reply: [{}] {}'.format( str(e), reply.status_code, reply.text) else: msg = 'Horizon submit exception: {}'.format(str(e)) logging.warning(msg) if (reply is not None and reply.status_code not in self.status_forcelist) or retry_count <= 0: if reply is None: raise HorizonRequestError(e) raise HorizonError('Invalid horizon reply: [{}] {}'.format( reply.status_code, reply.text), reply.status_code) retry_count -= 1 logging.warning('Submit retry attempt {}'.format(retry_count)) sleep(self.backoff_factor)
Returns information and links relating to a single account. `GET /accounts/{account} <https://www.stellar.org/developers/horizon/reference/endpoints/accounts-single.html>`_ :param str address: The account ID to retrieve details about. :return: The account details in a JSON response. :rtype: dict
def account(self, address): """Returns information and links relating to a single account. `GET /accounts/{account} <https://www.stellar.org/developers/horizon/reference/endpoints/accounts-single.html>`_ :param str address: The account ID to retrieve details about. :return: The account details in a JSON response. :rtype: dict """ endpoint = '/accounts/{account_id}'.format(account_id=address) return self.query(endpoint)
This endpoint represents a single data associated with a given account. `GET /accounts/{account}/data/{key} <https://www.stellar.org/developers/horizon/reference/endpoints/data-for-account.html>`_ :param str address: The account ID to look up a data item from. :param str key: The name of the key for the data item in question. :return: The value of the data field for the given account and data key. :rtype: dict
def account_data(self, address, key): """This endpoint represents a single data associated with a given account. `GET /accounts/{account}/data/{key} <https://www.stellar.org/developers/horizon/reference/endpoints/data-for-account.html>`_ :param str address: The account ID to look up a data item from. :param str key: The name of the key for the data item in question. :return: The value of the data field for the given account and data key. :rtype: dict """ endpoint = '/accounts/{account_id}/data/{data_key}'.format( account_id=address, data_key=key) return self.query(endpoint)
This endpoint represents all effects that changed a given account. `GET /accounts/{account}/effects{?cursor,limit,order} <https://www.stellar.org/developers/horizon/reference/endpoints/effects-for-account.html>`_ :param str address: The account ID to look up effects for. :param cursor: A paging token, specifying where to start returning records from. When streaming this can be set to "now" to stream object created since your request time. :type cursor: int, str :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :param bool sse: Use server side events for streaming responses. :return: The list of effects in a JSON response. :rtype: dict
def account_effects(self, address, cursor=None, order='asc', limit=10, sse=False): """This endpoint represents all effects that changed a given account. `GET /accounts/{account}/effects{?cursor,limit,order} <https://www.stellar.org/developers/horizon/reference/endpoints/effects-for-account.html>`_ :param str address: The account ID to look up effects for. :param cursor: A paging token, specifying where to start returning records from. When streaming this can be set to "now" to stream object created since your request time. :type cursor: int, str :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :param bool sse: Use server side events for streaming responses. :return: The list of effects in a JSON response. :rtype: dict """ endpoint = '/accounts/{account_id}/effects'.format(account_id=address) params = self.__query_params(cursor=cursor, order=order, limit=limit) return self.query(endpoint, params, sse)
This endpoint represents all assets. It will give you all the assets in the system along with various statistics about each. See the documentation below for details on query parameters that are available. `GET /assets{?asset_code,asset_issuer,cursor,limit,order} <https://www.stellar.org/developers/horizon/reference/endpoints/assets-all.html>`_ :param str asset_code: Code of the Asset to filter by. :param str asset_issuer: Issuer of the Asset to filter by. :param int cursor: A paging token, specifying where to start returning records from. :param str order: The order in which to return rows, "asc" or "desc", ordered by asset_code then by asset_issuer. :param int limit: Maximum number of records to return. :return: A list of all valid payment operations :rtype: dict
def assets(self, asset_code=None, asset_issuer=None, cursor=None, order='asc', limit=10): """This endpoint represents all assets. It will give you all the assets in the system along with various statistics about each. See the documentation below for details on query parameters that are available. `GET /assets{?asset_code,asset_issuer,cursor,limit,order} <https://www.stellar.org/developers/horizon/reference/endpoints/assets-all.html>`_ :param str asset_code: Code of the Asset to filter by. :param str asset_issuer: Issuer of the Asset to filter by. :param int cursor: A paging token, specifying where to start returning records from. :param str order: The order in which to return rows, "asc" or "desc", ordered by asset_code then by asset_issuer. :param int limit: Maximum number of records to return. :return: A list of all valid payment operations :rtype: dict """ endpoint = '/assets' params = self.__query_params(asset_code=asset_code, asset_issuer=asset_issuer, cursor=cursor, order=order, limit=limit) return self.query(endpoint, params)
The transaction details endpoint provides information on a single transaction. `GET /transactions/{hash} <https://www.stellar.org/developers/horizon/reference/endpoints/transactions-single.html>`_ :param str tx_hash: The hex-encoded transaction hash. :return: A single transaction's details. :rtype: dict
def transaction(self, tx_hash): """The transaction details endpoint provides information on a single transaction. `GET /transactions/{hash} <https://www.stellar.org/developers/horizon/reference/endpoints/transactions-single.html>`_ :param str tx_hash: The hex-encoded transaction hash. :return: A single transaction's details. :rtype: dict """ endpoint = '/transactions/{tx_hash}'.format(tx_hash=tx_hash) return self.query(endpoint)
This endpoint represents all operations that are part of a given transaction. `GET /transactions/{hash}/operations{?cursor,limit,order} <https://www.stellar.org/developers/horizon/reference/endpoints/operations-for-transaction.html>`_ :param str tx_hash: The hex-encoded transaction hash. :param int cursor: A paging token, specifying where to start returning records from. :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :param bool include_failed: Set to `True` to include operations of failed transactions in results. :return: A single transaction's operations. :rtype: dict
def transaction_operations(self, tx_hash, cursor=None, order='asc', include_failed=False, limit=10): """This endpoint represents all operations that are part of a given transaction. `GET /transactions/{hash}/operations{?cursor,limit,order} <https://www.stellar.org/developers/horizon/reference/endpoints/operations-for-transaction.html>`_ :param str tx_hash: The hex-encoded transaction hash. :param int cursor: A paging token, specifying where to start returning records from. :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :param bool include_failed: Set to `True` to include operations of failed transactions in results. :return: A single transaction's operations. :rtype: dict """ endpoint = '/transactions/{tx_hash}/operations'.format(tx_hash=tx_hash) params = self.__query_params(cursor=cursor, order=order, limit=limit, include_failed=include_failed) return self.query(endpoint, params)
This endpoint represents all effects that occurred as a result of a given transaction. `GET /transactions/{hash}/effects{?cursor,limit,order} <https://www.stellar.org/developers/horizon/reference/endpoints/effects-for-transaction.html>`_ :param str tx_hash: The hex-encoded transaction hash. :param int cursor: A paging token, specifying where to start returning records from. :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :return: A single transaction's effects. :rtype: dict
def transaction_effects(self, tx_hash, cursor=None, order='asc', limit=10): """This endpoint represents all effects that occurred as a result of a given transaction. `GET /transactions/{hash}/effects{?cursor,limit,order} <https://www.stellar.org/developers/horizon/reference/endpoints/effects-for-transaction.html>`_ :param str tx_hash: The hex-encoded transaction hash. :param int cursor: A paging token, specifying where to start returning records from. :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :return: A single transaction's effects. :rtype: dict """ endpoint = '/transactions/{tx_hash}/effects'.format(tx_hash=tx_hash) params = self.__query_params(cursor=cursor, order=order, limit=limit) return self.query(endpoint, params)
Return, for each orderbook, a summary of the orderbook and the bids and asks associated with that orderbook. See the external docs below for information on the arguments required. `GET /order_book <https://www.stellar.org/developers/horizon/reference/endpoints/orderbook-details.html>`_ :param str selling_asset_code: Code of the Asset being sold. :param str buying_asset_code: Type of the Asset being bought. :param str selling_asset_issuer: Account ID of the issuer of the Asset being sold, if it is a native asset, let it be `None`. :param str buying_asset_issuer: Account ID of the issuer of the Asset being bought, if it is a native asset, let it be `None`. :param int limit: Limit the number of items returned. :return: A list of orderbook summaries as a JSON object. :rtype: dict
def order_book(self, selling_asset_code, buying_asset_code, selling_asset_issuer=None, buying_asset_issuer=None, limit=10): """Return, for each orderbook, a summary of the orderbook and the bids and asks associated with that orderbook. See the external docs below for information on the arguments required. `GET /order_book <https://www.stellar.org/developers/horizon/reference/endpoints/orderbook-details.html>`_ :param str selling_asset_code: Code of the Asset being sold. :param str buying_asset_code: Type of the Asset being bought. :param str selling_asset_issuer: Account ID of the issuer of the Asset being sold, if it is a native asset, let it be `None`. :param str buying_asset_issuer: Account ID of the issuer of the Asset being bought, if it is a native asset, let it be `None`. :param int limit: Limit the number of items returned. :return: A list of orderbook summaries as a JSON object. :rtype: dict """ selling_asset = Asset(selling_asset_code, selling_asset_issuer) buying_asset = Asset(buying_asset_code, buying_asset_issuer) asset_params = { 'selling_asset_type': selling_asset.type, 'selling_asset_code': None if selling_asset.is_native() else selling_asset.code, 'selling_asset_issuer': selling_asset.issuer, 'buying_asset_type': buying_asset.type, 'buying_asset_code': None if buying_asset.is_native() else buying_asset.code, 'buying_asset_issuer': buying_asset.issuer, } endpoint = '/order_book' params = self.__query_params(limit=limit, **asset_params) return self.query(endpoint, params)
The ledger details endpoint provides information on a single ledger. `GET /ledgers/{sequence} <https://www.stellar.org/developers/horizon/reference/endpoints/ledgers-single.html>`_ :param int ledger_id: The id of the ledger to look up. :return: The details of a single ledger. :rtype: dict
def ledger(self, ledger_id): """The ledger details endpoint provides information on a single ledger. `GET /ledgers/{sequence} <https://www.stellar.org/developers/horizon/reference/endpoints/ledgers-single.html>`_ :param int ledger_id: The id of the ledger to look up. :return: The details of a single ledger. :rtype: dict """ endpoint = '/ledgers/{ledger_id}'.format(ledger_id=ledger_id) return self.query(endpoint)
This endpoint represents all effects that occurred in the given ledger. `GET /ledgers/{id}/effects{?cursor,limit,order} <https://www.stellar.org/developers/horizon/reference/endpoints/effects-for-ledger.html>`_ :param int ledger_id: The id of the ledger to look up. :param int cursor: A paging token, specifying where to start returning records from. :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :return: The effects for a single ledger. :rtype: dict
def ledger_effects(self, ledger_id, cursor=None, order='asc', limit=10): """This endpoint represents all effects that occurred in the given ledger. `GET /ledgers/{id}/effects{?cursor,limit,order} <https://www.stellar.org/developers/horizon/reference/endpoints/effects-for-ledger.html>`_ :param int ledger_id: The id of the ledger to look up. :param int cursor: A paging token, specifying where to start returning records from. :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :return: The effects for a single ledger. :rtype: dict """ endpoint = '/ledgers/{ledger_id}/effects'.format(ledger_id=ledger_id) params = self.__query_params(cursor=cursor, order=order, limit=limit) return self.query(endpoint, params)
This endpoint represents all transactions in a given ledger. `GET /ledgers/{id}/transactions{?cursor,limit,order} <https://www.stellar.org/developers/horizon/reference/endpoints/transactions-for-ledger.html>`_ :param int ledger_id: The id of the ledger to look up. :param int cursor: A paging token, specifying where to start returning records from. :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :param bool include_failed: Set to `True` to include failed transactions in results. :return: The transactions contained in a single ledger. :rtype: dict
def ledger_transactions(self, ledger_id, cursor=None, order='asc', include_failed=False, limit=10): """This endpoint represents all transactions in a given ledger. `GET /ledgers/{id}/transactions{?cursor,limit,order} <https://www.stellar.org/developers/horizon/reference/endpoints/transactions-for-ledger.html>`_ :param int ledger_id: The id of the ledger to look up. :param int cursor: A paging token, specifying where to start returning records from. :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :param bool include_failed: Set to `True` to include failed transactions in results. :return: The transactions contained in a single ledger. :rtype: dict """ endpoint = '/ledgers/{ledger_id}/transactions'.format( ledger_id=ledger_id) params = self.__query_params(cursor=cursor, order=order, limit=limit, include_failed=include_failed) return self.query(endpoint, params)
This endpoint represents all effects. `GET /effects{?cursor,limit,order} <https://www.stellar.org/developers/horizon/reference/endpoints/effects-all.html>`_ :param cursor: A paging token, specifying where to start returning records from. When streaming this can be set to "now" to stream object created since your request time. :type cursor: int, str :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :param bool sse: Use server side events for streaming responses. :return: A list of all effects. :rtype: dict
def effects(self, cursor=None, order='asc', limit=10, sse=False): """This endpoint represents all effects. `GET /effects{?cursor,limit,order} <https://www.stellar.org/developers/horizon/reference/endpoints/effects-all.html>`_ :param cursor: A paging token, specifying where to start returning records from. When streaming this can be set to "now" to stream object created since your request time. :type cursor: int, str :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :param bool sse: Use server side events for streaming responses. :return: A list of all effects. :rtype: dict """ endpoint = '/effects' params = self.__query_params(cursor=cursor, order=order, limit=limit) return self.query(endpoint, params, sse)
This endpoint represents all operations that are part of validated transactions. `GET /operations{?cursor,limit,order} <https://www.stellar.org/developers/horizon/reference/endpoints/operations-all.html>`_ :param cursor: A paging token, specifying where to start returning records from. When streaming this can be set to "now" to stream object created since your request time. :type cursor: int, str :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :param bool include_failed: Set to `True` to include operations of failed transactions in results. :param bool sse: Use server side events for streaming responses. :return: A list of all operations. :rtype: dict
def operations(self, cursor=None, order='asc', limit=10, include_failed=False, sse=False): """This endpoint represents all operations that are part of validated transactions. `GET /operations{?cursor,limit,order} <https://www.stellar.org/developers/horizon/reference/endpoints/operations-all.html>`_ :param cursor: A paging token, specifying where to start returning records from. When streaming this can be set to "now" to stream object created since your request time. :type cursor: int, str :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :param bool include_failed: Set to `True` to include operations of failed transactions in results. :param bool sse: Use server side events for streaming responses. :return: A list of all operations. :rtype: dict """ endpoint = '/operations' params = self.__query_params(cursor=cursor, order=order, limit=limit, include_failed=include_failed) return self.query(endpoint, params, sse)
The operation details endpoint provides information on a single operation. `GET /operations/{id} <https://www.stellar.org/developers/horizon/reference/endpoints/operations-single.html>`_ :param id op_id: The operation ID to get details on. :return: Details on a single operation. :rtype: dict
def operation(self, op_id): """The operation details endpoint provides information on a single operation. `GET /operations/{id} <https://www.stellar.org/developers/horizon/reference/endpoints/operations-single.html>`_ :param id op_id: The operation ID to get details on. :return: Details on a single operation. :rtype: dict """ endpoint = '/operations/{op_id}'.format(op_id=op_id) return self.query(endpoint)
This endpoint represents all effects that occurred as a result of a given operation. `GET /operations/{id}/effects{?cursor,limit,order} <https://www.stellar.org/developers/horizon/reference/endpoints/effects-for-operation.html>`_ :param int op_id: The operation ID to get effects on. :param int cursor: A paging token, specifying where to start returning records from. :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :return: A list of effects on the given operation. :rtype: dict
def operation_effects(self, op_id, cursor=None, order='asc', limit=10): """This endpoint represents all effects that occurred as a result of a given operation. `GET /operations/{id}/effects{?cursor,limit,order} <https://www.stellar.org/developers/horizon/reference/endpoints/effects-for-operation.html>`_ :param int op_id: The operation ID to get effects on. :param int cursor: A paging token, specifying where to start returning records from. :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :return: A list of effects on the given operation. :rtype: dict """ endpoint = '/operations/{op_id}/effects'.format(op_id=op_id) params = self.__query_params(cursor=cursor, order=order, limit=limit) return self.query(endpoint, params)
Load a list of assets available to the source account id and find any payment paths from those source assets to the desired destination asset. See the below docs for more information on required and optional parameters for further specifying your search. `GET /paths <https://www.stellar.org/developers/horizon/reference/endpoints/path-finding.html>`_ :param str destination_account: The destination account that any returned path should use. :param str destination_amount: The amount, denominated in the destination asset, that any returned path should be able to satisfy. :param str source_account: The sender's account id. Any returned path must use a source that the sender can hold. :param str destination_asset_code: The asset code for the destination. :param destination_asset_issuer: The asset issuer for the destination, if it is a native asset, let it be `None`. :type destination_asset_issuer: str, None :return: A list of paths that can be used to complete a payment based on a given query. :rtype: dict
def paths(self, destination_account, destination_amount, source_account, destination_asset_code, destination_asset_issuer=None): """Load a list of assets available to the source account id and find any payment paths from those source assets to the desired destination asset. See the below docs for more information on required and optional parameters for further specifying your search. `GET /paths <https://www.stellar.org/developers/horizon/reference/endpoints/path-finding.html>`_ :param str destination_account: The destination account that any returned path should use. :param str destination_amount: The amount, denominated in the destination asset, that any returned path should be able to satisfy. :param str source_account: The sender's account id. Any returned path must use a source that the sender can hold. :param str destination_asset_code: The asset code for the destination. :param destination_asset_issuer: The asset issuer for the destination, if it is a native asset, let it be `None`. :type destination_asset_issuer: str, None :return: A list of paths that can be used to complete a payment based on a given query. :rtype: dict """ destination_asset = Asset(destination_asset_code, destination_asset_issuer) destination_asset_params = { 'destination_asset_type': destination_asset.type, 'destination_asset_code': None if destination_asset.is_native() else destination_asset.code, 'destination_asset_issuer': destination_asset.issuer } endpoint = '/paths' params = self.__query_params(destination_account=destination_account, source_account=source_account, destination_amount=destination_amount, **destination_asset_params ) return self.query(endpoint, params)
Load a list of trades, optionally filtered by an orderbook. See the below docs for more information on required and optional parameters for further specifying your search. `GET /trades <https://www.stellar.org/developers/horizon/reference/endpoints/trades.html>`_ :param str base_asset_code: Code of base asset. :param str base_asset_issuer: Issuer of base asset, if it is a native asset, let it be `None`. :param str counter_asset_code: Code of counter asset. :param str counter_asset_issuer: Issuer of counter asset, if it is a native asset, let it be `None`. :param int offer_id: Filter for by a specific offer id. :param int cursor: A paging token, specifying where to start returning records from. :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :return: A list of trades filtered by a given query. :rtype: dict
def trades(self, base_asset_code=None, counter_asset_code=None, base_asset_issuer=None, counter_asset_issuer=None, offer_id=None, cursor=None, order='asc', limit=10): """Load a list of trades, optionally filtered by an orderbook. See the below docs for more information on required and optional parameters for further specifying your search. `GET /trades <https://www.stellar.org/developers/horizon/reference/endpoints/trades.html>`_ :param str base_asset_code: Code of base asset. :param str base_asset_issuer: Issuer of base asset, if it is a native asset, let it be `None`. :param str counter_asset_code: Code of counter asset. :param str counter_asset_issuer: Issuer of counter asset, if it is a native asset, let it be `None`. :param int offer_id: Filter for by a specific offer id. :param int cursor: A paging token, specifying where to start returning records from. :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :return: A list of trades filtered by a given query. :rtype: dict """ base_asset = Asset(base_asset_code, base_asset_issuer) counter_asset = Asset(counter_asset_code, counter_asset_issuer) asset_params = { 'base_asset_type': base_asset.type, 'base_asset_code': None if base_asset.is_native() else base_asset.code, 'base_asset_issuer': base_asset.issuer, 'counter_asset_type': counter_asset.type, 'counter_asset_code': None if counter_asset.is_native() else counter_asset.code, 'counter_asset_issuer': counter_asset.issuer } endpoint = '/trades' params = self.__query_params(offer_id=offer_id, cursor=cursor, order=order, limit=limit, **asset_params) return self.query(endpoint, params)
Load a list of aggregated historical trade data, optionally filtered by an orderbook. `GET /trade_aggregations <https://www.stellar.org/developers/horizon/reference/endpoints/trade_aggregations.html>`_ :param int start_time: Lower time boundary represented as millis since epoch. :param int end_time: Upper time boundary represented as millis since epoch. :param int resolution: Segment duration as millis since epoch. Supported values are 1 minute (60000), 5 minutes (300000), 15 minutes (900000), 1 hour (3600000), 1 day (86400000) and 1 week (604800000). :param str base_asset_code: Code of base asset. :param str base_asset_issuer: Issuer of base asset, if it is a native asset, let it be `None`. :param str counter_asset_code: Code of counter asset. :param str counter_asset_issuer: Issuer of counter asset, if it is a native asset, let it be `None`. :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :param int offset: segments can be offset using this parameter. Expressed in milliseconds. *Can only be used if the resolution is greater than 1 hour. Value must be in whole hours, less than the provided resolution, and less than 24 hours. :return: A list of collected trade aggregations. :rtype: dict
def trade_aggregations(self, resolution, base_asset_code, counter_asset_code, base_asset_issuer=None, counter_asset_issuer=None, start_time=None, end_time=None, order='asc', limit=10, offset=0): """Load a list of aggregated historical trade data, optionally filtered by an orderbook. `GET /trade_aggregations <https://www.stellar.org/developers/horizon/reference/endpoints/trade_aggregations.html>`_ :param int start_time: Lower time boundary represented as millis since epoch. :param int end_time: Upper time boundary represented as millis since epoch. :param int resolution: Segment duration as millis since epoch. Supported values are 1 minute (60000), 5 minutes (300000), 15 minutes (900000), 1 hour (3600000), 1 day (86400000) and 1 week (604800000). :param str base_asset_code: Code of base asset. :param str base_asset_issuer: Issuer of base asset, if it is a native asset, let it be `None`. :param str counter_asset_code: Code of counter asset. :param str counter_asset_issuer: Issuer of counter asset, if it is a native asset, let it be `None`. :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :param int offset: segments can be offset using this parameter. Expressed in milliseconds. *Can only be used if the resolution is greater than 1 hour. Value must be in whole hours, less than the provided resolution, and less than 24 hours. :return: A list of collected trade aggregations. :rtype: dict """ allowed_resolutions = (60000, 300000, 900000, 3600000, 86400000, 604800000) if resolution not in allowed_resolutions: raise NotValidParamError("resolution is invalid") if offset > resolution or offset >= 24 * 3600000 or offset % 3600000 != 0: raise NotValidParamError("offset is invalid") base_asset = Asset(base_asset_code, base_asset_issuer) counter_asset = Asset(counter_asset_code, counter_asset_issuer) asset_params = { 'base_asset_type': base_asset.type, 'base_asset_code': None if base_asset.is_native() else base_asset.code, 'base_asset_issuer': base_asset.issuer, 'counter_asset_type': counter_asset.type, 'counter_asset_code': None if counter_asset.is_native() else counter_asset.code, 'counter_asset_issuer': counter_asset.issuer } endpoint = '/trade_aggregations' params = self.__query_params(start_time=start_time, end_time=end_time, resolution=resolution, order=order, limit=limit, offset=offset, **asset_params) return self.query(endpoint, params)
This endpoint represents all trades for a given offer. `GET /offers/{offer_id}/trades{?cursor,limit,order} <https://www.stellar.org/developers/horizon/reference/endpoints/trades-for-offer.html>`_ :param int offer_id: The offer ID to get trades on. :param int cursor: A paging token, specifying where to start returning records from. :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :return: A list of effects on the given operation. :rtype: dict
def offer_trades(self, offer_id, cursor=None, order='asc', limit=10): """This endpoint represents all trades for a given offer. `GET /offers/{offer_id}/trades{?cursor,limit,order} <https://www.stellar.org/developers/horizon/reference/endpoints/trades-for-offer.html>`_ :param int offer_id: The offer ID to get trades on. :param int cursor: A paging token, specifying where to start returning records from. :param str order: The order in which to return rows, "asc" or "desc". :param int limit: Maximum number of records to return. :return: A list of effects on the given operation. :rtype: dict """ endpoint = '/offers/{offer_id}/trades'.format(offer_id=offer_id) params = self.__query_params(cursor=cursor, order=order, limit=limit) return self.query(endpoint, params)
Fetch the base fee from the latest ledger. In the future, we'll fetch the base fee from `/fee_stats` :return: base free :rtype: int
def base_fee(self): """Fetch the base fee from the latest ledger. In the future, we'll fetch the base fee from `/fee_stats` :return: base free :rtype: int """ latest_ledger = self.ledgers(order='desc', limit=1) try: base_fee = latest_ledger['_embedded']['records'][0]['base_fee_in_stroops'] except (KeyError, IndexError): base_fee = 100 return base_fee
Sign this transaction envelope with a given keypair. Note that the signature must not already be in this instance's list of signatures. :param keypair: The keypair to use for signing this transaction envelope. :type keypair: :class:`Keypair <stellar_base.keypair.Keypair>` :raises: :exc:`SignatureExistError <stellar_base.utils.SignatureExistError>`
def sign(self, keypair): """Sign this transaction envelope with a given keypair. Note that the signature must not already be in this instance's list of signatures. :param keypair: The keypair to use for signing this transaction envelope. :type keypair: :class:`Keypair <stellar_base.keypair.Keypair>` :raises: :exc:`SignatureExistError <stellar_base.utils.SignatureExistError>` """ assert isinstance(keypair, Keypair) tx_hash = self.hash_meta() sig = keypair.sign_decorated(tx_hash) sig_dict = [signature.__dict__ for signature in self.signatures] if sig.__dict__ in sig_dict: raise SignatureExistError('The keypair has already signed') else: self.signatures.append(sig)
Sign this transaction envelope with a Hash(X) signature. See Stellar's documentation on `Multi-Sig <https://www.stellar.org/developers/guides/concepts/multi-sig.html>`_ for more details on Hash(x) signatures. :param preimage: 32 byte hash or hex encoded string, the "x" value to be hashed and used as a signature. :type preimage: str, bytes
def sign_hashX(self, preimage): """Sign this transaction envelope with a Hash(X) signature. See Stellar's documentation on `Multi-Sig <https://www.stellar.org/developers/guides/concepts/multi-sig.html>`_ for more details on Hash(x) signatures. :param preimage: 32 byte hash or hex encoded string, the "x" value to be hashed and used as a signature. :type preimage: str, bytes """ # if len(preimage) > 64: # raise PreimageLengthError('preimage must <= 64 bytes') preimage = convert_hex_to_bytes(preimage) sig = hashX_sign_decorated(preimage) sig_dict = [signature.__dict__ for signature in self.signatures] if sig.__dict__ in sig_dict: raise SignatureExistError('The preimage has already signed.') else: self.signatures.append(sig)
Get the signature base of this transaction envelope. Return the "signature base" of this transaction, which is the value that, when hashed, should be signed to create a signature that validators on the Stellar Network will accept. It is composed of a 4 prefix bytes followed by the xdr-encoded form of this transaction. :return: The signature base of this transaction envelope.
def signature_base(self): """Get the signature base of this transaction envelope. Return the "signature base" of this transaction, which is the value that, when hashed, should be signed to create a signature that validators on the Stellar Network will accept. It is composed of a 4 prefix bytes followed by the xdr-encoded form of this transaction. :return: The signature base of this transaction envelope. """ network_id = self.network_id tx_type = Xdr.StellarXDRPacker() tx_type.pack_EnvelopeType(Xdr.const.ENVELOPE_TYPE_TX) tx_type = tx_type.get_buffer() tx = Xdr.StellarXDRPacker() tx.pack_Transaction(self.tx.to_xdr_object()) tx = tx.get_buffer() return network_id + tx_type + tx
Get an XDR object representation of this :class:`TransactionEnvelope`.
def to_xdr_object(self): """Get an XDR object representation of this :class:`TransactionEnvelope`. """ tx = self.tx.to_xdr_object() return Xdr.types.TransactionEnvelope(tx, self.signatures)
Get the base64 encoded XDR string representing this :class:`TransactionEnvelope`.
def xdr(self): """Get the base64 encoded XDR string representing this :class:`TransactionEnvelope`. """ te = Xdr.StellarXDRPacker() te.pack_TransactionEnvelope(self.to_xdr_object()) te = base64.b64encode(te.get_buffer()) return te
Create a new :class:`TransactionEnvelope` from an XDR string. :param xdr: The XDR string that represents a transaction envelope. :type xdr: bytes, str
def from_xdr(cls, xdr): """Create a new :class:`TransactionEnvelope` from an XDR string. :param xdr: The XDR string that represents a transaction envelope. :type xdr: bytes, str """ xdr_decoded = base64.b64decode(xdr) te = Xdr.StellarXDRUnpacker(xdr_decoded) te_xdr_object = te.unpack_TransactionEnvelope() signatures = te_xdr_object.signatures tx_xdr_object = te_xdr_object.tx tx = Transaction.from_xdr_object(tx_xdr_object) te = TransactionEnvelope(tx, signatures=signatures) # te = TransactionEnvelope( # tx, {'signatures': signatures, 'network_id': 'PUBLIC'}) return te
table for caclulating CRC (list of 256 integers) :param bytes data: Data for calculating CRC. :param int crc: Initial value. :param list table: Table for caclulating CRC (list of 256 integers) :return: calculated value of CRC
def _crc16(data, crc, table): """table for caclulating CRC (list of 256 integers) :param bytes data: Data for calculating CRC. :param int crc: Initial value. :param list table: Table for caclulating CRC (list of 256 integers) :return: calculated value of CRC """ bytes_to_int = lambda x: ord(x) if sys.version_info.major == 2 else x for byte in data: crc = ((crc << 8) & 0xff00) ^ table[((crc >> 8) & 0xff) ^ bytes_to_int(byte)] return crc & 0xffff
Send a federation query to a Stellar Federation service. For more info, see the `complete guide on Stellar Federation. <https://www.stellar.org/developers/guides/concepts/federation.html>`_. :param str address_or_id: The address which you expect te retrieve federation information about. :param str fed_type: The type of federation query that you are making. Must be 'name', 'id', 'forward', or 'txid'. :param str domain: The domain that corresponds to the address or ID; this is where the stellar.toml file lives (which ultimately points to the URL of the federation service). :param bool allow_http: Whether to allow for requests over plain HTTP over HTTPS. Note - you should *always* use HTTPS outside of testing. :return dict: The federation query response decoded from JSON as a dict.
def federation(address_or_id, fed_type='name', domain=None, allow_http=False): """Send a federation query to a Stellar Federation service. For more info, see the `complete guide on Stellar Federation. <https://www.stellar.org/developers/guides/concepts/federation.html>`_. :param str address_or_id: The address which you expect te retrieve federation information about. :param str fed_type: The type of federation query that you are making. Must be 'name', 'id', 'forward', or 'txid'. :param str domain: The domain that corresponds to the address or ID; this is where the stellar.toml file lives (which ultimately points to the URL of the federation service). :param bool allow_http: Whether to allow for requests over plain HTTP over HTTPS. Note - you should *always* use HTTPS outside of testing. :return dict: The federation query response decoded from JSON as a dict. """ if fed_type == 'name': if '*' not in address_or_id: raise FederationError('Not a valid federation address.') param, domain = address_or_id.rsplit('*', 1) if param == '' or domain == '': raise FederationError('Not a valid federation address.') elif fed_type == 'id': try: assert is_valid_address(address_or_id) except StellarAddressInvalidError: raise FederationError('{} is not a valid account id.'.format(address_or_id)) else: raise FederationError('Not a valid fed_type.') if '.' not in domain: raise FederationError('Not a valid domain name.') fed_service = get_federation_service(domain, allow_http) if not fed_service: raise FederationError('Not a valid federation server.') return _get_federation_info(address_or_id, fed_service, fed_type)
Send a federation query to a Stellar Federation service. Note: The preferred method of making this call is via :function:`federation`, as it handles error checking and parsing of arguments. :param str address_or_id: The address which you expect te retrieve federation information about. :param str federation_service: The url of the federation service you're requesting information from. :param str fed_type: The type of federation query that you are making. Must be 'name', 'id', 'forward', or 'txid'. :return dict: The federation query response decoded from JSON as a dict.
def _get_federation_info(address_or_id, federation_service, fed_type='name'): """Send a federation query to a Stellar Federation service. Note: The preferred method of making this call is via :function:`federation`, as it handles error checking and parsing of arguments. :param str address_or_id: The address which you expect te retrieve federation information about. :param str federation_service: The url of the federation service you're requesting information from. :param str fed_type: The type of federation query that you are making. Must be 'name', 'id', 'forward', or 'txid'. :return dict: The federation query response decoded from JSON as a dict. """ params = {'q': address_or_id, 'type': fed_type} r = requests.get(federation_service, params=params) if r.status_code == 200: return r.json() else: return None
Retrieve the FEDERATION_SERVER config from a domain's stellar.toml. :param str domain: The domain the .toml file is hosted at. :param bool allow_http: Specifies whether the request should go over plain HTTP vs HTTPS. Note it is recommend that you *always* use HTTPS. :return str: The FEDERATION_SERVER url.
def get_federation_service(domain, allow_http=False): """Retrieve the FEDERATION_SERVER config from a domain's stellar.toml. :param str domain: The domain the .toml file is hosted at. :param bool allow_http: Specifies whether the request should go over plain HTTP vs HTTPS. Note it is recommend that you *always* use HTTPS. :return str: The FEDERATION_SERVER url. """ st = get_stellar_toml(domain, allow_http) if not st: return None return st.get('FEDERATION_SERVER')
Retrieve the AUTH_SERVER config from a domain's stellar.toml. :param str domain: The domain the .toml file is hosted at. :param bool allow_http: Specifies whether the request should go over plain HTTP vs HTTPS. Note it is recommend that you *always* use HTTPS. :return str: The AUTH_SERVER url.
def get_auth_server(domain, allow_http=False): """Retrieve the AUTH_SERVER config from a domain's stellar.toml. :param str domain: The domain the .toml file is hosted at. :param bool allow_http: Specifies whether the request should go over plain HTTP vs HTTPS. Note it is recommend that you *always* use HTTPS. :return str: The AUTH_SERVER url. """ st = get_stellar_toml(domain, allow_http) if not st: return None return st.get('AUTH_SERVER')
Retrieve the stellar.toml file from a given domain. Retrieve the stellar.toml file for information about interacting with Stellar's federation protocol for a given Stellar Anchor (specified by a domain). :param str domain: The domain the .toml file is hosted at. :param bool allow_http: Specifies whether the request should go over plain HTTP vs HTTPS. Note it is recommend that you *always* use HTTPS. :return: The stellar.toml file as a an object via :func:`toml.loads`.
def get_stellar_toml(domain, allow_http=False): """Retrieve the stellar.toml file from a given domain. Retrieve the stellar.toml file for information about interacting with Stellar's federation protocol for a given Stellar Anchor (specified by a domain). :param str domain: The domain the .toml file is hosted at. :param bool allow_http: Specifies whether the request should go over plain HTTP vs HTTPS. Note it is recommend that you *always* use HTTPS. :return: The stellar.toml file as a an object via :func:`toml.loads`. """ toml_link = '/.well-known/stellar.toml' if allow_http: protocol = 'http://' else: protocol = 'https://' url_list = ['', 'www.', 'stellar.'] url_list = [protocol + url + domain + toml_link for url in url_list] for url in url_list: r = requests.get(url) if r.status_code == 200: return toml.loads(r.text) return None
Add an :class:`Operation <stellar_base.operation.Operation>` to this transaction. This method will only add an operation if it is not already in the transaction's list of operations, i.e. every operation in the transaction should be unique. :param Operation operation: The operation to add to this transaction.
def add_operation(self, operation): """Add an :class:`Operation <stellar_base.operation.Operation>` to this transaction. This method will only add an operation if it is not already in the transaction's list of operations, i.e. every operation in the transaction should be unique. :param Operation operation: The operation to add to this transaction. """ if operation not in self.operations: self.operations.append(operation)
Creates an XDR Transaction object that represents this :class:`Transaction`.
def to_xdr_object(self): """Creates an XDR Transaction object that represents this :class:`Transaction`. """ source_account = account_xdr_object(self.source) memo = self.memo.to_xdr_object() operations = [o.to_xdr_object() for o in self.operations] ext = Xdr.nullclass() ext.v = 0 return Xdr.types.Transaction(source_account, self.fee, self.sequence, self.time_bounds, memo, operations, ext)
Packs and base64 encodes this :class:`Transaction` as an XDR string.
def xdr(self): """Packs and base64 encodes this :class:`Transaction` as an XDR string. """ tx = Xdr.StellarXDRPacker() tx.pack_Transaction(self.to_xdr_object()) return base64.b64encode(tx.get_buffer())