Contents Menu Expand Light mode Dark mode Auto light/dark mode
Trading Strategy documentation
  • Documention home
  • Getting started
  • Overview
    • About Trading Strategy
    • Supported markets and venues
    • Accessing market data
    • Tooling
    • Oracles
  • Developing strategies
    • Setting up development environment
      • Github Codespaces
      • Visual Studio Code Dev Container for Jupyter Notebooks
      • Docker development image
      • PyCharm
      • Local Python installation
      • Google Colab
      • Binder development
    • Trading strategy examples
    • Code examples
      • Getting started coding tutorial (old)
      • Drawing DEX prices using OHLCV candle charts
      • Interactive charts
      • Technical analysis
      • Exploring trading pairs
      • Finding low fee trading pairs
      • Preface
      • Liquidity analysis
      • Price impact estimation
      • Query pool liquidity on a decentralised exchange
      • Dataset download
      • Charts and diagrams (old)
      • Lending protocols and short/long leverage data
      • Loading exchange, pair, and candlestick data for Uniswap V3
      • Streaming JSONL data
    • Market data format details
      • Market data client
      • OHLCV Candle format
      • Tracked trading pairs and tokens
      • US dollar price conversion
      • Trading pair naming conventions
      • Internal ids
      • Token tax and deflationary tokens
      • Good trading pairs to start with
      • Wrapped tokens
      • Profitability calculations
    • Troubleshooting
    • Internal development process
  • Architecture
    • Architecture overview
    • Command line application
    • Webhook server
    • Strategy types
    • Serialisation
    • Unit testing
  • Deploying live trading strategies
    • Trade-executor command
    • Live trading modes
    • Strategy metadata
    • Hot wallet deployment
    • Vault deployment
    • Lagoon vault deployment
    • Velvet portfolio deployment
    • Website and monitoring
    • Managing Docker images
    • Turning backtest to an executable live trading strategy
    • Troubleshooting live trade execution deployments
    • Repairing frozen trading positions
    • Vault manual transactions
  • Learn algorithmic trading
    • To follow
    • Conference presentations and videos
    • Books on algorithmic trading
    • Online courses on algorithmic trading
    • Tutorials on algorithmic trading
    • AI and machine learning
    • Papers about algorithmic trading
    • Python
    • Jupyter Notebook learning material
    • Algorithmic trading frameworks for Python
    • Communities around algorithmic trading
    • Develop tools and Jupyter Notebook environments
    • Charting solutions for Python
    • Additional algorithmic trading links
    • Developing portfolio construction trading strategies
  • Glossary
  • API reference
    • Market data client
      • client
        • BaseClient
        • Client
      • chain
        • ChainId
      • exchange
        • Exchange
        • ExchangeType
        • ExchangeUniverse
      • pair
        • DEXPair
        • LegacyPairUniverse
        • PandasPairUniverse
        • generate_address_columns
        • resolve_pairs_based_on_ticker
      • candle
        • Candle
        • CandleResult
        • GroupedCandleUniverse
        • TradingPairDataAvailability
        • is_candle_green
        • is_candle_red
      • liquidity
        • GroupedLiquidityUniverse
        • LiquidityResult
        • ResampledLiquidityUniverse
        • XYLiquidity
      • trade
        • Trade
      • timebucket
        • TimeBucket
      • token
        • Token
      • reader
        • read_parquet
      • priceimpact
        • HistoricalXYPriceImpactCalculator
        • LiquiditySampleMeasure
        • PriceImpact
        • estimate_xyk_price_impact
      • stablecoin
        • is_stablecoin_like
      • types
      • utils
        • aggregate_ohlcv
          • AggregateId
          • aggregate_ohlcv_across_pairs
          • build_aggregate_map
          • calculate_volume_weighted_ohlcv
          • make_aggregate_id
        • columnar
          • iterate_columnar_dicts
        • df_index
          • flatten_dataframe_datetime_index
          • get_timestamp_index
        • format
          • format_duration_days_hours_mins
          • format_percent
          • format_percent_2_decimals
          • format_price
          • format_value
          • string_to_eth_address
        • forward_fill
          • fill_future_gap
          • fill_future_gap_multi_pair
          • forward_fill
          • generate_future_filler_data
        • gap
          • Gap
          • detect_frequency
          • detect_timestamp_gaps
          • equalise_timestamp_index
          • fill_missing_ohlcv
        • groupeduniverse
          • PairGroupedUniverse
          • filter_for_pairs
          • filter_for_single_pair
          • resample_candles
          • resample_dataframe
          • resample_price_series
          • resample_rolling
          • resample_series
        • jupyter
          • JupyterOutputMode
          • display_with_styles
          • format_links_for_html_output
          • get_notebook_output_mode
          • is_pyodide
          • make_clickable
        • liquidity_filter
          • build_liquidity_summary
          • get_liquidity_today
          • get_somewhat_realistic_max_liquidity
          • get_top_liquidity_pairs_by_base_token
          • prefilter_pairs_with_tvl
        • logging_retry
          • LoggingRetry
        • mapper
        • schema
          • append_to_columnar_work_buffer
          • create_columnar_work_buffer
          • create_pyarrow_schema_for_dataclass
          • map_field_to_arrow
          • unmappable
        • time
          • assert_compatible_timestamp
          • floor_pandas_month
          • floor_pandas_week
          • generate_monthly_timestamps
          • get_prior_timestamp
          • is_compatible_timestamp
          • naive_utcfromtimestamp
          • naive_utcnow
          • to_int_unix_timestamp
          • to_unix_timestamp
        • token_extra_data
          • filter_scams
          • load_extra_metadata
          • load_token_metadata
        • token_filter
          • StablecoinFilteringMode
          • add_base_quote_address_columns
          • deduplicate_pairs_by_volume
          • filter_by_token_sniffer_score
          • filter_for_base_tokens
          • filter_for_blacklisted_tokens
          • filter_for_chain
          • filter_for_derivatives
          • filter_for_exchange
          • filter_for_exchange_ids
          • filter_for_exchange_slugs
          • filter_for_exchanges
          • filter_for_nonascii_tokens
          • filter_for_quote_tokens
          • filter_for_rebases
          • filter_for_stablecoins
          • filter_for_trading_fee
          • filter_pairs_default
          • is_derivative
          • is_rebase
        • wrangle
          • examine_anomalies
          • examine_price_between_time_anomalies
          • filter_bad_wicks
          • fix_bad_wicks
          • fix_dex_price_data
          • fix_prices_in_between_time_frames
          • heal_anomalies
          • normalise_volume
          • remove_min_max_price
          • remove_zero_candles
      • transport
        • base
          • BaseTransport
        • cache
          • CacheStatus
          • CachedHTTPTransport
          • OHLCVCandleType
          • wait_other_writers
        • data_trigger
          • wait_for_data
        • jsonl
          • load_candles_jsonl
          • load_token_metadata_jsonl
          • load_trading_strategy_like_jsonl_data
        • progress_enabled_download
          • download_with_tqdm_progress_bar
        • pyodide
        • token_cache
          • TokenCacheEntry
          • calculate_token_cache_summary
          • display_token_metadata
          • read_token_cache
      • charting
        • candle_chart
          • VolumeBarMode
          • create_label
          • make_candle_labels
          • validate_ohclv_dataframe
          • validate_plot_info
          • visualise_ohlcv
      • testing
        • mock_client
          • MockClient
        • uniswap_v2_mock_client
          • UniswapV2MockClient
      • top
        • TopPairData
        • TopPairMethod
        • TopPairsReply
      • binance
        • constants
          • split_binance_symbol
        • downloader
          • BinanceDownloader
          • clean_time_series_data
          • get_binance_interval
          • get_indices_of_uneven_intervals
        • utils
          • add_info_columns_to_ohlc
          • generate_exchange_for_binance
          • generate_exchange_universe_for_binance
          • generate_lending_reserve_for_binance
          • generate_pair_for_binance
          • generate_pairs_for_binance
      • alternative_data
        • coingecko
          • CoingeckoClient
          • CoingeckoEntry
          • CoingeckoUniverse
          • categorise_pairs
          • fetch_top_coins
      • direct_feed
        • candle_feed
          • CandleFeed
          • prepare_raw_candle_data
        • conversion
          • CurrencyConversion
          • convert_to_float
        • dash
        • direct_feed_pair
        • ohlcv_aggregate
          • OHLCVCandle
          • get_feed_for_pair
          • resample_trades_into_ohlcv
          • truncate_ohlcv
        • store
          • DirectFeedStore
        • synthetic_feed
          • SyntheticTradeFeed
        • timeframe
          • Timeframe
        • trade_feed
          • SaveHook
          • Trade
          • TradeDelta
          • TradeFeed
        • trade_store
          • ParquetFileStore
          • TradeFeedStore
        • uniswap_v2
          • SwapKind
          • UniswapV2TradeFeed
          • calculate_reserve_price_in_quote_token_decimal
          • decode_swap
          • decode_sync
        • warn
          • disable_pandas_warnings
    • Trade execution engine
      • state
        • balance_update
          • BalanceUpdate
          • BalanceUpdateCause
          • BalanceUpdatePositionType
        • blockhain_transaction
          • BlockchainTransaction
          • BlockchainTransactionType
          • JSONAssetDelta
          • solidity_arg_encoder
        • freeze
          • freeze_position_on_failed_trade
        • generic_position
          • GenericPosition
        • identifier
          • AssetIdentifier
          • AssetType
          • AssetWithTrackedValue
          • ExchangeType
          • TradingPairIdentifier
          • TradingPairKind
        • interest
          • Interest
        • interest_distribution
          • AssetInterestData
          • InterestDistributionEntry
          • InterestDistributionOperation
        • loan
          • Loan
          • LoanSide
        • metadata
          • EnzymeSmartContracts
          • Metadata
          • OnChainData
          • VelvetSmartContracts
        • other_data
          • OtherData
        • pickle_over_json
          • decode_pickle_over_json
          • encode_pickle_over_json
        • portfolio
          • Portfolio
        • position
          • PositionOtherData
          • TradingPosition
          • TriggerPriceUpdate
        • repair
          • RepairResult
          • close_position_with_empty_trade
          • find_trades_to_be_repaired
          • make_counter_trade
          • reconfirm_trade
          • repair_trade
          • repair_trades
          • repair_tx_missing
          • repair_tx_not_generated
          • repair_zero_quantity
          • unfreeze_position
        • reserve
          • ReservePosition
        • retry
          • rebroadcast_trade
          • retry_trades
        • revaluation
          • RevalueEvent
        • size_risk
          • SizeRisk
          • SizingType
        • state
          • BacktestData
          • State
        • statistics
          • FinalPositionStatistics
          • PortfolioStatistics
          • PositionStatistics
          • Statistics
          • calculate_naive_profitability
        • store
          • JSONFileStore
          • NoneStore
          • SimulateStore
          • StateStore
          • StateStoreModel
        • sync
          • Accounting
          • BalanceEventRef
          • Deployment
          • InterestSync
          • Sync
          • Treasury
        • trade
          • TradeExecution
          • TradeFlag
          • TradeStatus
          • TradeType
        • trigger
          • Trigger
          • TriggerCondition
          • TriggerType
        • types
        • uptime
          • Uptime
        • validator
          • validate_nested_state_dict
          • validate_state_serialisation
          • validate_state_value
          • walk
        • valuation
          • ValuationUpdate
        • visualisation
          • Plot
          • PlotKind
          • PlotLabel
          • PlotShape
          • RecordingTime
          • Visualisation
      • strategy
        • account_correction
          • AccountingBalanceCheck
          • AccountingCorrectionCause
          • UnknownTokenPositionFix
          • apply_accounting_correction
          • calculate_account_corrections
          • calculate_total_assets
          • check_accounts
          • check_state_internal_coherence
          • correct_accounts
          • is_relative_mismatch
          • open_missing_credit_position
          • open_missing_position
          • open_missing_spot_position
          • open_missing_spot_position_direct
          • transfer_away_assets_without_position
        • alpha_model
          • AlphaModel
          • TradingPairSignal
          • TradingPairSignalFlags
          • calculate_required_new_cash
          • format_signals
        • approval
          • ApprovalModel
          • ApprovalType
          • UncheckedApprovalModel
        • asset
          • AssetToPositionsMapping
          • build_expected_asset_map
          • get_asset_amounts
          • get_onchain_assets
          • get_relevant_assets
          • map_onchain_asset_to_position
        • bootstrap
          • bootstrap_strategy
          • import_strategy_file
          • make_factory_from_strategy_mod
        • cycle
          • CycleDuration
          • round_datetime_down
          • round_datetime_up
          • snap_to_next_tick
          • snap_to_previous_tick
        • default_routing_options
          • TradeRouting
        • description
          • StrategyExecutionDescription
        • dummy
          • DummyExecutionModel
        • dust
          • get_close_epsilon_for_pair
          • get_dust_epsilon_for_asset
          • get_dust_epsilon_for_pair
          • get_relative_epsilon_for_asset
          • get_relative_epsilon_for_pair
        • engine_version
        • execution_context
          • ExecutionContext
          • ExecutionMode
        • execution_model
          • AssetManagementMode
          • ExecutionModel
          • RoutingStateDetails
        • factory
          • StrategyFactory
        • fixed_size_risk
          • FixedSizeRiskModel
        • interest
          • accrue_interest
          • distribute_interest_for_assets
          • distribute_to_entry
          • estimate_interest
          • prepare_interest_distribution
          • record_interest_rate
          • set_interest_checkpoint
          • sync_interests
          • update_interest
          • update_leveraged_position_interest
        • lending_protocol_leverage
          • create_credit_supply_loan
          • create_short_loan
          • reset_credit_supply_loan
          • update_credit_supply_loan
          • update_short_loan
        • output
          • format_position
          • format_trade
          • output_positions
          • output_trades
        • pandas_trader
          • alternative_market_data
            • get_resample_frequency
            • load_candle_universe_from_dataframe
            • load_candle_universe_from_parquet
            • load_candles_from_dataframe
            • load_candles_from_parquet
            • replace_candles
            • resample_multi_pair
            • resample_single_pair
          • decision_trigger
            • UpdatedUniverseResult
            • fetch_availability
            • fetch_lending_data
            • fetch_price_data
            • update_universe
            • validate_latest_candles
            • wait_for_universe_data_availability_jsonl
          • indicator
            • CreateIndicatorsProtocolV1
            • CreateIndicatorsProtocolV2
            • DiskIndicatorStorage
            • IndicatorDefinition
            • IndicatorDependencyResolver
            • IndicatorKey
            • IndicatorResult
            • IndicatorSet
            • IndicatorSource
            • IndicatorStorage
            • MemoryIndicatorStorage
            • calculate_and_load_indicators
            • calculate_and_load_indicators_inline
            • calculate_indicators
            • call_create_indicators
            • group_indicators
            • load_indicators
            • prepare_indicators
            • setup_indicator_multiprocessing
            • validate_function_kwargs
            • warm_up_indicator_cache
            • wrap_nones
          • indicator_decorator
            • IndicatorDecoration
            • IndicatorRegistry
            • detect_source
            • extract_args
            • flatten_dict_permutations
          • position_manager
            • PositionManager
            • explain_open_position_failure
            • explain_portfolio_contents
          • rebalance
            • get_existing_portfolio_weights
            • get_weight_diffs
            • rebalance_portfolio_old
          • runner
            • PandasTraderRunner
          • strategy_input
            • StrategyInput
            • StrategyInputIndicators
          • token_mapper
            • TokenTuple
            • create_trading_universe_for_tokens
            • find_best_pairs_for_tokens
        • parameters
          • CoreStrategyParameters
          • RollingParameter
          • StrategyParameters
          • display_parameters
          • dump_parameters
        • pricing_model
          • FixedPricing
          • PricingModel
          • PricingModelFactory
        • qstrader
          • alpha_model
            • AlphaModel
          • order_sizer
            • CashBufferedOrderSizer
          • portfolio_construction_model
            • PortfolioConstructionModel
          • runner
            • QSTraderRunner
        • reserve_currency
          • ReserveCurrency
        • reverse_universe
          • DataRangeMode
          • create_universe_from_trading_pair_identifiers
          • reverse_trading_universe_from_state
        • routing
          • RoutingModel
          • RoutingState
        • run_state
          • ExceptionData
          • LatestStateVisualisation
          • RunState
        • runner
          • StrategyRunner
          • post_process_trade_decision
          • prepare_sorted_trades
        • size_risk_model
          • SizeRiskModel
        • stop_loss
          • check_flexible_triggers
          • check_position_triggers
          • check_trigger_hit
          • expire_remaining_triggers
          • report_position_triggered
          • update_trade_triggered
          • update_trigger_expired
        • strategy_cycle_trigger
          • StrategyCycleTrigger
        • strategy_module
          • CreateTradingUniverseProtocol
          • DecideTradesProtocol
          • DecideTradesProtocol2
          • DecideTradesProtocol3
          • DecideTradesProtocol4
          • StrategyModuleInformation
          • parse_strategy_module
          • read_strategy_module
        • strategy_type
          • StrategyType
        • summary
          • KeyMetric
          • KeyMetricCalculationMethod
          • KeyMetricKind
          • KeyMetricSource
          • StrategySummary
          • StrategySummaryStatistics
        • sync_model
          • DummySyncModel
          • OnChainBalance
          • SyncModel
        • tag
          • StrategyTag
        • trade_pricing
          • TradePricing
          • format_fees_dollars
          • format_fees_percentage
        • trading_strategy_universe
          • Dataset
          • DefaultTradingStrategyUniverseModel
          • TradingStrategyUniverse
          • TradingStrategyUniverseModel
          • create_pair_universe_from_code
          • load_all_data
          • load_pair_data_for_single_exchange
          • load_partial_data
          • load_trading_and_lending_data
          • translate_credit_reserve
          • translate_token
          • translate_trading_pair
        • tvl_size_risk
          • BaseTVLSizeRiskModel
          • QuoteTokenTVLSizeRiskModel
          • TVLMethod
          • USDTVLSizeRiskModel
        • universe_model
          • StaticUniverseModel
          • StrategyExecutionUniverse
          • UniverseModel
          • UniverseOptions
        • valuation
          • ValuationModel
          • ValuationModelFactory
          • revalue_portfolio
          • revalue_state
        • valuation_update
          • update_position_valuations
        • weighting
          • check_normalised_weights
          • clip_to_normalised
          • normalise_weights
          • weight_by_1_slash_n
          • weight_by_1_slash_signal
          • weight_equal
          • weight_passthrouh
      • analysis
        • advanced_metrics
          • AdvancedMetricsMode
          • calculate_advanced_metrics
          • visualise_advanced_metrics
        • alpha_model_analyser
          • analyse_alpha_model_weights
          • construct_event_timeline
          • create_alpha_model_timeline_all_assets
          • create_pair_weight_analysis_summary_table
          • render_alpha_model_plotly_table
        • credit
          • calculate_credit_metrics
        • curve
          • CurveType
        • fee_analyser
          • analyse_trading_fees
          • create_pair_trading_fee_summary_table
        • grid_search
          • TopGridSearchResult
          • analyse_combination
          • analyse_grid_search_result
          • find_best_grid_search_results
          • order_grid_search_results_by_metric
          • render_grid_search_result_table
          • visualise_3d_scatter
          • visualise_grid_search_equity_curves
          • visualise_heatmap_2d
          • visualise_table
        • indicator
          • display_indicators
        • multi_asset_benchmark
          • compare_multiple_portfolios
          • compare_strategy_backtest_to_multiple_assets
          • get_benchmark_data
        • multipair
          • analyse_multipair
          • analyse_pair_trades
          • format_multipair_summary
        • optimiser
          • analyse_optimiser_result
          • debug_optimiser_result
          • plot_profile_duration_data
          • plot_profile_size_data
          • profile_optimiser
        • pair
          • display_strategy_universe
        • position
          • display_position_valuations
          • display_positions
          • display_reserve_position_events
          • display_transactions
        • regime
          • Regime
          • RegimeRegion
          • get_regime_signal_regions
        • returns
          • calculate_returns
          • get_default_returns_folder
          • save_daily_returns
        • single_pair
          • expand_entries_and_exits
        • slippage
          • display_slippage
        • stop_loss
          • analyse_stop_losses
          • analyse_trigger_updates
        • timemap
          • ScoringMethod
          • visualise_weekly_time_heatmap
        • trade_analyser
          • TimelineRowStylingMode
          • TimelineStyler
          • TradeAnalysis
          • TradeSummary
          • avg
          • avg_timedelta
          • build_trade_analysis
          • calculate_annualised_return
          • expand_timeline
          • expand_timeline_raw
          • func_check
          • get_avg_profit_pct_check
          • get_avg_trade_duration
        • universe
          • analyse_long_short_universe
        • weights
          • LegendMode
          • calculate_asset_weights
          • calculate_weights_statistics
          • render_weight_series_table
          • visualise_weights
      • visual
        • asset_correlation
          • calculate_correlation_matrix
          • visualise_asset_correlation
          • visualise_correlation_matrix
        • benchmark
          • create_benchmark_equity_curves
          • get_plot_from_series
          • transform_to_equity_curve
          • visualise_all_cash
          • visualise_benchmark
          • visualise_equity_curve_benchmark
          • visualise_equity_curve_comparison
          • visualise_equity_curves
          • visualise_long_short_benchmark
          • visualise_portfolio_equity_curve
          • visualise_portfolio_interest_curve
          • visualise_vs_returns
        • bullbear
          • visualise_market_regime_filter
          • visualise_raw_market_regime_indicator
        • custom_indicators
          • calculate_on_balance_volume
        • equity_curve
          • calculate_aggregate_returns
          • calculate_compounding_realised_trading_profitability
          • calculate_compounding_unrealised_trading_profitability
          • calculate_cumulative_daily_returns
          • calculate_cumulative_return
          • calculate_daily_returns
          • calculate_deposit_adjusted_returns
          • calculate_equity_curve
          • calculate_investment_flow
          • calculate_long_compounding_realised_trading_profitability
          • calculate_non_cumulative_daily_returns
          • calculate_realised_profitability
          • calculate_returns
          • calculate_rolling_sharpe
          • calculate_short_compounding_realised_trading_profitability
          • calculate_size_relative_realised_trading_returns
          • extract_compounding_unrealised_trading_profitability_portfolio_statistics
          • generate_buy_and_hold_returns
          • resample_returns
          • visualise_equity_curve
          • visualise_returns_distribution
          • visualise_returns_over_time
        • grid_search
        • grid_search_advanced
          • BenchmarkMetric
          • BenchmarkVisualisationType
          • calculate_rolling_metrics
          • calculate_sharpe_at_timestamps
          • check_inputs
          • crunch_1d
          • crunch_2d
          • prepare_comparisons
          • visualise_grid_rolling_metric_heatmap
          • visualise_grid_rolling_metric_line_chart
          • visualise_grid_single_rolling_metric
        • grid_search_basic
          • visualise_grid_search_equity_curves
          • visualise_single_grid_search_result_benchmark
        • grid_search_visualisation
          • BenchmarkMetric
          • calculate_rolling_metrics
          • calculate_sharpe_at_timestamps
          • check_inputs
          • crunch
          • prepare_comparisons
          • visualise_grid_single_rolling_metric
        • image_output
          • open_bytes_in_browser
          • open_plotly_figure_in_browser
          • render_plotly_figure_as_image_file
        • multiple_pairs
          • PairSubplotInfo
          • get_start_and_end_full
          • visualise_multiple_pairs
        • palette
          • format_blog_post_figure
          • generate_sepia_palette
          • hacker_crt_green_palette
        • qs_wrapper
          • import_quantstats_wrapped
        • single_pair
          • display_positions_table
          • get_position_hover_text
          • visualise_positions_with_duration_and_slippage
          • visualise_single_pair
          • visualise_single_pair_positions_with_duration_and_slippage
          • visualise_single_position
        • strategy_state
          • adjust_legend
          • draw_multi_pair_strategy_state
          • draw_single_pair_strategy_state
          • visualise_single_pair_strategy_state
        • technical_indicator
          • export_plot_as_dataframe
          • overlay_all_technical_indicators
          • visualise_technical_indicator
        • utils
          • export_trade_for_dataframe
          • export_trades_as_dataframe
          • get_all_positions
          • get_all_text
          • get_num_detached_and_names
          • get_pair_base_quote_names
          • get_pair_name_from_first_trade
          • get_start_and_end
          • get_subplot_names
          • visualise_trades
        • web_chart
          • TimeWindow
          • WebChart
          • WebChartSource
          • WebChartType
          • export_time_series
          • render_web_chart
      • backtest
        • backtest_execution
          • BacktestExecution
          • fix_sell_token_amount
        • backtest_generic_router
          • EthereumBacktestPairConfigurator
        • backtest_module
          • run_backtest_for_module
        • backtest_pricing
          • BacktestPricing
          • backtest_pricing_factory
        • backtest_routing
          • BacktestRoutingIgnoredModel
          • BacktestRoutingModel
          • BacktestRoutingState
        • backtest_runner
          • BacktestResult
          • BacktestSetup
          • guess_data_delay_tolerance
          • run_backtest
          • run_backtest_inline
          • setup_backtest
          • setup_backtest_for_universe
        • backtest_sync
          • BacktestSyncModel
          • FundFlowEvent
        • backtest_valuation
          • BacktestValuationModel
          • backtest_valuation_factory
        • data_preload
          • preload_data
        • grid_search
          • GridCombination
          • GridParameter
          • GridSearchDataRetention
          • GridSearchResult
          • GridSearchWorker
          • create_grid_search_failed_result
          • get_grid_search_result_path
          • initialise_multiprocess_strategy_universe_from_disk
          • load_multiprocess_strategy_universe
          • perform_grid_search
          • pick_best_grid_search_result
          • pick_grid_search_result
          • prepare_grid_combinations
          • run_grid_combination_multiprocess
          • run_grid_combination_threaded
          • run_grid_search_backtest
          • save_disk_multiprocess_strategy_universe
          • save_forked_multiprocess_strategy_universe
          • warm_up_grid_search_indicator_cache
        • legacy_backtest_sync
          • BacktestSyncer
        • notebook
        • optimiser
          • MinTradeCountFilter
          • ObjectiveWrapper
          • OptimiserResult
          • OptimiserSearchResult
          • ResultFilter
          • SearchFunction
          • create_grid_combination
          • get_optimised_dimensions
          • perform_optimisation
          • prepare_optimiser_parameters
        • optimiser_functions
          • BalancedSharpeAndMaxDrawdownOptimisationFunction
          • RollingSharpeOptimisationFunction
          • optimise_max_drawdown
          • optimise_profit
          • optimise_sharpe
          • optimise_sharpe_and_max_drawdown_ratio
          • optimise_sortino
          • optimise_win_rate
        • preprocessed_backtest
          • BacktestDatasetDefinion
          • ExportFormat
          • SavedDataset
          • make_base_symbol
          • make_full_ticker
          • make_link
          • make_simple_ticker
          • prepare_dataset
          • run_and_write_report
        • preprocessed_backtest_exporter
          • export_all_main
        • simulated_wallet
          • SimulatedWallet
        • tearsheet
          • BacktestReporter
          • export_backtest_report
      • ethereum
        • aave_v3
          • aave_v3_routing
            • AaveV3Routing
            • AaveV3RoutingState
          • analysis
            • analyse_credit_trade_by_receipt
        • address_sync_model
          • AddressSyncModel
        • balance_update
          • apply_balance_update_events
          • apply_reserve_update_events
          • perform_balance_update
        • enzyme
          • asset
            • EnzymeAsset
            • EnzymeAssetType
            • load_enzyme_asset_list
          • tx
            • EnzymeTransactionBuilder
          • vault
            • EnzymeVaultSyncModel
        • eth_pricing_model
          • EthereumPricingModel
        • eth_valuation
          • EthereumPoolRevaluator
        • ethereum_protocol_adapters
          • EthereumPairConfigurator
          • create_1delta_adapter
          • create_aave_v3_adapter
          • create_uniswap_v2_adapter
          • create_uniswap_v3_adapter
          • get_exchange_type
        • ethereumtrader
          • EthereumTrader
          • get_base_quote_contracts
          • get_mock_erc20_contract
        • execution
          • EthereumExecution
          • approve_infinity
          • approve_tokens
          • broadcast
          • confirm_approvals
          • get_held_assets
          • prepare_swaps
          • translate_to_naive_swap
          • update_confirmation_status
          • wait_trades_to_complete
        • hot_wallet_sync_model
          • HotWalletSyncModel
          • EthereumHotWalletReserveSyncer
        • onchain_balance
          • fetch_address_balances
        • one_delta
          • analysis
            • analyse_credit_trade_by_receipt
            • analyse_leverage_trade_by_receipt
            • analyse_one_delta_trade
            • decode_path
          • one_delta_execution
            • OneDeltaExecution
          • one_delta_live_pricing
            • OneDeltaLivePricing
            • one_delta_live_pricing_factory
          • one_delta_routing
            • OneDeltaRouting
            • OneDeltaRoutingState
            • get_one_delta
          • one_delta_valuation
            • OneDeltaPoolRevaluator
            • one_delta_valuation_factory
        • rebroadcast
          • rebroadcast_all
        • revert
          • clean_revert_reason_message
        • routing_data
          • RoutingData
          • create_compatible_routing
          • create_uniswap_v2_compatible_routing
          • create_uniswap_v3_compatible_routing
          • get_all_uniswap_v3_compatible_routing_types
          • get_backtest_routing_model
          • get_pancake_default_routing_parameters
          • get_quickswap_default_routing_parameters
          • get_routing_model
          • get_sushi_default_routing_parameters
          • get_trader_joe_default_routing_parameters
          • get_uniswap_v2_compatible_routing_types
          • get_uniswap_v2_default_routing_parameters
          • get_uniswap_v3_arbitrum_default_routing_parameters
          • get_uniswap_v3_compatible_routing_types_arbitrum
          • get_uniswap_v3_compatible_routing_types_eth
          • get_uniswap_v3_compatible_routing_types_poly
          • get_uniswap_v3_ethereum_default_routing_parameters
          • get_uniswap_v3_polygon_default_routing_parameters
          • validate_reserve_currency
        • routing_model
          • EthereumRoutingModel
        • routing_state
          • EthereumRoutingState
          • get_base_quote
          • get_base_quote_intermediary
          • get_token_for_asset
          • route_tokens
        • swap
          • get_swap_transactions
          • is_swap_function
          • report_failure
        • token
          • create_spot_token_map_existing_positions
          • create_spot_token_map_potential_positions
          • fetch_token_as_asset
          • translate_token_details
        • tvl
          • fetch_quote_token_tvl_with_exchange_rate
          • fetch_quote_token_tvls
          • fetch_uni_v2_v3_quote_token_tvl
          • find_usd_rate
        • tx
          • HotWalletTransactionBuilder
          • TransactionBuilder
        • uniswap_v2
          • uniswap_v2_execution
            • UniswapV2Execution
            • get_current_price
          • uniswap_v2_execution_v0
            • UniswapV2ExecutionModelVersion0
            • UniswapV2RoutingInstructions
            • broadcast_and_resolve
            • resolve_trades
          • uniswap_v2_live_pricing
            • UniswapV2LivePricing
            • uniswap_v2_live_pricing_factory
          • uniswap_v2_routing
            • UniswapV2Routing
            • UniswapV2RoutingState
            • get_uniswap_for_pair
          • uniswap_v2_valuation
            • UniswapV2PoolRevaluator
            • uniswap_v2_sell_valuation_factory
          • uniswap_v2_valuation_v0
            • UniswapV2PoolValuationMethodV0
            • uniswap_v2_sell_valuation_factory
        • uniswap_v3
          • uniswap_v3_execution
            • UniswapV3Execution
            • get_current_price
          • uniswap_v3_live_pricing
            • UniswapV3LivePricing
            • uniswap_v3_live_pricing_factory
          • uniswap_v3_routing
            • UniswapV3Routing
            • UniswapV3RoutingState
            • get_uniswap_for_pair
          • uniswap_v3_valuation
            • UniswapV3PoolRevaluator
            • uniswap_v3_sell_valuation_factory
        • universe
          • create_exchange_universe
          • create_pair_universe
        • wallet
          • ReserveUpdateEvent
          • perform_gas_level_checks
          • sync_reserves
          • update_wallet_balances
        • web3config
          • Web3Config
      • cli
        • approval
          • CLIApprovalModel
        • backup
          • backup_state
        • bootstrap
          • backup_state
          • create_approval_model
          • create_client
          • create_execution_and_sync_model
          • create_execution_model
          • create_metadata
          • create_state_store
          • create_sync_model
          • create_web3_config
          • monkey_patch
          • prepare_cache
          • prepare_executor_id
          • validate_executor_id
        • close_position
          • close_single_or_all_positions
        • commands
          • app
          • backtest
            • backtest
          • check_accounts
            • check_accounts
          • check_position_triggers
            • check_position_triggers
          • check_universe
            • check_universe
          • check_wallet
            • check_wallet
          • close_all
            • close_all
          • close_position
            • close_position
          • console
            • console
            • launch_console
          • correct_accounts
            • correct_accounts
          • deploy_guard
            • deploy_guard
          • enzyme_asset_list
            • enzyme_asset_list
          • enzyme_deploy_vault
            • enzyme_deploy_vault
          • export
            • export
            • walk_all_typer_options
          • hello
            • hello
          • init
            • init
          • lagoon_deploy_vault
            • lagoon_deploy_vault
          • pair_mapping
            • construct_identifier_from_pair
            • parse_pair_data
          • perform_test_trade
            • perform_test_trade
          • repair
            • repair
          • reset
            • reset
          • reset_deposits
            • reset_deposits
          • retry
            • retry
          • send_log_message
            • send_log_message
          • shared_options
            • PositionType
            • parse_comma_separated_list
            • required_option
          • show_positions
            • TransactionType
            • show_positions
          • show_valuation
            • show_valuation
          • start
            • start
          • token_cache
            • PrintTokenOption
            • PurgeType
            • token_cache
          • trading_pair
            • PrintTokenOption
            • PurgeType
            • trading_pair
          • version
            • version
          • visualise
            • visualise
          • webapi
            • webapi
        • discord
          • get_discord_logging_handler
          • post_logging_discord_image
        • double_position
          • check_double_position
        • env
          • EnvVarDescription
          • get_available_env_vars
        • guard
          • generate_whitelist
          • get_enzyme_deployment
        • latest_release
          • main
        • log
          • get_ring_buffer_handler
          • setup_custom_log_levels
          • setup_discord_logging
          • setup_file_logging
          • setup_in_memory_logging
          • setup_logging
          • setup_logstash_logging
          • setup_notebook_logging
          • setup_pytest_logging
          • setup_strategy_logging
          • setup_telegram_logging
        • loop
          • ExecutionLoop
          • ExecutionTestHook
        • main
        • result
          • display_backtesting_results
        • slippage
          • configure_max_slippage_tolerance
        • testtrade
          • make_test_trade
        • universe
          • UniverseInitData
          • setup_universe
        • version_info
          • VersionInfo
        • watchdog
          • WatchdogMode
          • check_hung_workers
          • create_watchdog_registry
          • get_last_ping
          • get_timeout
          • get_watched_workers
          • mark_alive
          • register_worker
          • start_background_watchdog
          • stop_watchdog
          • suicide
      • utils
        • accuracy
          • ensure_exact_zero
          • setup_decimal_accuracy
          • snap_to_epsilon
          • sum_decimal
        • binance
          • create_binance_universe
          • fetch_binance_dataset
        • blockchain
          • get_block_timestamp
          • get_latest_block_timestamp
        • cpu
          • get_safe_max_workers_count
        • crossover
          • contains_cross_over
          • contains_cross_under
        • dataclass
          • EthereumAddress
          • UTCFriendlyDataClassJsonMixin
        • dedent
          • dedent_any
          • strip_except_newlines
        • default_strategies
          • get_default_strategies_path
        • format
          • calculate_percentage
        • fullname
          • get_object_full_name
        • increasing
          • is_monotonically_decreasing
          • is_monotonically_increasing
        • jupyter_notebook_folder
          • get_strategies_folder
        • jupyter_notebook_name
          • get_notebook_name
          • path
        • leverage_calculations
          • LeverageEstimate
          • calculate_liquidation_price
          • calculate_sizes_for_leverage
        • list
          • get_linearly_sampled_items
        • notebook
          • OutputMode
          • set_large_plotly_chart_font
          • set_notebook_logging
          • setup_charting_and_output
        • price
          • is_legit_price_value
        • profile
          • profiled
        • python_function
          • hash_function
        • python_module_loader
          • extract_module_members
          • import_python_source_file
        • ring_buffer_logging_handler
          • ExportedRecord
          • RingBufferHandler
        • slippage
          • get_slippage_in_bps
        • sort
          • unique_sort
        • state_downloader
          • download_state
        • summarydataframe
          • Format
          • Value
          • as_bars
          • as_decimal
          • as_dollar
          • as_duration
          • as_integer
          • as_missing
          • as_percent
          • create_summary_table
          • format_value
          • format_values
        • timer
          • timed_task
        • timestamp
          • convert_and_validate_timestamp
          • convert_and_validate_timestamp_as_float
          • convert_and_validate_timestamp_as_int
          • json_decode_timedelta
          • json_encode_timedelta
        • token
        • typing
        • url
          • get_url_domain
          • redact_url_password
      • webhook
        • api
          • web_chart
          • web_file
          • web_home
          • web_icon
          • web_logs
          • web_metadata
          • web_notify
          • web_ping
          • web_source
          • web_state
          • web_status
          • web_visulisation
        • app
          • Root
          • create_pyramid_app
          • forbidden_view
          • init_web_api
        • error
          • convert_to_api_error_response
          • error_tween_factory
          • exception_response
          • exception_view
        • events
          • add_cors_headers
        • http_log
          • configure_http_request_logging
          • log_tween_factory
        • server
          • WebhookServer
          • create_webhook_server
      • testing
        • backtest_trader
          • BacktestTrader
        • dummy_wallet
          • DummyWalletSyncer
        • ethereumtrader_one_delta
          • OneDeltaTestTrader
        • ethereumtrader_uniswap_v2
          • UniswapV2TestTrader
        • ethereumtrader_uniswap_v3
          • UniswapV3TestTrader
        • pairuniversetrader
          • PairUniverseTestTrader
        • pytest_helpers
          • is_failed_test
        • simulated_execution_loop
          • set_up_simulated_ethereum_generic_execution
          • set_up_simulated_execution_loop_one_delta
          • set_up_simulated_execution_loop_uniswap_v2
          • set_up_simulated_execution_loop_uniswap_v3
        • simulated_trader
          • SimulatedTestTrader
        • synthetic_ethereum_data
          • generate_random_ethereum_address
        • synthetic_exchange_data
          • generate_exchange
          • generate_simple_routing_model
        • synthetic_lending_data
          • generate_lending_reserve
          • generate_lending_universe
        • synthetic_pair_data
          • generate_pair
        • synthetic_price_data
          • generate_fixed_price_candles
          • generate_multi_pair_candles
          • generate_ohlcv_candles
          • generate_tvl_candles
          • load_ohlcv_parquet_file
        • synthetic_universe_data
          • create_synthetic_single_pair_universe
        • unit_test_trader
          • UnitTestTrader
      • monkeypatch
        • cloudpickle_patch
          • reducer_override
        • dataclasses_json
          • patch_dataclasses_json
        • web3
          • construct_sign_and_send_raw_middleware
    • Technical analysis
      • Statistics
        • entropy
        • kurtosis
        • mad
        • median
        • skew
        • stdev
        • tos_stdevall
        • variance
        • zscore
      • Overlap and moving averages
        • alma
        • dema
        • ema
        • fwma
        • hilo
        • hl2
        • hlc3
        • hma
        • hwma
        • ichimoku
        • jma
        • kama
        • linreg
        • ma
        • mcgd
        • midpoint
        • midprice
        • ohlc4
        • pwma
        • rma
        • sinwma
        • sma
        • ssf
        • supertrend
        • swma
        • t3
        • tema
        • trima
        • vidya
        • vwap
        • vwma
        • wcp
        • wma
        • zlma
      • Trend indicators
        • adx
        • amat
        • aroon
        • chop
        • cksp
        • decay
        • decreasing
        • dpo
        • increasing
        • long_run
        • psar
        • qstick
        • short_run
        • tsignals
        • ttm_trend
        • vhf
        • vortex
        • xsignals
      • Momentum indicators
        • ao
        • apo
        • bias
        • bop
        • brar
        • cci
        • cfo
        • cg
        • cmo
        • coppock
        • cti
        • dm
        • er
        • eri
        • fisher
        • inertia
        • kdj
        • kst
        • macd
        • mom
        • pgo
        • ppo
        • psl
        • pvo
        • qqe
        • roc
        • rsi
        • rsx
        • rvgi
        • slope
        • smi
        • squeeze
        • squeeze_pro
        • stc
        • stoch
        • stochrsi
        • td_seq
        • trix
        • tsi
        • uo
        • willr
      • Volatility indicators
        • aberration
        • accbands
        • atr
        • bbands
        • donchian
        • hwc
        • kc
        • massi
        • natr
        • pdist
        • rvi
        • thermo
        • true_range
        • ui
      • Volume based indicators
        • ad
        • adosc
        • aobv
        • cmf
        • efi
        • eom
        • kvo
        • mfi
        • nvi
        • obv
        • pvi
        • pvol
        • pvr
        • pvt
        • vp
      • Candle pattern indicators
        • cdl_doji
        • cdl_inside
        • cdl_pattern
        • cdl_z
        • ha
      • Market cycles
        • ebsw
      • Portfolio performance
        • drawdown
        • log_return
        • percent_return
    • Web3 Ethereum DeFi
Back to top
Edit this page

Web3 Ethereum DeFi#

Web3-Ethereum-DeFi is a low-level library for smart contracts, DeFi trading (Uniswap, PancakeSwap), Ethereum JSON-RPC, EVM transactions and automated test suites using Python.

See the separate web3-ethereum-defi documentation for low level Ethereum interactions.

More information#

  • Github

  • README

  • Documentation

Previous
percent_return

Trading Strategy is in beta and still under development. Any documentation is preliminary and not final.

Contents
  • Web3 Ethereum DeFi
    • More information