Skip to content

FinceptTerminal is a modern finance application offering advanced market analytics, investment research, and economic data tools, designed for interactive exploration and data-driven decision-making in a user-friendly environment.

Broker Update

tilakpatel223d0a581993c4
diff --git a/fincept-qt/CMakeLists.txt b/fincept-qt/CMakeLists.txt
index 5d8d8058b..d4d6c9bc7 100644
--- a/fincept-qt/CMakeLists.txt
+++ b/fincept-qt/CMakeLists.txt
@@ -701,6 +701,7 @@ set(CORE_SOURCES
src/core/session/SessionManager.cpp
src/core/session/ScreenStateManager.cpp
src/core/i18n/LanguageManager.cpp
+ src/core/currency/CurrencyManager.cpp
src/core/keys/KeyConfigManager.cpp
src/core/keys/WindowCycler.cpp
src/core/net/NetSpeedMeter.cpp
@@ -845,6 +846,7 @@ set(STORAGE_SOURCES
src/storage/sqlite/migrations/v033_historify.cpp
src/storage/sqlite/migrations/v034_strategy_portfolio.cpp
src/storage/sqlite/migrations/v035_news_analysis.cpp
+ src/storage/sqlite/migrations/v036_instrument_broker_token.cpp
# Historical OHLCV data store (Historify, Phase 3 §13)
src/storage/HistoricalDataStore.cpp
@@ -988,6 +990,7 @@ set(TRADING_SOURCES
src/trading/websocket/UpstoxWebSocket.cpp
src/trading/websocket/KotakWebSocket.cpp
src/trading/websocket/IIFLWebSocket.cpp
+ src/trading/websocket/IciciDirectWebSocket.cpp
# Indian brokers
src/trading/brokers/zerodha/ZerodhaBroker.cpp
src/trading/brokers/zerodha/Totp.cpp
@@ -1008,6 +1011,7 @@ set(TRADING_SOURCES
src/trading/brokers/flattrade/FlattradeBroker.cpp
src/trading/brokers/paytm/PaytmBroker.cpp
src/trading/brokers/tradejini/TradejiniBroker.cpp
+ src/trading/brokers/icicidirect/IciciDirectBroker.cpp
# Global brokers
src/trading/brokers/alpaca/AlpacaBroker.cpp
src/trading/brokers/alpaca/AlpacaWebSocket.cpp
@@ -1017,13 +1021,31 @@ set(TRADING_SOURCES
src/trading/brokers/metaapi/MetaApiBroker.cpp
# Instrument system (Phase 1)
+ src/trading/instruments/InstrumentNormalize.cpp
+ src/trading/instruments/InstrumentDecompress.cpp
+ src/trading/instruments/InstrumentDownload.cpp
src/trading/instruments/InstrumentRepository.cpp
src/trading/instruments/ZerodhaInstrumentParser.cpp
src/trading/instruments/FyersInstrumentParser.cpp
src/trading/instruments/GrowwInstrumentParser.cpp
src/trading/instruments/DhanInstrumentParser.cpp
+ src/trading/instruments/IciciInstrumentParser.cpp
src/trading/instruments/InstrumentService.cpp
src/trading/instruments/SymbolResolver.cpp
+ # Unified cross-broker search — additional broker instrument sources
+ src/trading/instruments/InstrumentSources.cpp
+ src/trading/instruments/parsers/NorenSymbolParser.cpp
+ src/trading/instruments/parsers/ShoonyaInstrumentSource.cpp
+ src/trading/instruments/parsers/FlattradeInstrumentSource.cpp
+ src/trading/instruments/parsers/SamcoInstrumentParser.cpp
+ src/trading/instruments/parsers/UpstoxInstrumentParser.cpp
+ src/trading/instruments/parsers/FivePaisaInstrumentParser.cpp
+ src/trading/instruments/parsers/PaytmInstrumentParser.cpp
+ src/trading/instruments/parsers/MotilalInstrumentParser.cpp
+ src/trading/instruments/parsers/AliceBlueInstrumentParser.cpp
+ src/trading/instruments/parsers/TradejiniInstrumentParser.cpp
+ src/trading/instruments/parsers/KotakInstrumentParser.cpp
+ src/trading/instruments/parsers/XtsInstrumentParser.cpp
)
# Algo Engine (native C++ trading engine — replaces Python algo runner)
@@ -1284,7 +1306,9 @@ set(UI_SOURCES
# Algo Trading visual strategy builder widgets
src/ui/widgets/algo/ConditionBlock.cpp
- src/ui/widgets/algo/LogicConnectorWidget.cpp
+ src/ui/widgets/algo/OperandEditor.cpp
+ src/ui/widgets/algo/GroupBlock.cpp
+ src/ui/widgets/algo/BacktestReportPanel.cpp
src/ui/widgets/algo/ConditionSection.cpp
src/ui/widgets/algo/RiskManagementPanel.cpp
src/ui/widgets/algo/SymbolSearchCombo.cpp
@@ -2239,6 +2263,7 @@ set_source_files_properties(
src/storage/sqlite/migrations/v033_historify.cpp
src/storage/sqlite/migrations/v034_strategy_portfolio.cpp
src/storage/sqlite/migrations/v035_news_analysis.cpp
+ src/storage/sqlite/migrations/v036_instrument_broker_token.cpp
# Polymarket screen files — each defines static fmt_* helpers in same namespace
src/screens/polymarket/PolymarketScreen.cpp
src/screens/polymarket/PolymarketCommandBar.cpp
@@ -2281,6 +2306,7 @@ set_source_files_properties(
src/trading/brokers/flattrade/FlattradeBroker.cpp
src/trading/brokers/paytm/PaytmBroker.cpp
src/trading/brokers/tradejini/TradejiniBroker.cpp
+ src/trading/brokers/icicidirect/IciciDirectBroker.cpp
src/trading/brokers/alpaca/AlpacaBroker.cpp
src/trading/brokers/alpaca/AlpacaWebSocket.cpp
src/trading/brokers/ibkr/IBKRBroker.cpp
@@ -2407,6 +2433,7 @@ set_source_files_properties(
src/trading/brokers/flattrade/FlattradeBroker.cpp
src/trading/brokers/paytm/PaytmBroker.cpp
src/trading/brokers/tradejini/TradejiniBroker.cpp
+ src/trading/brokers/icicidirect/IciciDirectBroker.cpp
src/trading/brokers/alpaca/AlpacaBroker.cpp
src/trading/brokers/alpaca/AlpacaWebSocket.cpp
src/trading/brokers/ibkr/IBKRBroker.cpp
@@ -2427,6 +2454,7 @@ set_source_files_properties(
src/trading/websocket/UpstoxWebSocket.cpp
src/trading/websocket/KotakWebSocket.cpp
src/trading/websocket/IIFLWebSocket.cpp
+ src/trading/websocket/IciciDirectWebSocket.cpp
# Phase 3 trading services — file-scope kLog / anonymous-namespace helpers
src/trading/ActionCenter.cpp
src/trading/StrategyPortfolio.cpp
@@ -2438,6 +2466,29 @@ set_source_files_properties(
PROPERTIES SKIP_UNITY_BUILD_INCLUSION TRUE
)
+# Instrument subsystem — shared normalizer + per-broker parsers each carry
+# file-scope anonymous-namespace helpers/maps (map_exchange, *_index_map, …);
+# keep out of unity to avoid ODR/redefinition clashes when batched together.
+set_source_files_properties(
+ src/trading/instruments/InstrumentNormalize.cpp
+ src/trading/instruments/InstrumentDecompress.cpp
+ src/trading/instruments/InstrumentDownload.cpp
+ src/trading/instruments/InstrumentSources.cpp
+ src/trading/instruments/parsers/NorenSymbolParser.cpp
+ src/trading/instruments/parsers/ShoonyaInstrumentSource.cpp
+ src/trading/instruments/parsers/FlattradeInstrumentSource.cpp
+ src/trading/instruments/parsers/XtsInstrumentParser.cpp
+ src/trading/instruments/parsers/UpstoxInstrumentParser.cpp
+ src/trading/instruments/parsers/FivePaisaInstrumentParser.cpp
+ src/trading/instruments/parsers/KotakInstrumentParser.cpp
+ src/trading/instruments/parsers/MotilalInstrumentParser.cpp
+ src/trading/instruments/parsers/PaytmInstrumentParser.cpp
+ src/trading/instruments/parsers/AliceBlueInstrumentParser.cpp
+ src/trading/instruments/parsers/SamcoInstrumentParser.cpp
+ src/trading/instruments/parsers/TradejiniInstrumentParser.cpp
+ PROPERTIES SKIP_UNITY_BUILD_INCLUSION TRUE
+)
+
# Storage repositories: each defines kCols — safe to batch in groups of 3
set_source_files_properties(
src/storage/repositories/AgentConfigRepository.cpp
@@ -2787,6 +2838,12 @@ endif()
find_package(OpenSSL REQUIRED)
message(STATUS "OpenSSL found: ${OPENSSL_VERSION} — include: ${OPENSSL_INCLUDE_DIR}")
+# zlib: gzip (Upstox master) + zip (Shoonya symbol masters) decompression.
+# See trading/instruments/InstrumentDecompress.cpp. System zlib on macOS/Linux,
+# Qt-bundled on Windows.
+find_package(ZLIB REQUIRED)
+message(STATUS "ZLIB found: ${ZLIB_VERSION_STRING}")
+
# ── macOS: make Qt's openssl TLS plugin discoverable ─────────────────────────
# Qt's libqopensslbackend.dylib only searches /usr/local/lib, /opt/local/lib,
# /sw/lib, /usr/lib and Qt's own lib dir for libssl/libcrypto. Homebrew on
@@ -2840,6 +2897,7 @@ target_link_libraries(FinceptTerminal PRIVATE
qtadvanceddocking-qt6
OpenSSL::SSL
OpenSSL::Crypto
+ ZLIB::ZLIB
fincept_ed25519
)
diff --git a/fincept-qt/agg.txt b/fincept-qt/agg.txt
new file mode 100644
index 000000000..e11b5666c
--- /dev/null
+++ b/fincept-qt/agg.txt
@@ -0,0 +1,456 @@
+========== Handlers includes (top 40) ==========
+1: // src/screens/equity_trading/EquityTradingScreen_Handlers.cpp
+2: //
+3: // User-action handlers: account switch / symbol selection / mode toggle,
+4: // token-expiry recovery, accounts dialog, order submit / cancel / modify,
+5: // order-book click, refresh_candles.
+6: //
+7: // Part of the partial-class split of EquityTradingScreen.cpp.
+8:
+9: #include "screens/equity_trading/EquityTradingScreen.h"
+10:
+11: #include "core/logging/Logger.h"
+12: #include "core/session/ScreenStateManager.h"
+13: #include "core/symbol/SymbolContext.h"
+14: #include "core/symbol/SymbolDragSource.h"
+15: #include "screens/equity_trading/AccountManagementDialog.h"
+16: #include "screens/equity_trading/BroadcastOrderDialog.h"
+17: #include "screens/equity_trading/EquityBottomPanel.h"
+18: #include "screens/equity_trading/EquityChart.h"
+19: #include "screens/equity_trading/EquityOrderBook.h"
+20: #include "screens/equity_trading/EquityOrderEntry.h"
+21: #include "screens/equity_trading/EquityTickerBar.h"
+22: #include "screens/equity_trading/EquityWatchlist.h"
+23: #include "services/portfolio/PortfolioService.h"
+24: #include "storage/repositories/SettingsRepository.h"
+25: #include "trading/AccountManager.h"
+26: #include "trading/ActionCenter.h"
+27: #include "trading/BrokerRegistry.h"
+28: #include "trading/DataStreamManager.h"
+29: #include "trading/OrderMatcher.h"
+30: #include "trading/PaperTrading.h"
+31: #include "ui/theme/StyleSheets.h"
+32: #include "ui/theme/Theme.h"
+33:
+34: #include <QApplication>
+35: #include <QCheckBox>
+36: #include <QComboBox>
+37: #include <QCompleter>
+38: #include <QDate>
+39: #include <QDateTime>
+40: #include <QDialog>
+
+========== Handlers: on_account_changed + credentials_saved (260-360) ==========
+260: auto* dlg = new AccountManagementDialog(this);
+261:
+262: connect(dlg, &AccountManagementDialog::account_added, this, [this](const QString& account_id) {
+263: Q_UNUSED(account_id);
+264: update_account_menu();
+265: // Don't auto-focus a freshly-added account: it has no credentials yet,
+266: // so on_account_changed() would spawn ~11 QtConcurrent::run fetches that
+267: // all bail at the empty-api_key check. On macOS that thread-storm trips
+268: // pthread_create inside QThreadPool and crashes the main thread (see
+269: // crash report 2026-05-08-123609.ips). Defer focus to credentials_saved.
+270: });
+271:
+272: connect(dlg, &AccountManagementDialog::account_removed, this, [this](const QString& account_id) {
+273: DataStreamManager::instance().stop_stream(account_id);
+274: update_account_menu();
+275: // If removed the focused account, switch to next available
+276: if (account_id == focused_account_id_) {
+277: auto accounts = AccountManager::instance().active_accounts();
+278: if (!accounts.isEmpty())
+279: on_account_changed(accounts.first().account_id);
+280: else
+281: focused_account_id_.clear();
+282: }
+283: update_connection_status();
+284: });
+285:
+286: connect(dlg, &AccountManagementDialog::credentials_saved, this, [this](const QString& account_id) {
+287: token_expired_shown_.store(false);
+288: // First account ever connected: focus it now (account_added intentionally
+289: // does not auto-focus — see comment there). on_account_changed() does its
+290: // own start_stream() + symbol/watchlist setup, so we're done after that.
+291: if (focused_account_id_.isEmpty()) {
+292: on_account_changed(account_id);
+293: AccountManager::instance().set_connection_state(account_id, ConnectionState::Connected);
+294: update_connection_status();
+295: return;
+296: }
+297: // Start/restart the stream with new credentials
+298: DataStreamManager::instance().start_stream(account_id);
+299: auto* stream = DataStreamManager::instance().stream_for(account_id);
+300: if (stream && account_id == focused_account_id_) {
+301: stream->set_selected_symbol(selected_symbol_, selected_exchange_);
+302: stream->subscribe_symbols(watchlist_symbols_);
+303: }
+304: AccountManager::instance().set_connection_state(account_id, ConnectionState::Connected);
+305: update_connection_status();
+306: });
+307:
+308: dlg->exec();
+309: dlg->deleteLater();
+310: }
+311:
+312: // ============================================================================
+313: // Order Handling
+314: // ============================================================================
+315:
+316: void EquityTradingScreen::on_order_submitted(const UnifiedOrder& order) {
+317: if (focused_account_id_.isEmpty()) {
+318: order_entry_->show_order_status("No account selected — add one via ACCOUNTS", false);
+319: return;
+320: }
+321:
+322: auto account = AccountManager::instance().get_account(focused_account_id_);
+323:
+324: if (account.trading_mode == "paper") {
+325: const QString portfolio_id = account.paper_portfolio_id;
+326: if (portfolio_id.isEmpty()) {
+327: order_entry_->show_order_status("No paper portfolio for this account", false);
+328: return;
+329: }
+330:
+331: LOG_INFO(TAG, QString("Paper order: %1 %2 x%3 account=%4")
+332: .arg(order.side == OrderSide::Buy ? "BUY" : "SELL")
+333: .arg(order.symbol)
+334: .arg(order.quantity)
+335: .arg(account.display_name));
+336:
+337: const QString side = order.side == OrderSide::Buy ? "buy" : "sell";
+338: const QString type = order_type_str(order.order_type);
+339: std::optional<double> price_opt;
+340: if (order.order_type == OrderType::Limit || order.order_type == OrderType::StopLossLimit) {
+341: price_opt = order.price;
+342: } else if (order.order_type == OrderType::Market) {
+343: const double ref = current_price_ > 0 ? current_price_ : (order.price > 0 ? order.price : 0.0);
+344: if (ref > 0)
+345: price_opt = ref;
+346: }
+347: std::optional<double> stop_opt;
+348: if (order.stop_price > 0)
+349: stop_opt = order.stop_price;
+350:
+351: if (order.order_type == OrderType::Market && !price_opt) {
+352: order_entry_->show_order_status("Price not available yet — wait for quotes to load", false);
+353: return;
+354: }
+355:
+356: try {
+357: auto pt_order = pt_place_order(portfolio_id, order.symbol, side, type, order.quantity, price_opt, stop_opt);
+358:
+359: if (order.order_type == OrderType::Market) {
+360: double fill_price = current_price_ > 0 ? current_price_ : (order.price > 0 ? order.price : 0.0);
+
+========== on_account_changed definition location ==========
+src/screens/equity_trading/EquityTradingScreen_Handlers.cpp:73:void EquityTradingScreen::on_account_changed(const QString& account_id) {
+src/screens/equity_trading/EquityTradingScreen_Handlers.cpp:266: // so on_account_changed() would spawn ~11 QtConcurrent::run fetches that
+src/screens/equity_trading/EquityTradingScreen_Handlers.cpp:279: on_account_changed(accounts.first().account_id);
+src/screens/equity_trading/EquityTradingScreen_Handlers.cpp:289: // does not auto-focus — see comment there). on_account_changed() does its
+src/screens/equity_trading/EquityTradingScreen_Handlers.cpp:292: on_account_changed(account_id);
+src/screens/equity_trading/EquityTradingScreen.cpp:109: on_account_changed(acct);
+src/screens/equity_trading/EquityTradingScreen.cpp:350: on_account_changed(accounts.first().account_id);
+src/screens/equity_trading/EquityTradingScreen.cpp:494: on_account_changed(id);
+src/screens/equity_trading/EquityTradingScreen.cpp:568: on_account_changed(acct);
+src/screens/equity_trading/EquityTradingScreen.h:59: void on_account_changed(const QString& account_id);
+
+========== EquityTradingScreen.h (FULL) ==========
+1: #pragma once
+2: // Equity Trading Screen — multi-account coordinator.
+3: // Supports multiple broker accounts simultaneously via DataStreamManager.
+4: // Each account has its own data stream (WS/polling), portfolio, and credentials.
+5:
+6: #include "core/symbol/IGroupLinked.h"
+7: #include "screens/common/IStatefulScreen.h"
+8: #include "screens/equity_trading/EquityTypes.h"
+9: #include "trading/BrokerAccount.h"
+10: #include "trading/TradingTypes.h"
+11:
+12: #include <QHash>
+13: #include <QHideEvent>
+14: #include <QLabel>
+15: #include <QLineEdit>
+16: #include <QMenu>
+17: #include <QPushButton>
+18: #include <QShowEvent>
+19: #include <QTimer>
+20: #include <QWidget>
+21:
+22: #include <atomic>
+23:
+24: namespace fincept::screens::equity {
+25: class EquityTickerBar;
+26: class EquityWatchlist;
+27: class EquityChart;
+28: class EquityOrderEntry;
+29: class EquityOrderBook;
+30: class EquityBottomPanel;
+31: } // namespace fincept::screens::equity
+32:
+33: namespace fincept::screens {
+34:
+35: class EquityTradingScreen : public QWidget, public IGroupLinked, public IStatefulScreen {
+36: Q_OBJECT
+37: Q_INTERFACES(fincept::IGroupLinked)
+38: public:
+39: explicit EquityTradingScreen(QWidget* parent = nullptr);
+40: ~EquityTradingScreen();
+41:
+42: // IGroupLinked — see WatchlistScreen for the propagation contract.
+43: void set_group(SymbolGroup g) override { link_group_ = g; }
+44: SymbolGroup group() const override { return link_group_; }
+45: void on_group_symbol_changed(const SymbolRef& ref) override;
+46: SymbolRef current_symbol() const override;
+47:
+48: // IStatefulScreen
+49: QVariantMap save_state() const override;
+50: void restore_state(const QVariantMap& state) override;
+51: QString state_key() const override { return QStringLiteral("equity_trading"); }
+52:
+53: protected:
+54: void showEvent(QShowEvent* event) override;
+55: void hideEvent(QHideEvent* event) override;
+56:
+57: private slots:
+58: // Multi-account slots
+59: void on_account_changed(const QString& account_id);
+60: void on_symbol_selected(const QString& symbol);
+61: void on_mode_toggled();
+62: void on_accounts_clicked(); // opens AccountManagementDialog
+63: void handle_token_expired(const QString& account_id);
+64: void on_order_submitted(const trading::UnifiedOrder& order);
+65: void on_cancel_order(const QString& order_id);
+66: void on_ob_price_clicked(double price);
+67: void on_import_holdings_requested(const QVector<trading::BrokerHolding>& holdings);
+68:
+69: void refresh_candles();
+70: void update_clock();
+71:
+72: // DataStreamManager signal handlers (on-demand / one-shot — kept as legacy signals)
+73: void on_stream_candles_fetched(const QString& account_id, const QVector<trading::BrokerCandle>& candles);
+74: void on_stream_orderbook_fetched(const QString& account_id,
+75: const QVector<QPair<double, double>>& bids,
+76: const QVector<QPair<double, double>>& asks,
+77: double spread, double spread_pct,
+78: const QVector<int>& bid_orders,
+79: const QVector<int>& ask_orders);
+80: void on_stream_time_sales_fetched(const QString& account_id, const QVector<trading::BrokerTrade>& trades);
+81: void on_stream_latest_trade_fetched(const QString& account_id, const trading::BrokerTrade& trade);
+82: void on_stream_calendar_fetched(const QString& account_id, const QVector<trading::MarketCalendarDay>& days);
+83: void on_stream_clock_fetched(const QString& account_id, const trading::MarketClock& clock);
+84:
+85: private:
+86: void setup_ui();
+87: void setup_timers();
+88: void connect_data_stream_signals();
+89: void init_focused_account();
+90: void switch_symbol(const QString& symbol);
+91: void update_account_menu();
+92: void update_connection_status();
+93: void async_modify_order(const QString& order_id, double qty, double price);
+94:
+95: // DataHub subscription helpers (D4 migration)
+96: void hub_subscribe_streaming();
+97: void hub_unsubscribe_all();
+98: void hub_subscribe_quotes();
+99: QString broker_id_for_focused() const;
+100:
+101: // ── Command bar widgets ──
+102: QPushButton* account_btn_ = nullptr; // shows focused account name
+103: QMenu* account_menu_ = nullptr; // lists all active accounts
+104: QLineEdit* symbol_input_ = nullptr;
+105: QPushButton* mode_btn_ = nullptr;
+106: QPushButton* accounts_btn_ = nullptr; // opens AccountManagementDialog
+107: QLabel* exchange_label_ = nullptr;
+108: QLabel* clock_label_ = nullptr;
+109: QLabel* conn_label_ = nullptr; // aggregate connection status
+110:
+111: // ── Sub-widgets ──
+112: equity::EquityTickerBar* ticker_bar_ = nullptr;
+113: equity::EquityWatchlist* watchlist_ = nullptr;
+114: equity::EquityChart* chart_ = nullptr;
+115: equity::EquityOrderEntry* order_entry_ = nullptr;
+116: equity::EquityOrderBook* orderbook_ = nullptr;
+117: equity::EquityBottomPanel* bottom_panel_ = nullptr;
+118:
+119: // ── Timers (only UI-local timers remain; data timers are in AccountDataStream) ──
+120: QTimer* clock_timer_ = nullptr;
+121: QTimer* market_clock_timer_ = nullptr;
+122:
+123: // ── Multi-account state ──
+124: QString focused_account_id_; // the account targeted by order entry + chart
+125: QString selected_symbol_ = "RELIANCE";
+126: QString selected_exchange_ = "NSE";
+127:
+128: // Paper trading (derived from focused account)
+129: int fill_cb_id_ = -1; // OrderMatcher fill callback
+130:
+131: // Async guards
+132: std::atomic<bool> token_expired_shown_{false};
+133:
+134: QStringList watchlist_symbols_;
+135: double current_price_ = 0.0; // last known LTP for selected symbol
+136:
+137: bool initialized_ = false;
+138: bool hub_active_ = false;
+139: QHash<QString, trading::BrokerQuote> watchlist_quote_cache_;
+140:
+141: // Symbol group link — SymbolGroup::None when unlinked.
+142: SymbolGroup link_group_ = SymbolGroup::None;
+143: };
+144:
+145: } // namespace fincept::screens
+
+========== EquityTradingScreen.cpp constructor + connects (1-120) ==========
+1: // Equity Trading Screen — multi-account coordinator.
+2: //
+3: // Core: ctor/dtor, show/hide events, setup_ui, setup_timers, update_clock,
+4: // connect_data_stream_signals, init_focused_account, update_account_menu,
+5: // update_connection_status, on_group_symbol_changed, current_symbol. Split
+6: // concerns:
+7: // - EquityTradingScreen_Streams.cpp — on_stream_* slots from DataStreamManager
+8: // - EquityTradingScreen_Handlers.cpp — user-action handlers
+9: // - EquityTradingScreen_Holdings.cpp — broker→portfolio holdings import
+10: #include "screens/equity_trading/EquityTradingScreen.h"
+11:
+12: #include "core/logging/Logger.h"
+13: #include "core/session/ScreenStateManager.h"
+14: #include "core/symbol/SymbolContext.h"
+15: #include "core/symbol/SymbolDragSource.h"
+16:
+17: #include <QApplication>
+18: #include <QMouseEvent>
+19: #include "screens/equity_trading/AccountManagementDialog.h"
+20: #include "screens/equity_trading/BroadcastOrderDialog.h"
+21: #include "screens/equity_trading/EquityBottomPanel.h"
+22: #include "screens/equity_trading/EquityChart.h"
+23: #include "screens/equity_trading/EquityOrderBook.h"
+24: #include "screens/equity_trading/EquityOrderEntry.h"
+25: #include "screens/equity_trading/EquityTickerBar.h"
+26: #include "screens/equity_trading/EquityWatchlist.h"
+27: #include "services/portfolio/PortfolioService.h"
+28: #include "storage/repositories/SettingsRepository.h"
+29: #include "trading/AccountManager.h"
+30: #include "trading/BrokerRegistry.h"
+31: #include "trading/DataStreamManager.h"
+32: #include "trading/OrderMatcher.h"
+33: #include "trading/PaperTrading.h"
+34: #include "trading/UnifiedTrading.h"
+35: #include "ui/theme/StyleSheets.h"
+36: #include "ui/theme/Theme.h"
+37:
+38: #include <QCheckBox>
+39: #include <QComboBox>
+40: #include <QCompleter>
+41: #include <QDate>
+42: #include <QDateTime>
+43: #include <QDialog>
+44: #include <QDialogButtonBox>
+45: #include <QFormLayout>
+46: #include <QHBoxLayout>
+47: #include <QHash>
+48: #include <QHeaderView>
+49: #include <QJsonArray>
+50: #include <QJsonDocument>
+51: #include <QJsonObject>
+52: #include <QLineEdit>
+53: #include <QMessageBox>
+54: #include <QPointer>
+55: #include <QPushButton>
+56: #include <QRadioButton>
+57: #include <QScrollBar>
+58: #include <QSplitter>
+59: #include <QStringListModel>
+60: #include <QTableWidget>
+61: #include <QVBoxLayout>
+62:
+63: #include <memory>
+64:
+65: #include <QtConcurrent/QtConcurrent>
+66:
+67:
+68: namespace fincept::screens {
+69:
+70: using namespace fincept::trading;
+71: using namespace fincept::screens::equity;
+72:
+73: static const QString TAG = "EquityTrading";
+74:
+75: EquityTradingScreen::EquityTradingScreen(QWidget* parent) : QWidget(parent) {
+76: watchlist_symbols_ = DEFAULT_WATCHLIST;
+77: setup_ui();
+78: setup_timers();
+79: connect_data_stream_signals();
+80:
+81: // Accept symbol drops anywhere on the screen — route through the
+82: // existing selection path so sub-panels resync and the linked group is
+83: // published to.
+84: symbol_dnd::installDropFilter(this, [this](const SymbolRef& ref, SymbolGroup) {
+85: if (ref.is_valid())
+86: on_symbol_selected(ref.symbol);
+87: });
+88: }
+89:
+90: EquityTradingScreen::~EquityTradingScreen() {
+91: if (fill_cb_id_ >= 0)
+92: OrderMatcher::instance().remove_fill_callback(fill_cb_id_);
+93: }
+94:
+95: // ============================================================================
+96: // Visibility — start/stop data streams (P3)
+97: // ============================================================================
+98:
+99: void EquityTradingScreen::showEvent(QShowEvent* event) {
+100: QWidget::showEvent(event);
+101:
+102: // Restore persisted session state on first show
+103: if (!initialized_) {
+104: const auto s = ScreenStateManager::instance().load_direct("equity_trading");
+105: if (!s.isEmpty()) {
+106: const QString acct = s.value("focused_account_id").toString();
+107: const QString sym = s.value("selected_symbol", selected_symbol_).toString();
+108: if (!acct.isEmpty() && acct != focused_account_id_ && AccountManager::instance().has_account(acct))
+109: on_account_changed(acct);
+110: if (sym != selected_symbol_)
+111: on_symbol_selected(sym);
+112: }
+113: }
+114:
+115: // Start all active account data streams
+116: DataStreamManager::instance().start_all_active();
+117: DataStreamManager::instance().resume_all();
+118:
+119: // Hub subscriptions for streaming data (D4)
+120: hub_subscribe_streaming();
+
+========== how market data refreshed: grep methods ==========
+109: on_account_changed(acct);
+323: stream->fetch_candles(selected_symbol_, tf);
+341: stream->fetch_clock();
+350: on_account_changed(accounts.first().account_id);
+370: connect(&dsm, &DataStreamManager::candles_fetched,
+371: this, &EquityTradingScreen::on_stream_candles_fetched);
+372: connect(&dsm, &DataStreamManager::orderbook_fetched,
+373: this, &EquityTradingScreen::on_stream_orderbook_fetched);
+374: connect(&dsm, &DataStreamManager::time_sales_fetched,
+375: this, &EquityTradingScreen::on_stream_time_sales_fetched);
+376: connect(&dsm, &DataStreamManager::latest_trade_fetched,
+377: this, &EquityTradingScreen::on_stream_latest_trade_fetched);
+378: connect(&dsm, &DataStreamManager::calendar_fetched,
+379: this, &EquityTradingScreen::on_stream_calendar_fetched);
+380: connect(&dsm, &DataStreamManager::clock_fetched,
+381: this, &EquityTradingScreen::on_stream_clock_fetched);
+403: auto* broker = BrokerRegistry::instance().get(account.broker_id);
+407: order_entry_->set_broker_id(account.broker_id);
+408: watchlist_->set_broker_id(account.broker_id);
+440: LOG_WARN(TAG, "Exception refreshing paper portfolio on fill");
+464: stream->fetch_candles(selected_symbol_, chart_->current_timeframe());
+465: stream->fetch_orderbook(selected_symbol_);
+466: stream->fetch_time_sales(selected_symbol_);
+467: stream->fetch_calendar();
+468: stream->fetch_clock();
+490: auto* broker = BrokerRegistry::instance().get(acct.broker_id);
+491: const QString broker_name = broker ? broker->profile().display_name : acct.broker_id;
+494: on_account_changed(id);
+568: on_account_changed(acct);
diff --git a/fincept-qt/fixscan.txt b/fincept-qt/fixscan.txt
new file mode 100644
index 000000000..2072d9768
--- /dev/null
+++ b/fincept-qt/fixscan.txt
@@ -0,0 +1,143 @@
+## A: where exchange_token is called (connect)
+src/screens/equity_trading/AccountManagementDialog.cpp:522: // Attempt token exchange asynchronously — exchange_token() makes a blocking
+src/screens/equity_trading/AccountManagementDialog.cpp:538: auto result = broker->exchange_token(api_key_val, api_secret_val, auth_code_val);
+src/screens/equity_trading/AccountManagementDialog.cpp:977: auto result = broker.exchange_token(api_key, api_secret, request_token);
+src/screens/equity_trading/AccountManagementDialog.cpp:1242: auto result = broker.exchange_token(client_id, api_secret, auth_code);
+src/screens/equity_trading/AccountManagementDialog.cpp:1461: auto result = broker.exchange_token(meta_token, QString(), auth_code_json);
+
+## B: credentials_saved signal + handlers
+src/screens/crypto_trading/CryptoTradingScreen_Handlers.cpp:205: connect(dlg, &CryptoCredentials::credentials_saved, this,
+src/screens/crypto_trading/CryptoCredentials.cpp:199: emit credentials_saved(api_key(), api_secret(), password());
+src/screens/polymarket/PolymarketScreen.cpp:204: connect(dlg, &PredictionAccountDialog::credentials_saved, this, [this](const QString& id) {
+src/screens/polymarket/PredictionAccountDialog.cpp:235: emit credentials_saved(QStringLiteral("polymarket"));
+src/screens/polymarket/PredictionAccountDialog.cpp:254: emit credentials_saved(QStringLiteral("polymarket"));
+src/screens/polymarket/PredictionAccountDialog.cpp:278: emit credentials_saved(QStringLiteral("kalshi"));
+src/screens/polymarket/PredictionAccountDialog.cpp:295: emit credentials_saved(QStringLiteral("kalshi"));
+src/screens/crypto_trading/CryptoCredentials.h:23: void credentials_saved(const QString& api_key, const QString& api_secret, const QString& password);
+src/screens/polymarket/PredictionAccountDialog.h:37: void credentials_saved(const QString& exchange_id);
+src/screens/equity_trading/EquityTradingScreen_Handlers.cpp:125: // process (see crash report 2026-05-08-123609.ips). The credentials_saved
+src/screens/equity_trading/EquityTradingScreen_Handlers.cpp:269: // crash report 2026-05-08-123609.ips). Defer focus to credentials_saved.
+src/screens/equity_trading/EquityTradingScreen_Handlers.cpp:286: connect(dlg, &AccountManagementDialog::credentials_saved, this, [this](const QString& account_id) {
+src/screens/equity_trading/AccountManagementDialog.cpp:579: emit self->credentials_saved(account_id);
+src/screens/equity_trading/AccountManagementDialog.cpp:862: emit self->credentials_saved(acct);
+src/screens/equity_trading/AccountManagementDialog.cpp:992: emit self->credentials_saved(acct);
+src/screens/equity_trading/AccountManagementDialog.cpp:1263: emit self->credentials_saved(acct);
+src/screens/equity_trading/AccountManagementDialog.cpp:1477: emit self->credentials_saved(acct);
+src/screens/equity_trading/AccountManagementDialog.h:34: void credentials_saved(const QString& account_id);
+
+## C: equity_trading files
+AccountManagementDialog.cpp
+AccountManagementDialog.h
+BroadcastOrderDialog.cpp
+BroadcastOrderDialog.h
+EquityBottomPanel.cpp
+EquityBottomPanel.h
+EquityChart.cpp
+EquityChart.h
+EquityOrderBook.cpp
+EquityOrderBook.h
+EquityOrderEntry.cpp
+EquityOrderEntry.h
+EquityTickerBar.cpp
+EquityTickerBar.h
+EquityTradingScreen_Handlers.cpp
+EquityTradingScreen_Holdings.cpp
+EquityTradingScreen_Streams.cpp
+EquityTradingScreen.cpp
+EquityTradingScreen.h
+EquityTypes.h
+EquityWatchlist.cpp
+EquityWatchlist.h
+
+## D: ChainSubTab.cpp lines 230-320
+ if (unders.isEmpty()) {
+ show_empty_state("Databento configuration error.");
+ return;
+ }
+ QString prefer;
+ if (keep_selection && unders.contains(last_underlying_))
+ prefer = last_underlying_;
+ else
+ prefer = unders.contains(QStringLiteral("SPY")) ? QStringLiteral("SPY") : unders.first();
+ header_->set_underlyings(unders, prefer);
+ rebuild_expiries_for_underlying(QStringLiteral("databento"), prefer, keep_selection);
+ return;
+ }
+ const bool loaded = InstrumentService::instance().is_loaded(broker_id);
+ LOG_INFO("FnoChain", QString("rebuild_picker_for_broker: is_loaded('%1')=%2").arg(broker_id).arg(loaded));
+ if (!loaded) {
+ show_empty_state(QString("Loading %1 instruments...").arg(broker_id));
+ header_->set_underlyings({});
+ header_->set_expiries({});
+
+ QPointer<ChainSubTab> self = this;
+ InstrumentService::instance().load_from_db_async(broker_id, [self, broker_id](int count) {
+ if (!self) {
+ LOG_WARN("FnoChain", QString("load_from_db_async callback: widget destroyed, broker='%1'").arg(broker_id));
+ return;
+ }
+ LOG_INFO("FnoChain", QString("load_from_db_async callback: broker='%1' count=%2").arg(broker_id).arg(count));
+ if (count > 0) {
+ self->rebuild_picker_for_broker(broker_id, true);
+ return;
+ }
+ QString account_id = find_account_for_broker(broker_id);
+ LOG_INFO("FnoChain", QString("find_account_for_broker('%1') → '%2'").arg(broker_id, account_id));
+ if (account_id.isEmpty()) {
+ self->show_empty_state(QString("No account configured for %1. Connect one in Equity Trading.").arg(broker_id));
+ return;
+ }
+ self->show_empty_state(QString("Downloading %1 instruments from broker...").arg(broker_id));
+ auto creds = trading::AccountManager::instance().load_credentials(account_id);
+ InstrumentService::instance().refresh(broker_id, creds);
+ });
+ return;
+ }
+ auto unders = OptionChainService::instance().list_underlyings(broker_id);
+ LOG_INFO("FnoChain", QString("list_underlyings('%1') → %2 items").arg(broker_id).arg(unders.size()));
+ if (unders.isEmpty()) {
+ show_empty_state("No NFO instruments cached for " + broker_id + ".");
+ header_->set_underlyings({});
+ header_->set_expiries({});
+ return;
+ }
+ QString prefer;
+ if (keep_selection && unders.contains(last_underlying_))
+ prefer = last_underlying_;
+ else
+ prefer = unders.contains("NIFTY") ? "NIFTY" : unders.first();
+ LOG_INFO("FnoChain", QString("Setting underlyings for '%1', prefer='%2' (%3 items)")
+ .arg(broker_id, prefer).arg(unders.size()));
+ header_->set_underlyings(unders, prefer);
+ LOG_INFO("FnoChain", "set_underlyings done, calling rebuild_expiries_for_underlying");
+ rebuild_expiries_for_underlying(broker_id, prefer, keep_selection);
+ LOG_INFO("FnoChain", "rebuild_expiries_for_underlying done");
+}
+
+void ChainSubTab::rebuild_expiries_for_underlying(const QString& broker_id, const QString& underlying,
+ bool keep_selection) {
+ if (broker_id == QStringLiteral("databento")) {
+ auto cached = OptionChainService::instance().list_expiries(QStringLiteral("databento"), underlying);
+ if (!cached.isEmpty()) {
+ QString prefer;
+ if (keep_selection && cached.contains(last_expiry_))
+ prefer = last_expiry_;
+ else
+ prefer = cached.first();
+ header_->set_expiries(cached, prefer);
+ if (is_visible_)
+ resubscribe();
+ return;
+ }
+ header_->set_expiries({});
+ show_empty_state(QString("Loading expiries for %1 from Databento...").arg(underlying));
+ QPointer<ChainSubTab> self = this;
+ OptionChainService::instance().list_databento_expiries(
+ underlying,
+ [self, underlying, keep_selection](const QStringList& exps) {
+ if (!self) return;
+ if (exps.isEmpty()) {
+ self->show_empty_state(
+ QString("No expiries found for %1. Check Databento API key and OPRA access.").arg(underlying));
+ return;
+ }
diff --git a/fincept-qt/run-tidy-changed.sh b/fincept-qt/run-tidy-changed.sh
new file mode 100755
index 000000000..25f2d30b9
--- /dev/null
+++ b/fincept-qt/run-tidy-changed.sh
@@ -0,0 +1,54 @@
+#!/bin/bash
+# Run clang-tidy-18 on changed C++ source files using flags extracted from the
+# unity-build compile DB (so unity-included files can still be analyzed).
+# Usage: run-tidy-changed.sh [file1 file2 ...] (no args = all changed .cpp)
+set -uo pipefail
+
+REPO=/Users/tilak/projects/FinceptTerminal
+TIDY=/opt/homebrew/opt/llvm@18/bin/clang-tidy
+CFG=/tmp/fincept-tidy18.yaml
+SDK=$(xcrun --show-sdk-path)
+
+cd "$REPO/fincept-qt" || exit 2
+
+# Extract the target's compile flags from a unity blob entry (identical for all
+# files in the FinceptTerminal target). Drop compiler, -c/-o, and source file.
+FLAGS=()
+while IFS= read -r line; do [ -n "$line" ] && FLAGS+=("$line"); done < <(python3 - <<'PY'
+import json
+db=json.load(open("build/macos-release/compile_commands.json"))
+e=next(x for x in db if "Unity/unity_" in x["file"])
+toks=(e.get("command") or " ".join(e["arguments"])).split()
+out=[]; i=1
+while i < len(toks):
+ t=toks[i]
+ if t in ("-c","-o"): i+=2; continue
+ # Drop CMake precompiled-header injection (PCH not built for lint)
+ # Strip the whole CMake PCH group: -Winvalid-pch -Xclang -include-pch
+ # -Xclang <pch> -Xclang -include -Xclang <hxx> (real includes use -I)
+ if t in ("-Xclang","-include-pch","-include","-Winvalid-pch"): i+=1; continue
+ if "cmake_pch" in t: i+=1; continue
+ out.append(t); i+=1
+out=[t for t in out if not t.endswith(".cxx") and not t.endswith(".o")]
+print("\n".join(out))
+PY
+)
+FLAGS+=("-isysroot" "$SDK")
+
+FILES=()
+if [ "$#" -gt 0 ]; then
+ FILES=("$@")
+else
+ while IFS= read -r line; do [ -n "$line" ] && FILES+=("$line"); done < <(
+ git -C "$REPO" diff --name-only --diff-filter=d \
+ | grep -E 'fincept-qt/src/.*\.cpp$' | grep -vE '/moc_|/qrc_' \
+ | sed 's#fincept-qt/##'
+ )
+fi
+
+echo "clang-tidy-18 on ${#FILES[@]} file(s) | ${#FLAGS[@]} compile flags"
+echo "=================================================="
+for f in "${FILES[@]}"; do
+ [ -f "$f" ] || { echo "MISSING FILE: $f"; continue; }
+ "$TIDY" --config-file="$CFG" --quiet "$f" -- "${FLAGS[@]}" 2>&1
+done
diff --git a/fincept-qt/scripts/strategies/AccumulativeInsightPortfolioRegressionAlgorithm.py b/fincept-qt/scripts/strategies/AccumulativeInsightPortfolioRegressionAlgorithm.py
deleted file mode 100644
index a3167a8a0..000000000
--- a/fincept-qt/scripts/strategies/AccumulativeInsightPortfolioRegressionAlgorithm.py
+++ /dev/null
@@ -1,59 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-19E8A564
-# Category: Portfolio Management
-# Description: Accumulative position building strategy. Starts with 25%
-# allocation on initial EMA crossover. Adds 25% on each pullback to EMA
-# that bounces. Maximum 100% allocation. Exits on bearish EMA cross.
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-class AccumulativeInsightPortfolioRegressionAlgorithm(QCAlgorithm):
- """Accumulative position building with EMA trend."""
-
- def initialize(self):
- self.set_start_date(2023, 1, 1)
- self.set_end_date(2024, 1, 1)
- self.set_cash(100000)
-
- self.symbol = "SPY"
- self.add_equity(self.symbol, Resolution.DAILY)
-
- self._fast_ema = self.ema(self.symbol, 10, Resolution.DAILY)
- self._slow_ema = self.ema(self.symbol, 30, Resolution.DAILY)
- self._current_weight = 0
- self._touched_ema = False
-
- def on_data(self, data):
- if not self._slow_ema.is_ready:
- return
- if self.symbol not in data:
- return
-
- price = data[self.symbol].close
- fast = self._fast_ema.current.value
- slow = self._slow_ema.current.value
-
- if fast > slow:
- # Uptrend
- if self._current_weight == 0:
- self._current_weight = 0.5
- self.set_holdings(self.symbol, self._current_weight)
- self._touched_ema = False
- elif price <= fast * 1.002:
- self._touched_ema = True
- elif self._touched_ema and price > fast and self._current_weight < 1.0:
- self._current_weight = min(1.0, self._current_weight + 0.25)
- self.set_holdings(self.symbol, self._current_weight)
- self._touched_ema = False
- else:
- # Downtrend - exit all
- if self._current_weight > 0:
- self.liquidate()
- self._current_weight = 0
- self._touched_ema = False
diff --git a/fincept-qt/scripts/strategies/AddAlphaModelAlgorithm.py b/fincept-qt/scripts/strategies/AddAlphaModelAlgorithm.py
deleted file mode 100644
index b1043bbe3..000000000
--- a/fincept-qt/scripts/strategies/AddAlphaModelAlgorithm.py
+++ /dev/null
@@ -1,54 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-761339E9
-# Category: Alpha Model
-# Description: Test algorithm using 'QCAlgorithm.add_alpha_model()'
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Test algorithm using 'QCAlgorithm.add_alpha_model()'
-### </summary>
-class AddAlphaModelAlgorithm(QCAlgorithm):
- def initialize(self):
- ''' Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
-
- self.set_start_date(2013,10,7) #Set Start Date
- self.set_end_date(2013,10,11) #Set End Date
- self.set_cash(100000) #Set Strategy Cash
-
- self.universe_settings.resolution = Resolution.DAILY
-
- spy = Symbol.create("SPY", SecurityType.EQUITY, Market.USA)
- fb = Symbol.create("FB", SecurityType.EQUITY, Market.USA)
- ibm = Symbol.create("IBM", SecurityType.EQUITY, Market.USA)
-
- # set algorithm framework models
- self.set_universe_selection(ManualUniverseSelectionModel([ spy, fb, ibm ]))
- self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())
- self.set_execution(ImmediateExecutionModel())
-
- self.add_alpha(OneTimeAlphaModel(spy))
- self.add_alpha(OneTimeAlphaModel(fb))
- self.add_alpha(OneTimeAlphaModel(ibm))
-
-class OneTimeAlphaModel(AlphaModel):
- def __init__(self, symbol):
- self.symbol = symbol
- self.triggered = False
-
- def update(self, algorithm, data):
- insights = []
- if not self.triggered:
- self.triggered = True
- insights.append(Insight.price(
- self.symbol,
- Resolution.DAILY,
- 1,
- InsightDirection.DOWN))
- return insights
diff --git a/fincept-qt/scripts/strategies/AddFutureOptionContractDataStreamingRegressionAlgorithm.py b/fincept-qt/scripts/strategies/AddFutureOptionContractDataStreamingRegressionAlgorithm.py
deleted file mode 100644
index a5aab8223..000000000
--- a/fincept-qt/scripts/strategies/AddFutureOptionContractDataStreamingRegressionAlgorithm.py
+++ /dev/null
@@ -1,92 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-3CCF5CE2
-# Category: Options
-# Description: This regression algorithm tests that we receive the expected data when we add future option contracts individually us...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### This regression algorithm tests that we receive the expected data when
-### we add future option contracts individually using <see cref="AddFutureOptionContract"/>
-### </summary>
-class AddFutureOptionContractDataStreamingRegressionAlgorithm(QCAlgorithm):
- def initialize(self):
- self.on_data_reached = False
- self.invested = False
- self.symbols_received = []
- self.expected_symbols_received = []
- self.data_received = {}
-
- self.set_start_date(2020, 1, 4)
- self.set_end_date(2020, 1, 8)
-
- self.es20h20 = self.add_future_contract(
- Symbol.create_future(Futures.Indices.SP_500_E_MINI, Market.CME, datetime(2020, 3, 20)),
- Resolution.MINUTE).symbol
-
- self.es19m20 = self.add_future_contract(
- Symbol.create_future(Futures.Indices.SP_500_E_MINI, Market.CME, datetime(2020, 6, 19)),
- Resolution.MINUTE).symbol
-
- # Get option contract lists for 2020/01/05 (timedelta(days=1)) because Lean has local data for that date
- option_chains = self.option_chain_provider.get_option_contract_list(self.es20h20, self.time + timedelta(days=1))
- option_chains += self.option_chain_provider.get_option_contract_list(self.es19m20, self.time + timedelta(days=1))
-
- for option_contract in option_chains:
- self.expected_symbols_received.append(self.add_future_option_contract(option_contract, Resolution.MINUTE).symbol)
-
- def on_data(self, data: Slice):
- if not data.has_data:
- return
-
- self.on_data_reached = True
- has_option_quote_bars = False
-
- for qb in data.quote_bars.values():
- if qb.symbol.security_type != SecurityType.FUTURE_OPTION:
- continue
-
- has_option_quote_bars = True
-
- self.symbols_received.append(qb.symbol)
- if qb.symbol not in self.data_received:
- self.data_received[qb.symbol] = []
-
- self.data_received[qb.symbol].append(qb)
-
- if self.invested or not has_option_quote_bars:
- return
-
- if data.contains_key(self.es20h20) and data.contains_key(self.es19m20):
- self.set_holdings(self.es20h20, 0.2)
- self.set_holdings(self.es19m20, 0.2)
-
- self.invested = True
-
- def on_end_of_algorithm(self):
- self.symbols_received = list(set(self.symbols_received))
- self.expected_symbols_received = list(set(self.expected_symbols_received))
-
- if not self.on_data_reached:
- raise AssertionError("OnData() was never called.")
- if len(self.symbols_received) != len(self.expected_symbols_received):
- raise AssertionError(f"Expected {len(self.expected_symbols_received)} option contracts Symbols, found {len(self.symbols_received)}")
-
- missing_symbols = [expected_symbol for expected_symbol in self.expected_symbols_received if expected_symbol not in self.symbols_received]
- if any(missing_symbols):
- raise AssertionError(f'Symbols: "{", ".join(missing_symbols)}" were not found in OnData')
-
- for expected_symbol in self.expected_symbols_received:
- data = self.data_received[expected_symbol]
- for data_point in data:
- data_point.end_time = datetime(1970, 1, 1)
-
- non_dupe_data_count = len(set(data))
- if non_dupe_data_count < 1000:
- raise AssertionError(f"Received too few data points. Expected >=1000, found {non_dupe_data_count} for {expected_symbol}")
diff --git a/fincept-qt/scripts/strategies/AddFutureOptionSingleOptionChainSelectedInUniverseFilterRegressionAlgorithm.py b/fincept-qt/scripts/strategies/AddFutureOptionSingleOptionChainSelectedInUniverseFilterRegressionAlgorithm.py
deleted file mode 100644
index 37c1969f0..000000000
--- a/fincept-qt/scripts/strategies/AddFutureOptionSingleOptionChainSelectedInUniverseFilterRegressionAlgorithm.py
+++ /dev/null
@@ -1,118 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-2EF41B6D
-# Category: Options
-# Description: This regression algorithm tests that we only receive the option chain for a single future contract in the option univ...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### This regression algorithm tests that we only receive the option chain for a single future contract
-### in the option universe filter.
-### </summary>
-class AddFutureOptionSingleOptionChainSelectedInUniverseFilterRegressionAlgorithm(QCAlgorithm):
- def initialize(self):
- self.invested = False
- self.on_data_reached = False
- self.option_filter_ran = False
- self.symbols_received = []
- self.expected_symbols_received = []
- self.data_received = {}
-
- self.set_start_date(2020, 1, 4)
- self.set_end_date(2020, 1, 8)
-
- self.es = self.add_future(Futures.Indices.SP_500_E_MINI, Resolution.MINUTE, Market.CME)
- self.es.set_filter(lambda future_filter: future_filter.expiration(0, 365).expiration_cycle([3, 6]))
-
- self.add_future_option(self.es.symbol, self.option_contract_universe_filter_function)
-
- def option_contract_universe_filter_function(self, option_contracts: OptionFilterUniverse) -> OptionFilterUniverse:
- self.option_filter_ran = True
-
- expiry = list(set([x.symbol.underlying.id.date for x in option_contracts]))
- expiry = None if not any(expiry) else expiry[0]
-
- symbol = [x.symbol.underlying for x in option_contracts]
- symbol = None if not any(symbol) else symbol[0]
-
- if expiry is None or symbol is None:
- raise AssertionError("Expected a single Option contract in the chain, found 0 contracts")
-
- enumerator = option_contracts.get_enumerator()
- while enumerator.move_next():
- self.expected_symbols_received.append(enumerator.current.symbol)
-
- return option_contracts
-
- def on_data(self, data: Slice):
- if not data.has_data:
- return
-
- self.on_data_reached = True
- has_option_quote_bars = False
-
- for qb in data.quote_bars.values():
- if qb.symbol.security_type != SecurityType.FUTURE_OPTION:
- continue
-
- has_option_quote_bars = True
-
- self.symbols_received.append(qb.symbol)
- if qb.symbol not in self.data_received:
- self.data_received[qb.symbol] = []
-
- self.data_received[qb.symbol].append(qb)
-
- if self.invested or not has_option_quote_bars:
- return
-
- for chain in data.option_chains.values():
- future_invested = False
- option_invested = False
-
- for option in chain.contracts.keys():
- if future_invested and option_invested:
- return
-
- future = option.underlying
-
- if not option_invested and data.contains_key(option):
- self.market_order(option, 1)
- self.invested = True
- option_invested = True
-
- if not future_invested and data.contains_key(future):
- self.market_order(future, 1)
- self.invested = True
- future_invested = True
-
- def on_end_of_algorithm(self):
- super().on_end_of_algorithm()
- self.symbols_received = list(set(self.symbols_received))
- self.expected_symbols_received = list(set(self.expected_symbols_received))
-
- if not self.option_filter_ran:
- raise AssertionError("Option chain filter was never ran")
- if not self.on_data_reached:
- raise AssertionError("OnData() was never called.")
- if len(self.symbols_received) != len(self.expected_symbols_received):
- raise AssertionError(f"Expected {len(self.expected_symbols_received)} option contracts Symbols, found {len(self.symbols_received)}")
-
- missing_symbols = [expected_symbol for expected_symbol in self.expected_symbols_received if expected_symbol not in self.symbols_received]
- if any(missing_symbols):
- raise AssertionError(f'Symbols: "{", ".join(missing_symbols)}" were not found in OnData')
-
- for expected_symbol in self.expected_symbols_received:
- data = self.data_received[expected_symbol]
- for data_point in data:
- data_point.end_time = datetime(1970, 1, 1)
-
- non_dupe_data_count = len(set(data))
- if non_dupe_data_count < 1000:
- raise AssertionError(f"Received too few data points. Expected >=1000, found {non_dupe_data_count} for {expected_symbol}")
diff --git a/fincept-qt/scripts/strategies/AddOptionContractExpiresRegressionAlgorithm.py b/fincept-qt/scripts/strategies/AddOptionContractExpiresRegressionAlgorithm.py
deleted file mode 100644
index ac895c629..000000000
--- a/fincept-qt/scripts/strategies/AddOptionContractExpiresRegressionAlgorithm.py
+++ /dev/null
@@ -1,61 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-5CED3309
-# Category: Options
-# Description: We add an option contract using 'QCAlgorithm.add_option_contract' and place a trade, the underlying gets deselected f...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### We add an option contract using 'QCAlgorithm.add_option_contract' and place a trade, the underlying
-### gets deselected from the universe selection but should still be present since we manually added the option contract.
-### Later we call 'QCAlgorithm.remove_option_contract' and expect both option and underlying to be removed.
-### </summary>
-class AddOptionContractExpiresRegressionAlgorithm(QCAlgorithm):
- def initialize(self):
- '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
-
- self.set_start_date(2014, 6, 5)
- self.set_end_date(2014, 6, 30)
-
- self._expiration = datetime(2014, 6, 21)
- self._option = None
- self._traded = False
-
- self._twx = Symbol.create("TWX", SecurityType.EQUITY, Market.USA)
-
- self.add_universe("my-daily-universe-name", self.selector)
-
- def selector(self, time):
- return [ "AAPL" ]
-
- def on_data(self, data):
- '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
-
- Arguments:
- data: Slice object keyed by symbol containing the stock data
- '''
- if self._option == None:
- options = self.option_chain(self._twx)
- options = sorted(options, key=lambda x: x.id.symbol)
-
- option = next((option
- for option in options
- if option.id.date == self._expiration and
- option.id.option_right == OptionRight.CALL and
- option.id.option_style == OptionStyle.AMERICAN), None)
- if option != None:
- self._option = self.add_option_contract(option).symbol
-
- if self._option != None and self.securities[self._option].price != 0 and not self._traded:
- self._traded = True
- self.buy(self._option, 1)
-
- if self.time > self._expiration and self.securities[self._twx].invested:
- # we liquidate the option exercised position
- self.liquidate(self._twx)
diff --git a/fincept-qt/scripts/strategies/AddOptionContractFromUniverseRegressionAlgorithm.py b/fincept-qt/scripts/strategies/AddOptionContractFromUniverseRegressionAlgorithm.py
deleted file mode 100644
index 845ecf499..000000000
--- a/fincept-qt/scripts/strategies/AddOptionContractFromUniverseRegressionAlgorithm.py
+++ /dev/null
@@ -1,81 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-202B8187
-# Category: Options
-# Description: We add an option contract using 'QCAlgorithm.add_option_contract' and place a trade, the underlying gets deselected f...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### We add an option contract using 'QCAlgorithm.add_option_contract' and place a trade, the underlying
-### gets deselected from the universe selection but should still be present since we manually added the option contract.
-### Later we call 'QCAlgorithm.remove_option_contract' and expect both option and underlying to be removed.
-### </summary>
-class AddOptionContractFromUniverseRegressionAlgorithm(QCAlgorithm):
- def initialize(self):
- '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
-
- self.set_start_date(2014, 6, 5)
- self.set_end_date(2014, 6, 9)
-
- self._expiration = datetime(2014, 6, 21)
- self._security_changes = None
- self._option = None
- self._traded = False
-
- self._twx = Symbol.create("TWX", SecurityType.EQUITY, Market.USA)
- self._aapl = Symbol.create("AAPL", SecurityType.EQUITY, Market.USA)
- self.universe_settings.resolution = Resolution.MINUTE
- self.universe_settings.data_normalization_mode = DataNormalizationMode.RAW
-
- self.add_universe(self.selector, self.selector)
-
- def selector(self, fundamental):
- if self.time <= datetime(2014, 6, 5):
- return [ self._twx ]
- return [ self._aapl ]
-
- def on_data(self, data):
- '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
-
- Arguments:
- data: Slice object keyed by symbol containing the stock data
- '''
- if self._option != None and self.securities[self._option].price != 0 and not self._traded:
- self._traded = True
- self.buy(self._option, 1)
-
- if self.time == datetime(2014, 6, 6, 14, 0, 0):
- # liquidate & remove the option
- self.remove_option_contract(self._option)
-
- def on_securities_changed(self, changes):
- # keep track of all removed and added securities
- if self._security_changes == None:
- self._security_changes = changes
- else:
- self._security_changes += changes
-
- if any(security.symbol.security_type == SecurityType.OPTION for security in changes.added_securities):
- return
-
- for addedSecurity in changes.added_securities:
- options = self.option_chain(addedSecurity.symbol)
- options = sorted(options, key=lambda x: x.id.symbol)
-
- option = next((option
- for option in options
- if option.id.date == self._expiration and
- option.id.option_right == OptionRight.CALL and
- option.id.option_style == OptionStyle.AMERICAN), None)
-
- self.add_option_contract(option)
-
- # just keep the first we got
- if self._option == None:
- self._option = option
diff --git a/fincept-qt/scripts/strategies/AddRemoveSecurityRegressionAlgorithm.py b/fincept-qt/scripts/strategies/AddRemoveSecurityRegressionAlgorithm.py
deleted file mode 100644
index 6a9a6c528..000000000
--- a/fincept-qt/scripts/strategies/AddRemoveSecurityRegressionAlgorithm.py
+++ /dev/null
@@ -1,63 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-DA228821
-# Category: Regression Test
-# Description: This algorithm demonstrates the runtime addition and removal of securities from your algorithm. With LEAN it is possi...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### This algorithm demonstrates the runtime addition and removal of securities from your algorithm.
-### With LEAN it is possible to add and remove securities after the initialization.
-### </summary>
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="assets" />
-### <meta name="tag" content="regression test" />
-class AddRemoveSecurityRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self):
- '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
-
- self.set_start_date(2013,10,7) #Set Start Date
- self.set_end_date(2013,10,11) #Set End Date
- self.set_cash(100000) #Set Strategy Cash
- # Fincept Terminal Strategy Engine - Symbol Configuration
- self.add_equity("SPY")
-
- self._last_action = None
-
-
- def on_data(self, data):
- '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.'''
- if self._last_action is not None and self._last_action.date() == self.time.date():
- return
-
- if not self.portfolio.invested:
- self.set_holdings("SPY", .5)
- self._last_action = self.time
-
- if self.time.weekday() == 1:
- self.add_equity("AIG")
- self.add_equity("BAC")
- self._last_action = self.time
-
- if self.time.weekday() == 2:
- self.set_holdings("AIG", .25)
- self.set_holdings("BAC", .25)
- self._last_action = self.time
-
- if self.time.weekday() == 3:
- self.remove_security("AIG")
- self.remove_security("BAC")
- self._last_action = self.time
-
- def on_order_event(self, order_event):
- if order_event.status == OrderStatus.SUBMITTED:
- self.debug("{0}: Submitted: {1}".format(self.time, self.transactions.get_order_by_id(order_event.order_id)))
- if order_event.status == OrderStatus.FILLED:
- self.debug("{0}: Filled: {1}".format(self.time, self.transactions.get_order_by_id(order_event.order_id)))
diff --git a/fincept-qt/scripts/strategies/AddRiskManagementAlgorithm.py b/fincept-qt/scripts/strategies/AddRiskManagementAlgorithm.py
deleted file mode 100644
index 4f70dc37d..000000000
--- a/fincept-qt/scripts/strategies/AddRiskManagementAlgorithm.py
+++ /dev/null
@@ -1,42 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-9874FF18
-# Category: Risk Management
-# Description: Test algorithm using 'QCAlgorithm.add_risk_management(IRiskManagementModel)'
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Test algorithm using 'QCAlgorithm.add_risk_management(IRiskManagementModel)'
-### </summary>
-class AddRiskManagementAlgorithm(QCAlgorithm):
- '''Basic template framework algorithm uses framework components to define the algorithm.'''
-
- def initialize(self):
- ''' Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
- self.universe_settings.resolution = Resolution.MINUTE
-
- self.set_start_date(2013,10,7) #Set Start Date
- self.set_end_date(2013,10,11) #Set End Date
- self.set_cash(100000) #Set Strategy Cash
-
- symbols = [ Symbol.create("SPY", SecurityType.EQUITY, Market.USA) ]
-
- # set algorithm framework models
- self.set_universe_selection(ManualUniverseSelectionModel(symbols))
- self.set_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(minutes = 20), 0.025, None))
- self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())
- self.set_execution(ImmediateExecutionModel())
-
- # Both setting methods should work
- risk_model = CompositeRiskManagementModel(MaximumDrawdownPercentPortfolio(0.02))
- risk_model.add_risk_management(MaximumUnrealizedProfitPercentPerSecurity(0.01))
-
- self.set_risk_management(MaximumDrawdownPercentPortfolio(0.02))
- self.add_risk_management(MaximumUnrealizedProfitPercentPerSecurity(0.01))
-
diff --git a/fincept-qt/scripts/strategies/AddUniverseSelectionModelAlgorithm.py b/fincept-qt/scripts/strategies/AddUniverseSelectionModelAlgorithm.py
deleted file mode 100644
index c036dee74..000000000
--- a/fincept-qt/scripts/strategies/AddUniverseSelectionModelAlgorithm.py
+++ /dev/null
@@ -1,42 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-8AB253F8
-# Category: Universe Selection
-# Description: Test algorithm using 'QCAlgorithm.add_universe_selection(IUniverseSelectionModel)'
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Test algorithm using 'QCAlgorithm.add_universe_selection(IUniverseSelectionModel)'
-### </summary>
-class AddUniverseSelectionModelAlgorithm(QCAlgorithm):
- def initialize(self):
- ''' Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
-
- self.set_start_date(2013,10,8) #Set Start Date
- self.set_end_date(2013,10,11) #Set End Date
- self.set_cash(100000) #Set Strategy Cash
-
- self.universe_settings.resolution = Resolution.DAILY
-
- # set algorithm framework models
- self.set_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(minutes = 20), 0.025, None))
- self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())
- self.set_execution(ImmediateExecutionModel())
-
- self.set_universe_selection(ManualUniverseSelectionModel([ Symbol.create("SPY", SecurityType.EQUITY, Market.USA) ]))
- self.add_universe_selection(ManualUniverseSelectionModel([ Symbol.create("AAPL", SecurityType.EQUITY, Market.USA) ]))
- self.add_universe_selection(ManualUniverseSelectionModel(
- Symbol.create("SPY", SecurityType.EQUITY, Market.USA), # duplicate will be ignored
- Symbol.create("FB", SecurityType.EQUITY, Market.USA)))
-
- def on_end_of_algorithm(self):
- if self.universe_manager.count != 3:
- raise ValueError("Unexpected universe count")
- if self.universe_manager.active_securities.count != 3:
- raise ValueError("Unexpected active securities")
diff --git a/fincept-qt/scripts/strategies/AlgorithmImports.py b/fincept-qt/scripts/strategies/AlgorithmImports.py
deleted file mode 100644
index 49189913d..000000000
--- a/fincept-qt/scripts/strategies/AlgorithmImports.py
+++ /dev/null
@@ -1,12 +0,0 @@
-# ============================================================================
-# Fincept Terminal - AlgorithmImports Shim
-# Thin wrapper that re-exports everything from fincept_engine.algorithm_imports
-# All actual code lives in fincept_engine/algorithm_imports.py
-# ============================================================================
-
-import os, sys
-_dir = os.path.dirname(os.path.abspath(__file__))
-if _dir not in sys.path:
- sys.path.insert(0, _dir)
-
-from fincept_engine.algorithm_imports import *
diff --git a/fincept-qt/scripts/strategies/AlgorithmModeAndDeploymentTargetAlgorithm.py b/fincept-qt/scripts/strategies/AlgorithmModeAndDeploymentTargetAlgorithm.py
deleted file mode 100644
index 9057db11f..000000000
--- a/fincept-qt/scripts/strategies/AlgorithmModeAndDeploymentTargetAlgorithm.py
+++ /dev/null
@@ -1,42 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-D137348C
-# Category: General Strategy
-# Description: Algorithm asserting the correct values for the deployment target and algorithm mode
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Algorithm asserting the correct values for the deployment target and algorithm mode.
-### </summary>
-class AlgorithmModeAndDeploymentTargetAlgorithm(QCAlgorithm):
- def initialize(self):
- self.set_start_date(2013,10, 7)
- self.set_end_date(2013,10,11)
- self.set_cash(100000)
-
- #translate commented code from c# to python
- self.debug(f"Algorithm Mode: {self.algorithm_mode}. Is Live Mode: {self.live_mode}. Deployment Target: {self.deployment_target}.")
-
- if self.algorithm_mode != AlgorithmMode.BACKTESTING:
- raise Exception(f"Algorithm mode is not backtesting. Actual: {self.algorithm_mode}")
-
- if self.live_mode:
- raise Exception("Algorithm should not be live")
-
- if self.deployment_target != DeploymentTarget.LOCAL_PLATFORM:
- raise Exception(f"Algorithm deployment target is not local. Actual{self.deployment_target}")
-
- # For a live deployment these checks should pass:
- # if self.algorithm_mode != AlgorithmMode.LIVE: raise Exception("Algorithm mode is not live")
- # if not self.live_mode: raise Exception("Algorithm should be live")
-
- # For a cloud deployment these checks should pass:
- # if self.deployment_target != DeploymentTarget.CLOUD_PLATFORM: raise Exception("Algorithm deployment target is not cloud")
-
- self.quit()
diff --git a/fincept-qt/scripts/strategies/AllShortableSymbolsCoarseSelectionRegressionAlgorithm.py b/fincept-qt/scripts/strategies/AllShortableSymbolsCoarseSelectionRegressionAlgorithm.py
deleted file mode 100644
index 07f105875..000000000
--- a/fincept-qt/scripts/strategies/AllShortableSymbolsCoarseSelectionRegressionAlgorithm.py
+++ /dev/null
@@ -1,135 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-6C937E43
-# Category: Regression Test
-# Description: Tests filtering in coarse selection by shortable quantity
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Tests filtering in coarse selection by shortable quantity
-### </summary>
-class AllShortableSymbolsCoarseSelectionRegressionAlgorithm(QCAlgorithm):
- def initialize(self):
- self._20140325 = datetime(2014, 3, 25)
- self._20140326 = datetime(2014, 3, 26)
- self._20140327 = datetime(2014, 3, 27)
- self._20140328 = datetime(2014, 3, 28)
- self._20140329 = datetime(2014, 3, 29)
- self.last_trade_date = datetime(1,1,1)
-
- self._aapl = Symbol.create("AAPL", SecurityType.EQUITY, Market.USA)
- self._bac = Symbol.create("BAC", SecurityType.EQUITY, Market.USA)
- self._gme = Symbol.create("GME", SecurityType.EQUITY, Market.USA)
- self._goog = Symbol.create("GOOG", SecurityType.EQUITY, Market.USA)
- self._qqq = Symbol.create("QQQ", SecurityType.EQUITY, Market.USA)
- self._spy = Symbol.create("SPY", SecurityType.EQUITY, Market.USA)
-
- self.coarse_selected = { self._20140325: False, self._20140326: False, self._20140327:False, self._20140328:False }
- self.expected_symbols = { self._20140325: [ self._bac, self._qqq, self._spy ],
- self._20140326: [ self._spy ],
- self._20140327: [ self._aapl, self._bac, self._gme, self._qqq, self._spy ],
- self._20140328: [ self._goog ],
- self._20140329: []}
-
- self.set_start_date(2014, 3, 25)
- self.set_end_date(2014, 3, 29)
- self.set_cash(10000000)
- self.shortable_provider = RegressionTestShortableProvider()
- self.security = self.add_equity(self._spy)
-
- self.add_universe(self.coarse_selection)
- self.universe_settings.resolution = Resolution.DAILY
-
- self.set_brokerage_model(AllShortableSymbolsRegressionAlgorithmBrokerageModel(self.shortable_provider))
-
- def on_data(self, data):
- if self.time.date() == self.last_trade_date:
- return
-
- for (symbol, security) in {x.key: x.value for x in sorted(self.active_securities, key = lambda kvp:kvp.key)}.items():
- if security.invested:
- continue
- shortable_quantity = security.shortable_provider.shortable_quantity(symbol, self.time)
- if not shortable_quantity:
- raise Exception(f"Expected {symbol} to be shortable on {self.time.strftime('%Y%m%d')}")
-
- """
- Buy at least once into all Symbols. Since daily data will always use
- MOO orders, it makes the testing of liquidating buying into Symbols difficult.
- """
- self.market_order(symbol, -shortable_quantity)
- self.last_trade_date = self.time.date()
-
- def coarse_selection(self, coarse):
- shortable_symbols = self.shortable_provider.all_shortable_symbols(self.time)
- selected_symbols = list(sorted(filter(lambda x: (x in shortable_symbols.keys()) and (shortable_symbols[x] >= 500), map(lambda x: x.symbol, coarse)), key= lambda x: x.value))
-
- expected_missing = 0
- if self.time.date() == self._20140327.date():
- gme = Symbol.create("GME", SecurityType.EQUITY, Market.USA)
- if gme not in shortable_symbols.keys():
- raise Exception("Expected unmapped GME in shortable symbols list on 2014-03-27")
- if "GME" not in list(map(lambda x: x.symbol.value, coarse)):
- raise Exception("Expected mapped GME in coarse symbols on 2014-03-27")
-
- expected_missing = 1
-
- missing = list(filter(lambda x: x not in selected_symbols, self.expected_symbols[self.time]))
- if len(missing) != expected_missing:
- raise Exception(f"Expected Symbols selected on {self.time.strftime('%Y%m%d')} to match expected Symbols, but the following Symbols were missing: {', '.join(list(map(lambda x:x.value, missing)))}")
-
- self.coarse_selected[self.time] = True
- return selected_symbols
-
- def on_end_of_algorithm(self):
- if not all(x for x in self.coarse_selected.values()):
- raise Exception(f"Expected coarse selection on all dates, but didn't run on: {', '.join(list(map(lambda x: x.key.strftime('%Y%m%d'), filter(lambda x:not x.value, self.coarse_selected))))}")
-
-class AllShortableSymbolsRegressionAlgorithmBrokerageModel(DefaultBrokerageModel):
- def __init__(self, shortable_provider):
- self.shortable_provider = shortable_provider
- super().__init__()
-
- def get_shortable_provider(self, security):
- return self.shortable_provider
-
-class RegressionTestShortableProvider(LocalDiskShortableProvider):
- def __init__(self):
- super().__init__("testbrokerage")
-
- """
- Gets a list of all shortable Symbols, including the quantity shortable as a Dictionary.
- """
- def all_shortable_symbols(self, localtime):
- shortable_data_directory = os.path.join(Globals.DataFolder, "equity", Market.USA, "shortable", self.brokerage)
- all_symbols = {}
-
- """
- Check backwards up to one week to see if we can source a previous file.
- If not, then we return a list of all Symbols with quantity set to zero.
- """
- i = 0
- while i <= 7:
- shortable_list_file = os.path.join(shortable_data_directory, "dates", f"{(localtime - timedelta(days=i)).strftime('%Y%m%d')}.csv")
-
- for line in Extensions.read_lines(self.data_provider, shortable_list_file):
- csv = line.split(',')
- ticker = csv[0]
-
- symbol = Symbol(SecurityIdentifier.generate_equity(ticker, Market.USA, mapping_resolve_date = localtime), ticker)
- quantity = int(csv[1])
- all_symbols[symbol] = quantity
-
- if len(all_symbols) > 0:
- return all_symbols
-
- i += 1
-
- # Return our empty dictionary if we did not find a file to extract
- return all_symbols
diff --git a/fincept-qt/scripts/strategies/AsynchronousUniverseRegressionAlgorithm.py b/fincept-qt/scripts/strategies/AsynchronousUniverseRegressionAlgorithm.py
deleted file mode 100644
index 7201759b0..000000000
--- a/fincept-qt/scripts/strategies/AsynchronousUniverseRegressionAlgorithm.py
+++ /dev/null
@@ -1,22 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-F9837218
-# Category: Universe Selection
-# Description: Example algorithm using the asynchronous universe selection functionality
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-from FundamentalRegressionAlgorithm import FundamentalRegressionAlgorithm
-
-### <summary>
-### Example algorithm using the asynchronous universe selection functionality
-### </summary>
-class AsynchronousUniverseRegressionAlgorithm(FundamentalRegressionAlgorithm):
-
- def initialize(self):
- super().initialize()
- self.universe_settings.asynchronous = True
diff --git a/fincept-qt/scripts/strategies/AutoRegressiveIntegratedMovingAverageRegressionAlgorithm.py b/fincept-qt/scripts/strategies/AutoRegressiveIntegratedMovingAverageRegressionAlgorithm.py
deleted file mode 100644
index d91d60c9d..000000000
--- a/fincept-qt/scripts/strategies/AutoRegressiveIntegratedMovingAverageRegressionAlgorithm.py
+++ /dev/null
@@ -1,41 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-5FF79273
-# Category: Regression Test
-# Description: Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorith...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-# <summary>
-# Regression algorithm to test the behaviour of ARMA versus AR models at the same order of differencing.
-# In particular, an ARIMA(1,1,1) and ARIMA(1,1,0) are instantiated while orders are placed if their difference
-# is sufficiently large (which would be due to the inclusion of the MA(1) term).
-# </summary>
-class AutoRegressiveIntegratedMovingAverageRegressionAlgorithm(QCAlgorithm):
- def initialize(self):
- '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
- self.set_start_date(2013, 1, 7)
- self.set_end_date(2013, 12, 11)
- self.settings.automatic_indicator_warm_up = True
- self.add_equity("SPY", Resolution.DAILY)
- self._arima = self.arima("SPY", 1, 1, 1, 50)
- self._ar = self.arima("SPY", 1, 1, 0, 50)
-
- def on_data(self, data):
- '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
-
- Arguments:
- data: Slice object keyed by symbol containing the stock data
- '''
- if self._arima.is_ready:
- if abs(self._arima.current.value - self._ar.current.value) > 1:
- if self._arima.current.value > self.last:
- self.market_order("SPY", 1)
- else:
- self.market_order("SPY", -1)
- self.last = self._arima.current.value
diff --git a/fincept-qt/scripts/strategies/AuxiliaryDataHandlersRegressionAlgorithm.py b/fincept-qt/scripts/strategies/AuxiliaryDataHandlersRegressionAlgorithm.py
deleted file mode 100644
index 29b25de3e..000000000
--- a/fincept-qt/scripts/strategies/AuxiliaryDataHandlersRegressionAlgorithm.py
+++ /dev/null
@@ -1,55 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-C395D1D2
-# Category: Regression Test
-# Description: Example algorithm using and asserting the behavior of auxiliary data handlers
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Example algorithm using and asserting the behavior of auxiliary data handlers
-### </summary>
-class AuxiliaryDataHandlersRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self):
- '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
- self.set_start_date(2007, 5, 16)
- self.set_end_date(2015, 1, 1)
-
- self.universe_settings.resolution = Resolution.DAILY
-
- # will get delisted
- self.add_equity("AAA.1")
-
- # get's remapped
- self.add_equity("SPWR")
-
- # has a split & dividends
- self.add_equity("AAPL")
-
- def on_delistings(self, delistings: Delistings):
- self._on_delistings_called = True
-
- def on_symbol_changed_events(self, symbolsChanged: SymbolChangedEvents):
- self._on_symbol_changed_events = True
-
- def on_splits(self, splits: Splits):
- self._on_splits = True
-
- def on_dividends(self, dividends: Dividends):
- self._on_dividends = True
-
- def on_end_of_algorithm(self):
- if not self._on_delistings_called:
- raise ValueError("OnDelistings was not called!")
- if not self._on_symbol_changed_events:
- raise ValueError("OnSymbolChangedEvents was not called!")
- if not self._on_splits:
- raise ValueError("OnSplits was not called!")
- if not self._on_dividends:
- raise ValueError("OnDividends was not called!")
diff --git a/fincept-qt/scripts/strategies/BaseFrameworkRegressionAlgorithm.py b/fincept-qt/scripts/strategies/BaseFrameworkRegressionAlgorithm.py
deleted file mode 100644
index c6d06d061..000000000
--- a/fincept-qt/scripts/strategies/BaseFrameworkRegressionAlgorithm.py
+++ /dev/null
@@ -1,59 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-0A7F740C
-# Category: Regression Test
-# Description: Multi-stock equal-weight alpha strategy. Allocates equal weight
-# across AAPL, MSFT, SPY, and GOOGL when any is above its 20-day EMA.
-# Rebalances daily. Originally a framework regression test for alpha models.
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-class BaseFrameworkRegressionAlgorithm(QCAlgorithm):
- """Equal-weight multi-stock strategy with EMA trend filter."""
-
- def initialize(self):
- self.set_start_date(2023, 1, 1)
- self.set_end_date(2024, 1, 1)
- self.set_cash(100000)
-
- self.symbols = ["AAPL", "MSFT", "SPY", "GOOGL"]
- self._emas = {}
-
- for sym in self.symbols:
- self.add_equity(sym, Resolution.DAILY)
- self._emas[sym] = self.ema(sym, 20, Resolution.DAILY)
-
- self._last_rebalance_month = -1
-
- def on_data(self, data):
- # Rebalance monthly
- if self.time.month == self._last_rebalance_month:
- return
- self._last_rebalance_month = self.time.month
-
- # Check which symbols are above their EMA (uptrend)
- longs = []
- for sym in self.symbols:
- if sym not in data:
- continue
- ema = self._emas[sym]
- if not ema.is_ready:
- continue
- if data[sym].close > ema.current.value:
- longs.append(sym)
-
- # Liquidate symbols not in longs
- for sym in self.symbols:
- if sym not in longs and self.portfolio[sym].invested:
- self.liquidate(sym)
-
- # Equal-weight allocation
- if longs:
- weight = 0.95 / len(longs)
- for sym in longs:
- self.set_holdings(sym, weight)
diff --git a/fincept-qt/scripts/strategies/BasicCSharpIntegrationTemplateAlgorithm.py b/fincept-qt/scripts/strategies/BasicCSharpIntegrationTemplateAlgorithm.py
deleted file mode 100644
index cf5dee805..000000000
--- a/fincept-qt/scripts/strategies/BasicCSharpIntegrationTemplateAlgorithm.py
+++ /dev/null
@@ -1,35 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-3B2A7C04
-# Category: Template
-# Description: OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-class BasicCSharpIntegrationTemplateAlgorithm(QCAlgorithm):
-
- def initialize(self):
-
- self.set_start_date(2013,10, 7) #Set Start Date
- self.set_end_date(2013,10,11) #Set End Date
- self.set_cash(100000) #Set Strategy Cash
-
- self.add_equity("SPY", Resolution.SECOND)
-
- def on_data(self, data):
- '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
-
- Arguments:
- data: Slice object keyed by symbol containing the stock data
- '''
- if not self.portfolio.invested:
- self.set_holdings("SPY", 1)
-
- ## Calculate value of sin(10) for both python and C#
- self.debug(f'According to Python, the value of sin(10) is {np.sin(10)}')
- self.debug(f'According to C#, the value of sin(10) is {Math.sin(10)}')
diff --git a/fincept-qt/scripts/strategies/BasicSetAccountCurrencyAlgorithm.py b/fincept-qt/scripts/strategies/BasicSetAccountCurrencyAlgorithm.py
deleted file mode 100644
index 82f0372e9..000000000
--- a/fincept-qt/scripts/strategies/BasicSetAccountCurrencyAlgorithm.py
+++ /dev/null
@@ -1,31 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-07DF2AB7
-# Category: General Strategy
-# Description: Simple buy-and-hold strategy demonstrating account setup and
-# position management. Invests 100% in SPY when not invested. Originally
-# demonstrated multi-currency account configuration.
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-class BasicSetAccountCurrencyAlgorithm(QCAlgorithm):
- """Buy-and-hold strategy demonstrating account setup."""
-
- def initialize(self):
- self.set_start_date(2023, 1, 1)
- self.set_end_date(2024, 1, 1)
- self.set_cash(100000)
-
- self.symbol = "SPY"
- self.add_equity(self.symbol, Resolution.DAILY)
-
- def on_data(self, data):
- if self.symbol not in data:
- return
- if not self.portfolio.invested:
- self.set_holdings(self.symbol, 1)
diff --git a/fincept-qt/scripts/strategies/BasicSetAccountCurrencyWithAmountAlgorithm.py b/fincept-qt/scripts/strategies/BasicSetAccountCurrencyWithAmountAlgorithm.py
deleted file mode 100644
index 75c4ce306..000000000
--- a/fincept-qt/scripts/strategies/BasicSetAccountCurrencyWithAmountAlgorithm.py
+++ /dev/null
@@ -1,21 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-9A26B9BE
-# Category: General Strategy
-# Description: Basic algorithm using SetAccountCurrency with an amount
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-from BasicSetAccountCurrencyAlgorithm import BasicSetAccountCurrencyAlgorithm
-
-### <summary>
-### Basic algorithm using SetAccountCurrency with an amount
-### </summary>
-class BasicSetAccountCurrencyWithAmountAlgorithm(BasicSetAccountCurrencyAlgorithm):
- def set_account_currency_and_amount(self):
- # Before setting any cash or adding a Security call SetAccountCurrency
- self.set_account_currency("EUR", 200000)
diff --git a/fincept-qt/scripts/strategies/BasicTemplateAlgorithm.py b/fincept-qt/scripts/strategies/BasicTemplateAlgorithm.py
deleted file mode 100644
index 671f1b3c7..000000000
--- a/fincept-qt/scripts/strategies/BasicTemplateAlgorithm.py
+++ /dev/null
@@ -1,41 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-82A09B26
-# Category: Template
-# Description: Basic template algorithm simply initializes the date range and cash. This is a skeleton framework you can use for des...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Basic template algorithm simply initializes the date range and cash. This is a skeleton
-### framework you can use for designing an algorithm.
-### </summary>
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="using quantconnect" />
-### <meta name="tag" content="trading and orders" />
-class BasicTemplateAlgorithm(QCAlgorithm):
- '''Basic template algorithm simply initializes the date range and cash'''
-
- def initialize(self):
- '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
-
- self.set_start_date(2013,10, 7) #Set Start Date
- self.set_end_date(2013,10,11) #Set End Date
- self.set_cash(100000) #Set Strategy Cash
- # Fincept Terminal Strategy Engine - Symbol Configuration
- self.add_equity("SPY", Resolution.MINUTE)
- self.debug("numpy test >>> print numpy.pi: " + str(np.pi))
-
- def on_data(self, data):
- '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
-
- Arguments:
- data: Slice object keyed by symbol containing the stock data
- '''
- if not self.portfolio.invested:
- self.set_holdings("SPY", 1)
diff --git a/fincept-qt/scripts/strategies/BasicTemplateAxosAlgorithm.py b/fincept-qt/scripts/strategies/BasicTemplateAxosAlgorithm.py
deleted file mode 100644
index 052c3c0d8..000000000
--- a/fincept-qt/scripts/strategies/BasicTemplateAxosAlgorithm.py
+++ /dev/null
@@ -1,42 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-0FAA6BDF
-# Category: Template
-# Description: Basic template algorithm for the Axos brokerage
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Basic template algorithm for the Axos brokerage
-### </summary>
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="using quantconnect" />
-### <meta name="tag" content="trading and orders" />
-class BasicTemplateAxosAlgorithm(QCAlgorithm):
- '''Basic template algorithm simply initializes the date range and cash'''
-
- def initialize(self):
- '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
-
- self.set_start_date(2013,10, 7) #Set Start Date
- self.set_end_date(2013,10,11) #Set End Date
- self.set_cash(100000) #Set Strategy Cash
-
- self.set_brokerage_model(BrokerageName.AXOS)
- self.add_equity("SPY", Resolution.MINUTE)
-
- def on_data(self, data):
- '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
-
- Arguments:
- data: Slice object keyed by symbol containing the stock data
- '''
- if not self.portfolio.invested:
- # will set 25% of our buying power with a market order
- self.set_holdings("SPY", 0.25)
- self.debug("Purchased SPY!")
diff --git a/fincept-qt/scripts/strategies/BasicTemplateCfdAlgorithm.py b/fincept-qt/scripts/strategies/BasicTemplateCfdAlgorithm.py
deleted file mode 100644
index 3471a0d3e..000000000
--- a/fincept-qt/scripts/strategies/BasicTemplateCfdAlgorithm.py
+++ /dev/null
@@ -1,42 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-07CF5BDC
-# Category: Template
-# Description: Momentum strategy adapted from CFD trading template. Uses dual
-# SMA (5/20) to detect short-term momentum shifts. Buys when 5-day SMA crosses
-# above 20-day SMA, exits on crossunder.
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-class BasicTemplateCfdAlgorithm(QCAlgorithm):
- """Dual SMA momentum strategy (adapted from CFD template)."""
-
- def initialize(self):
- self.set_start_date(2023, 1, 1)
- self.set_end_date(2024, 1, 1)
- self.set_cash(100000)
-
- self.symbol = "SPY"
- self.add_equity(self.symbol, Resolution.DAILY)
-
- self._fast = self.sma(self.symbol, 5, Resolution.DAILY)
- self._slow = self.sma(self.symbol, 20, Resolution.DAILY)
-
- def on_data(self, data):
- if not self._fast.is_ready or not self._slow.is_ready:
- return
- if self.symbol not in data:
- return
-
- fast_val = self._fast.current.value
- slow_val = self._slow.current.value
-
- if not self.portfolio.invested and fast_val > slow_val:
- self.set_holdings(self.symbol, 1)
- elif self.portfolio.invested and fast_val < slow_val:
- self.liquidate()
diff --git a/fincept-qt/scripts/strategies/BasicTemplateContinuousFutureAlgorithm.py b/fincept-qt/scripts/strategies/BasicTemplateContinuousFutureAlgorithm.py
deleted file mode 100644
index 4128acd3d..000000000
--- a/fincept-qt/scripts/strategies/BasicTemplateContinuousFutureAlgorithm.py
+++ /dev/null
@@ -1,65 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-CED11838
-# Category: Futures
-# Description: Basic Continuous Futures Template Algorithm
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Basic Continuous Futures Template Algorithm
-### </summary>
-class BasicTemplateContinuousFutureAlgorithm(QCAlgorithm):
- '''Basic template algorithm simply initializes the date range and cash'''
-
- def initialize(self):
- '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
-
- self.set_start_date(2013, 7, 1)
- self.set_end_date(2014, 1, 1)
-
- self._continuous_contract = self.add_future(Futures.Indices.SP_500_E_MINI,
- data_normalization_mode = DataNormalizationMode.BACKWARDS_RATIO,
- data_mapping_mode = DataMappingMode.LAST_TRADING_DAY,
- contract_depth_offset = 0)
-
- self._fast = self.sma(self._continuous_contract.symbol, 4, Resolution.DAILY)
- self._slow = self.sma(self._continuous_contract.symbol, 10, Resolution.DAILY)
- self._current_contract = None
-
- def on_data(self, data):
- '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
-
- Arguments:
- data: Slice object keyed by symbol containing the stock data
- '''
- for changed_event in data.symbol_changed_events.values():
- if changed_event.symbol == self._continuous_contract.symbol:
- self.log(f"SymbolChanged event: {changed_event}")
-
- if not self.portfolio.invested:
- if self._fast.current.value > self._slow.current.value:
- self._current_contract = self.securities[self._continuous_contract.mapped]
- self.buy(self._current_contract.symbol, 1)
- elif self._fast.current.value < self._slow.current.value:
- self.liquidate()
-
- # We check exchange hours because the contract mapping can call OnData outside of regular hours.
- if self._current_contract is not None and self._current_contract.symbol != self._continuous_contract.mapped and self._continuous_contract.exchange.exchange_open:
- self.log(f"{self.time} - rolling position from {self._current_contract.symbol} to {self._continuous_contract.mapped}")
-
- current_position_size = self._current_contract.holdings.quantity
- self.liquidate(self._current_contract.symbol)
- self.buy(self._continuous_contract.mapped, current_position_size)
- self._current_contract = self.securities[self._continuous_contract.mapped]
-
- def on_order_event(self, order_event):
- self.debug("Purchased Stock: {0}".format(order_event.symbol))
-
- def on_securities_changed(self, changes):
- self.debug(f"{self.time}-{changes}")
diff --git a/fincept-qt/scripts/strategies/BasicTemplateContinuousFutureWithExtendedMarketAlgorithm.py b/fincept-qt/scripts/strategies/BasicTemplateContinuousFutureWithExtendedMarketAlgorithm.py
deleted file mode 100644
index c0c270b95..000000000
--- a/fincept-qt/scripts/strategies/BasicTemplateContinuousFutureWithExtendedMarketAlgorithm.py
+++ /dev/null
@@ -1,68 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-34321EAB
-# Category: Futures
-# Description: Basic Continuous Futures Template Algorithm with extended market hours
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Basic Continuous Futures Template Algorithm with extended market hours
-### </summary>
-class BasicTemplateContinuousFutureWithExtendedMarketAlgorithm(QCAlgorithm):
- '''Basic template algorithm simply initializes the date range and cash'''
-
- def initialize(self):
- '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
-
- self.set_start_date(2013, 7, 1)
- self.set_end_date(2014, 1, 1)
-
- self._continuous_contract = self.add_future(Futures.Indices.SP_500_E_MINI,
- data_normalization_mode = DataNormalizationMode.BACKWARDS_RATIO,
- data_mapping_mode = DataMappingMode.LAST_TRADING_DAY,
- contract_depth_offset = 0,
- extended_market_hours = True)
-
- self._fast = self.sma(self._continuous_contract.symbol, 4, Resolution.DAILY)
- self._slow = self.sma(self._continuous_contract.symbol, 10, Resolution.DAILY)
- self._current_contract = None
-
- def on_data(self, data):
- '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
-
- Arguments:
- data: Slice object keyed by symbol containing the stock data
- '''
- for changed_event in data.symbol_changed_events.values():
- if changed_event.symbol == self._continuous_contract.symbol:
- self.log(f"SymbolChanged event: {changed_event}")
-
- if not self.is_market_open(self._continuous_contract.symbol):
- return
-
- if not self.portfolio.invested:
- if self._fast.current.value > self._slow.current.value:
- self._current_contract = self.securities[self._continuous_contract.mapped]
- self.buy(self._current_contract.symbol, 1)
- elif self._fast.current.value < self._slow.current.value:
- self.liquidate()
-
- if self._current_contract is not None and self._current_contract.symbol != self._continuous_contract.mapped:
- self.log(f"{Time} - rolling position from {self._current_contract.symbol} to {self._continuous_contract.mapped}")
-
- current_position_size = self._current_contract.holdings.quantity
- self.liquidate(self._current_contract.symbol)
- self.buy(self._continuous_contract.mapped, current_position_size)
- self._current_contract = self.securities[self._continuous_contract.mapped]
-
- def on_order_event(self, order_event):
- self.debug("Purchased Stock: {0}".format(order_event.symbol))
-
- def on_securities_changed(self, changes):
- self.debug(f"{self.time}-{changes}")
diff --git a/fincept-qt/scripts/strategies/BasicTemplateCryptoAlgorithm.py b/fincept-qt/scripts/strategies/BasicTemplateCryptoAlgorithm.py
deleted file mode 100644
index 2c76054ec..000000000
--- a/fincept-qt/scripts/strategies/BasicTemplateCryptoAlgorithm.py
+++ /dev/null
@@ -1,147 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-C45FB406
-# Category: Crypto
-# Description: The demonstration algorithm shows some of the most common order methods when working with Crypto assets
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### The demonstration algorithm shows some of the most common order methods when working with Crypto assets.
-### </summary>
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="using quantconnect" />
-### <meta name="tag" content="trading and orders" />
-class BasicTemplateCryptoAlgorithm(QCAlgorithm):
-
- def initialize(self):
- '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
-
- self.set_start_date(2018, 4, 4) #Set Start Date
- self.set_end_date(2018, 4, 4) #Set End Date
-
- # Although typically real brokerages as GDAX only support a single account currency,
- # here we add both USD and EUR to demonstrate how to handle non-USD account currencies.
- # Set Strategy Cash (USD)
- self.set_cash(10000)
-
- # Set Strategy Cash (EUR)
- # EUR/USD conversion rate will be updated dynamically
- self.set_cash("EUR", 10000)
-
- # Add some coins as initial holdings
- # When connected to a real brokerage, the amount specified in SetCash
- # will be replaced with the amount in your actual account.
- self.set_cash("BTC", 1)
- self.set_cash("ETH", 5)
-
- self.set_brokerage_model(BrokerageName.GDAX, AccountType.CASH)
-
- # You can uncomment the following lines when live trading with GDAX,
- # to ensure limit orders will only be posted to the order book and never executed as a taker (incurring fees).
- # Please note this statement has no effect in backtesting or paper trading.
- # self.default_order_properties = GDAXOrderProperties()
- # self.default_order_properties.post_only = True
-
- # Fincept Terminal Strategy Engine - Symbol Configuration
- self.add_crypto("BTCUSD", Resolution.MINUTE)
- self.add_crypto("ETHUSD", Resolution.MINUTE)
- self.add_crypto("BTCEUR", Resolution.MINUTE)
- symbol = self.add_crypto("LTCUSD", Resolution.MINUTE).symbol
-
- # create two moving averages
- self.fast = self.ema(symbol, 30, Resolution.MINUTE)
- self.slow = self.ema(symbol, 60, Resolution.MINUTE)
-
- def on_data(self, data):
- '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
-
- Arguments:
- data: Slice object keyed by symbol containing the stock data
- '''
-
- # Note: all limit orders in this algorithm will be paying taker fees,
- # they shouldn't, but they do (for now) because of this issue:
- # https://github.com/QuantConnect/Lean/issues/1852
-
- if self.time.hour == 1 and self.time.minute == 0:
- # Sell all ETH holdings with a limit order at 1% above the current price
- limit_price = round(self.securities["ETHUSD"].price * 1.01, 2)
- quantity = self.portfolio.cash_book["ETH"].amount
- self.limit_order("ETHUSD", -quantity, limit_price)
-
- elif self.time.hour == 2 and self.time.minute == 0:
- # Submit a buy limit order for BTC at 5% below the current price
- usd_total = self.portfolio.cash_book["USD"].amount
- limit_price = round(self.securities["BTCUSD"].price * 0.95, 2)
- # use only half of our total USD
- quantity = usd_total * 0.5 / limit_price
- self.limit_order("BTCUSD", quantity, limit_price)
-
- elif self.time.hour == 2 and self.time.minute == 1:
- # Get current USD available, subtracting amount reserved for buy open orders
- usd_total = self.portfolio.cash_book["USD"].amount
- usd_reserved = sum(x.quantity * x.limit_price for x
- in [x for x in self.transactions.get_open_orders()
- if x.direction == OrderDirection.BUY
- and x.type == OrderType.LIMIT
- and (x.symbol.value == "BTCUSD" or x.symbol.value == "ETHUSD")])
- usd_available = usd_total - usd_reserved
- self.debug("usd_available: {}".format(usd_available))
-
- # Submit a marketable buy limit order for ETH at 1% above the current price
- limit_price = round(self.securities["ETHUSD"].price * 1.01, 2)
-
- # use all of our available USD
- quantity = usd_available / limit_price
-
- # this order will be rejected (for now) because of this issue:
- # https://github.com/QuantConnect/Lean/issues/1852
- self.limit_order("ETHUSD", quantity, limit_price)
-
- # use only half of our available USD
- quantity = usd_available * 0.5 / limit_price
- self.limit_order("ETHUSD", quantity, limit_price)
-
- elif self.time.hour == 11 and self.time.minute == 0:
- # Liquidate our BTC holdings (including the initial holding)
- self.set_holdings("BTCUSD", 0)
-
- elif self.time.hour == 12 and self.time.minute == 0:
- # Submit a market buy order for 1 BTC using EUR
- self.buy("BTCEUR", 1)
-
- # Submit a sell limit order at 10% above market price
- limit_price = round(self.securities["BTCEUR"].price * 1.1, 2)
- self.limit_order("BTCEUR", -1, limit_price)
-
- elif self.time.hour == 13 and self.time.minute == 0:
- # Cancel the limit order if not filled
- self.transactions.cancel_open_orders("BTCEUR")
-
- elif self.time.hour > 13:
- # To include any initial holdings, we read the LTC amount from the cashbook
- # instead of using Portfolio["LTCUSD"].quantity
-
- if self.fast > self.slow:
- if self.portfolio.cash_book["LTC"].amount == 0:
- self.buy("LTCUSD", 10)
- else:
- if self.portfolio.cash_book["LTC"].amount > 0:
- # The following two statements currently behave differently if we have initial holdings:
- # https://github.com/QuantConnect/Lean/issues/1860
-
- self.liquidate("LTCUSD")
- # self.set_holdings("LTCUSD", 0)
-
- def on_order_event(self, order_event):
- self.debug("{} {}".format(self.time, order_event.to_string()))
-
- def on_end_of_algorithm(self):
- self.log("{} - TotalPortfolioValue: {}".format(self.time, self.portfolio.total_portfolio_value))
- self.log("{} - CashBook: {}".format(self.time, self.portfolio.cash_book))
diff --git a/fincept-qt/scripts/strategies/BasicTemplateCryptoFutureAlgorithm.py b/fincept-qt/scripts/strategies/BasicTemplateCryptoFutureAlgorithm.py
deleted file mode 100644
index 10e33a40f..000000000
--- a/fincept-qt/scripts/strategies/BasicTemplateCryptoFutureAlgorithm.py
+++ /dev/null
@@ -1,144 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-F09974A0
-# Category: Futures
-# Description: Minute resolution regression algorithm trading Coin and USDT binance futures long and short asserting the behavior
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Minute resolution regression algorithm trading Coin and USDT binance futures long and short asserting the behavior
-### </summary>
-class BasicTemplateCryptoFutureAlgorithm(QCAlgorithm):
- # <summary>
- # Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
- # </summary>
-
- def initialize(self):
- self.set_start_date(2022, 12, 13)
- self.set_end_date(2022, 12, 13)
-
- self.set_time_zone(TimeZones.UTC)
-
- try:
- self.set_brokerage_model(BrokerageName.BINANCE_FUTURES, AccountType.CASH)
- except:
- # expected, we don't allow cash account type
- pass
-
- self.set_brokerage_model(BrokerageName.BINANCE_FUTURES, AccountType.MARGIN)
-
- self.btc_usd = self.add_crypto_future("BTCUSD")
- self.ada_usdt = self.add_crypto_future("ADAUSDT")
-
- self.fast = self.ema(self.btc_usd.symbol, 30, Resolution.MINUTE)
- self.slow = self.ema(self.btc_usd.symbol, 60, Resolution.MINUTE)
-
- self.interest_per_symbol = {self.btc_usd.symbol: 0, self.ada_usdt.symbol: 0}
-
- self.set_cash(1000000)
-
- # the amount of BTC we need to hold to trade 'BTCUSD'
- self.btc_usd.base_currency.set_amount(0.005)
- # the amount of USDT we need to hold to trade 'ADAUSDT'
- self.ada_usdt.quote_currency.set_amount(200)
-
- # <summary>
- # OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
- # </summary>
- # <param name="data">Slice object keyed by symbol containing the stock data</param>
- def on_data(self, slice):
- interest_rates = slice.Get(MarginInterestRate)
- for interest_rate in interest_rates:
- self.interest_per_symbol[interest_rate.key] += 1
- self.cached_interest_rate = self.securities[interest_rate.key].cache.get_data[MarginInterestRate]()
- if self.cached_interest_rate != interest_rate.value:
- raise Exception(f"Unexpected cached margin interest rate for {interest_rate.key}!")
-
- if self.fast > self.slow:
- if self.portfolio.invested == False and self.transactions.orders_count == 0:
- self.ticket = self.buy(self.btc_usd.symbol, 50)
- if self.ticket.status != OrderStatus.INVALID:
- raise Exception(f"Unexpected valid order {self.ticket}, should fail due to margin not sufficient")
-
- self.buy(self.btc_usd.symbol, 1)
-
- self.margin_used = self.portfolio.total_margin_used
- self.btc_usd_holdings = self.btc_usd.holdings
- # Coin futures value is 100 USD
- self.holdings_value_btc_usd = 100
-
- if abs(self.btc_usd_holdings.total_sale_volume - self.holdings_value_btc_usd) > 1:
- raise Exception(f"Unexpected TotalSaleVolume {self.btc_usd_holdings.total_sale_volume}")
-
- if abs(self.btc_usd_holdings.absolute_holdings_cost - self.holdings_value_btc_usd) > 1:
- raise Exception(f"Unexpected holdings cost {self.btc_usd_holdings.holdings_cost}")
-
- # margin used is based on the maintenance rate
- if (abs(self.btc_usd_holdings.absolute_holdings_cost * 0.05 - self.margin_used) > 1) or (BuyingPowerModelExtensions.get_maintenance_margin(self.btc_usd.buying_power_model, self.btc_usd) != self.margin_used):
- raise Exception(f"Unexpected margin used {self.margin_used}")
-
- self.buy(self.ada_usdt.symbol, 1000)
-
- self.margin_used = self.portfolio.total_margin_used - self.margin_used
- self.ada_usdt_holdings = self.ada_usdt.holdings
-
- # USDT/BUSD futures value is based on it's price
- self.holdings_value_usdt = self.ada_usdt.price * self.ada_usdt.symbol_properties.contract_multiplier * 1000
-
- if abs(self.ada_usdt_holdings.total_sale_volume - self.holdings_value_usdt) > 1:
- raise Exception(f"Unexpected TotalSaleVolume {self.ada_usdt_holdings.total_sale_volume}")
-
- if abs(self.ada_usdt_holdings.absolute_holdings_cost - self.holdings_value_usdt) > 1:
- raise Exception(f"Unexpected holdings cost {self.ada_usdt_holdings.holdings_cost}")
-
- if (abs(self.ada_usdt_holdings.absolute_holdings_cost * 0.05 - self.margin_used) > 1) or (BuyingPowerModelExtensions.get_maintenance_margin(self.ada_usdt.buying_power_model, self.ada_usdt) != self.margin_used):
- raise Exception(f"Unexpected margin used {self.margin_used}")
-
- # position just opened should be just spread here
- self.profit = self.portfolio.total_unrealized_profit
-
- if (5 - abs(self.profit)) < 0:
- raise Exception(f"Unexpected TotalUnrealizedProfit {self.portfolio.total_unrealized_profit}")
-
- if (self.portfolio.total_profit != 0):
- raise Exception(f"Unexpected TotalProfit {self.portfolio.total_profit}")
-
- else:
- if self.time.hour > 10 and self.transactions.orders_count == 3:
- self.sell(self.btc_usd.symbol, 3)
- self.btc_usd_holdings = self.btc_usd.holdings
- if abs(self.btc_usd_holdings.absolute_holdings_cost - 100 * 2) > 1:
- raise Exception(f"Unexpected holdings cost {self.btc_usd_holdings.holdings_cost}")
-
- self.sell(self.ada_usdt.symbol, 3000)
- ada_usdt_holdings = self.ada_usdt.holdings
-
- # USDT/BUSD futures value is based on it's price
- holdings_value_usdt = self.ada_usdt.price * self.ada_usdt.symbol_properties.contract_multiplier * 2000
-
- if abs(ada_usdt_holdings.absolute_holdings_cost - holdings_value_usdt) > 1:
- raise Exception(f"Unexpected holdings cost {ada_usdt_holdings.holdings_cost}")
-
- # position just opened should be just spread here
- profit = self.portfolio.total_unrealized_profit
- if (5 - abs(profit)) < 0:
- raise Exception(f"Unexpected TotalUnrealizedProfit {self.portfolio.total_unrealized_profit}")
- # we barely did any difference on the previous trade
- if (5 - abs(self.portfolio.total_profit)) < 0:
- raise Exception(f"Unexpected TotalProfit {self.portfolio.total_profit}")
-
-
- def on_end_of_algorithm(self):
- if self.interest_per_symbol[self.ada_usdt.symbol] != 1:
- raise Exception(f"Unexpected interest rate count {self.interest_per_symbol[self.ada_usdt.symbol]}")
- if self.interest_per_symbol[self.btc_usd.symbol] != 3:
- raise Exception(f"Unexpected interest rate count {self.interest_per_symbol[self.btc_usd.symbol]}")
-
- def on_order_event(self, order_event):
- self.debug("{0} {1}".format(self.time, order_event))
diff --git a/fincept-qt/scripts/strategies/BasicTemplateCryptoFutureHourlyAlgorithm.py b/fincept-qt/scripts/strategies/BasicTemplateCryptoFutureHourlyAlgorithm.py
deleted file mode 100644
index 291e454e8..000000000
--- a/fincept-qt/scripts/strategies/BasicTemplateCryptoFutureHourlyAlgorithm.py
+++ /dev/null
@@ -1,124 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-E96624E8
-# Category: Futures
-# Description: Hourly regression algorithm trading ADAUSDT binance futures long and short asserting the behavior
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Hourly regression algorithm trading ADAUSDT binance futures long and short asserting the behavior
-### </summary>
-class BasicTemplateCryptoFutureHourlyAlgorithm(QCAlgorithm):
- # <summary>
- # Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
- # </summary>
-
- def initialize(self):
- self.set_start_date(2022, 12, 13)
- self.set_end_date(2022, 12, 13)
-
- self.set_time_zone(TimeZones.UTC)
-
- try:
- self.set_brokerage_model(BrokerageName.BINANCE_COIN_FUTURES, AccountType.CASH)
- except:
- # expected, we don't allow cash account type
- pass
-
- self.set_brokerage_model(BrokerageName.BINANCE_COIN_FUTURES, AccountType.MARGIN)
-
- self.ada_usdt = self.add_crypto_future("ADAUSDT", Resolution.HOUR)
-
- self.fast = self.ema(self.ada_usdt.symbol, 3, Resolution.HOUR)
- self.slow = self.ema(self.ada_usdt.symbol, 6, Resolution.HOUR)
-
- self.interest_per_symbol = {self.ada_usdt.symbol: 0}
-
- # Default USD cash, set 1M but it wont be used
- self.set_cash(1000000)
-
- # the amount of USDT we need to hold to trade 'ADAUSDT'
- self.ada_usdt.quote_currency.set_amount(200)
-
- # <summary>
- # OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
- # </summary>
- # <param name="data">Slice object keyed by symbol containing the stock data</param>
- def on_data(self, slice):
- interest_rates = slice.get(MarginInterestRate);
- for interest_rate in interest_rates:
- self.interest_per_symbol[interest_rate.key] += 1
- self.cached_interest_rate = self.securities[interest_rate.key].cache.get_data[MarginInterestRate]()
- if self.cached_interest_rate != interest_rate.value:
- raise Exception(f"Unexpected cached margin interest rate for {interest_rate.key}!")
-
- if self.fast > self.slow:
- if self.portfolio.invested == False and self.transactions.orders_count == 0:
- self.ticket = self.buy(self.ada_usdt.symbol, 100000)
- if self.ticket.status != OrderStatus.INVALID:
- raise Exception(f"Unexpected valid order {self.ticket}, should fail due to margin not sufficient")
-
- self.buy(self.ada_usdt.symbol, 1000)
-
- self.margin_used = self.portfolio.total_margin_used
-
- self.ada_usdt_holdings = self.ada_usdt.holdings
-
- # USDT/BUSD futures value is based on it's price
- self.holdings_value_usdt = self.ada_usdt.price * self.ada_usdt.symbol_properties.contract_multiplier * 1000
-
- if abs(self.ada_usdt_holdings.total_sale_volume - self.holdings_value_usdt) > 1:
- raise Exception(f"Unexpected TotalSaleVolume {self.ada_usdt_holdings.total_sale_volume}")
-
- if abs(self.ada_usdt_holdings.absolute_holdings_cost - self.holdings_value_usdt) > 1:
- raise Exception(f"Unexpected holdings cost {self.ada_usdt_holdings.holdings_cost}")
-
- if (abs(self.ada_usdt_holdings.absolute_holdings_cost * 0.05 - self.margin_used) > 1) or (BuyingPowerModelExtensions.get_maintenance_margin(self.ada_usdt.buying_power_model, self.ada_usdt) != self.margin_used):
- raise Exception(f"Unexpected margin used {self.margin_used}")
-
- # position just opened should be just spread here
- self.profit = self.portfolio.total_unrealized_profit
-
- if (5 - abs(self.profit)) < 0:
- raise Exception(f"Unexpected TotalUnrealizedProfit {self.portfolio.total_unrealized_profit}")
-
- if (self.portfolio.total_profit != 0):
- raise Exception(f"Unexpected TotalProfit {self.portfolio.total_profit}")
-
- else:
- # let's revert our position and double
- if self.time.hour > 10 and self.transactions.orders_count == 2:
- self.sell(self.ada_usdt.symbol, 3000)
-
- self.ada_usdt_holdings = self.ada_usdt.holdings
-
- # USDT/BUSD futures value is based on it's price
- self.holdings_value_usdt = self.ada_usdt.price * self.ada_usdt.symbol_properties.contract_multiplier * 2000
-
- if abs(self.ada_usdt_holdings.absolute_holdings_cost - self.holdings_value_usdt) > 1:
- raise Exception(f"Unexpected holdings cost {self.ada_usdt_holdings.holdings_cost}")
-
- # position just opened should be just spread here
- self.profit = self.portfolio.total_unrealized_profit
- if (5 - abs(self.profit)) < 0:
- raise Exception(f"Unexpected TotalUnrealizedProfit {self.portfolio.total_unrealized_profit}")
-
- # we barely did any difference on the previous trade
- if (5 - abs(self.portfolio.total_profit)) < 0:
- raise Exception(f"Unexpected TotalProfit {self.portfolio.total_profit}")
-
- if self.time.hour >= 22 and self.transactions.orders_count == 3:
- self.liquidate()
-
- def on_end_of_algorithm(self):
- if self.interest_per_symbol[self.ada_usdt.symbol] != 1:
- raise Exception(f"Unexpected interest rate count {self.interest_per_symbol[self.ada_usdt.symbol]}")
-
- def on_order_event(self, order_event):
- self.debug("{0} {1}".format(self.time, order_event))
diff --git a/fincept-qt/scripts/strategies/BasicTemplateDailyAlgorithm.py b/fincept-qt/scripts/strategies/BasicTemplateDailyAlgorithm.py
deleted file mode 100644
index 52bac7cb3..000000000
--- a/fincept-qt/scripts/strategies/BasicTemplateDailyAlgorithm.py
+++ /dev/null
@@ -1,40 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-1ADBAC8E
-# Category: Template
-# Description: Demonstration of requesting daily resolution data for US Equities. This is a simple regression test algorithm using a...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Demonstration of requesting daily resolution data for US Equities.
-### This is a simple regression test algorithm using a skeleton algorithm and requesting daily data.
-### </summary>
-### <meta name="tag" content="using data" />
-class BasicTemplateDailyAlgorithm(QCAlgorithm):
- '''Basic template algorithm simply initializes the date range and cash'''
-
- def initialize(self):
- '''initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
-
- self.set_start_date(2013,10,8) #Set Start Date
- self.set_end_date(2013,10,17) #Set End Date
- self.set_cash(100000) #Set Strategy Cash
- # Fincept Terminal Strategy Engine - Symbol Configuration
- self.add_equity("SPY", Resolution.DAILY)
-
-
- def on_data(self, data):
- '''on_data event is the primary entry point for your algorithm. Each new data point will be pumped in here.
-
- Arguments:
- data: Slice object keyed by symbol containing the stock data
- '''
- if not self.portfolio.invested:
- self.set_holdings("SPY", 1)
- self.debug("Purchased Stock")
diff --git a/fincept-qt/scripts/strategies/BasicTemplateEurexFuturesAlgorithm.py b/fincept-qt/scripts/strategies/BasicTemplateEurexFuturesAlgorithm.py
deleted file mode 100644
index 2716862f9..000000000
--- a/fincept-qt/scripts/strategies/BasicTemplateEurexFuturesAlgorithm.py
+++ /dev/null
@@ -1,118 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-59CC070D
-# Category: Futures
-# Description: This algorithm tests and demonstrates EUREX futures subscription and trading: - It tests contracts rollover by adding...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### This algorithm tests and demonstrates EUREX futures subscription and trading:
-### - It tests contracts rollover by adding a continuous future and asserting that mapping happens at some point.
-### - It tests basic trading by buying a contract and holding it until expiration.
-### - It tests delisting and asserts the holdings are liquidated after that.
-### </summary>
-class BasicTemplateEurexFuturesAlgorithm(QCAlgorithm):
- def __init__(self):
- super().__init__()
- self._continuous_contract = None
- self._mapped_symbol = None
- self._contract_to_trade = None
- self._mappings_count = 0
- self._bought_quantity = 0
- self._liquidated_quantity = 0
- self._delisted = False
-
- def initialize(self):
- self.set_start_date(2024, 5, 30)
- self.set_end_date(2024, 6, 23)
-
- self.set_account_currency(Currencies.EUR);
- self.set_cash(1000000)
-
- self._continuous_contract = self.add_future(
- Futures.Indices.EURO_STOXX_50,
- Resolution.MINUTE,
- data_normalization_mode=DataNormalizationMode.BACKWARDS_RATIO,
- data_mapping_mode=DataMappingMode.FIRST_DAY_MONTH,
- contract_depth_offset=0,
- )
- self._continuous_contract.set_filter(timedelta(days=0), timedelta(days=180))
- self._mapped_symbol = self._continuous_contract.mapped
-
- benchmark = self.add_index("SX5E", market=Market.EUREX)
- self.set_benchmark(benchmark.symbol)
-
- func_seeder = FuncSecuritySeeder(self.get_last_known_prices)
- self.set_security_initializer(lambda security: func_seeder.seed_security(security))
-
- def on_data(self, slice):
- for changed_event in slice.symbol_changed_events.values():
- self._mappings_count += 1
- if self._mappings_count > 1:
- raise Exception(f"{self.time} - Unexpected number of symbol changed events (mappings): {self._mappings_count}. Expected only 1.")
-
- self.debug(f"{self.time} - SymbolChanged event: {changed_event}")
-
- if changed_event.old_symbol != str(self._mapped_symbol.id):
- raise Exception(f"{self.time} - Unexpected symbol changed event old symbol: {changed_event}")
-
- if changed_event.new_symbol != str(self._continuous_contract.mapped.id):
- raise Exception(f"{self.time} - Unexpected symbol changed event new symbol: {changed_event}")
-
- # Let's trade the previous mapped contract, so we can hold it until expiration for testing
- # (will be sooner than the new mapped contract)
- self._contract_to_trade = self._mapped_symbol
- self._mapped_symbol = self._continuous_contract.mapped
-
- # Let's trade after the mapping is done
- if self._contract_to_trade is not None and self._bought_quantity == 0 and self.securities[self._contract_to_trade].exchange.exchange_open:
- self.buy(self._contract_to_trade, 1)
-
- if self._contract_to_trade is not None and slice.delistings.contains_key(self._contract_to_trade):
- delisting = slice.delistings[self._contract_to_trade]
- if delisting.type == DelistingType.DELISTED:
- self._delisted = True
-
- if self.portfolio.invested:
- raise Exception(f"{self.time} - Portfolio should not be invested after the traded contract is delisted.")
-
- def on_order_event(self, order_event):
- if order_event.symbol != self._contract_to_trade:
- raise Exception(f"{self.time} - Unexpected order event symbol: {order_event.symbol}. Expected {self._contract_to_trade}")
-
- if order_event.direction == OrderDirection.BUY:
- if order_event.status == OrderStatus.FILLED:
- if self._bought_quantity != 0 and self._liquidated_quantity != 0:
- raise Exception(f"{self.time} - Unexpected buy order event status: {order_event.status}")
-
- self._bought_quantity = order_event.quantity
- elif order_event.direction == OrderDirection.SELL:
- if order_event.status == OrderStatus.FILLED:
- if self._bought_quantity <= 0 and self._liquidated_quantity != 0:
- raise Exception(f"{self.time} - Unexpected sell order event status: {order_event.status}")
-
- self._liquidated_quantity = order_event.quantity
- if self._liquidated_quantity != -self._bought_quantity:
- raise Exception(f"{self.time} - Unexpected liquidated quantity: {self._liquidated_quantity}. Expected: {-self._bought_quantity}")
-
- def on_securities_changed(self, changes):
- for added_security in changes.added_securities:
- if added_security.symbol.security_type == SecurityType.FUTURE and added_security.symbol.is_canonical():
- self._mapped_symbol = self._continuous_contract.mapped
-
- def on_end_of_algorithm(self):
- if self._mappings_count == 0:
- raise Exception(f"Unexpected number of symbol changed events (mappings): {self._mappings_count}. Expected 1.")
-
- if not self._delisted:
- raise Exception("Contract was not delisted")
-
- # Make sure we traded and that the position was liquidated on delisting
- if self._bought_quantity <= 0 or self._liquidated_quantity >= 0:
- raise Exception(f"Unexpected sold quantity: {self._bought_quantity} and liquidated quantity: {self._liquidated_quantity}")
diff --git a/fincept-qt/scripts/strategies/BasicTemplateFillForwardAlgorithm.py b/fincept-qt/scripts/strategies/BasicTemplateFillForwardAlgorithm.py
deleted file mode 100644
index 4a951e324..000000000
--- a/fincept-qt/scripts/strategies/BasicTemplateFillForwardAlgorithm.py
+++ /dev/null
@@ -1,33 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-D7F55E8F
-# Category: Template
-# Description: Basic template algorithm simply initializes the date range and cash
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-class BasicTemplateFillForwardAlgorithm(QCAlgorithm):
- '''Basic template algorithm simply initializes the date range and cash'''
-
- def initialize(self):
- '''initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
-
- self.set_start_date(2013,10,7) #Set Start Date
- self.set_end_date(2013,11,30) #Set End Date
- self.set_cash(100000) #Set Strategy Cash
- # Fincept Terminal Strategy Engine - Symbol Configuration
- self.add_security(SecurityType.EQUITY, "ASUR", Resolution.SECOND)
-
- def on_data(self, data):
- '''on_data event is the primary entry point for your algorithm. Each new data point will be pumped in here.
-
- Arguments:
- data: Slice object keyed by symbol containing the stock data
- '''
- if not self.portfolio.invested:
- self.set_holdings("ASUR", 1)
diff --git a/fincept-qt/scripts/strategies/BasicTemplateForexAlgorithm.py b/fincept-qt/scripts/strategies/BasicTemplateForexAlgorithm.py
deleted file mode 100644
index 0ee1c1372..000000000
--- a/fincept-qt/scripts/strategies/BasicTemplateForexAlgorithm.py
+++ /dev/null
@@ -1,51 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-DBF9152F
-# Category: Forex
-# Description: Algorithm demonstrating FOREX asset types and requesting history on them in bulk. As FOREX uses QuoteBars you should ...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Algorithm demonstrating FOREX asset types and requesting history on them in bulk. As FOREX uses
-### QuoteBars you should request slices
-### </summary>
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="history and warm up" />
-### <meta name="tag" content="history" />
-### <meta name="tag" content="forex" />
-class BasicTemplateForexAlgorithm(QCAlgorithm):
-
- def initialize(self):
- # Set the cash we'd like to use for our backtest
- self.set_cash(100000)
-
- # Start and end dates for the backtest.
- self.set_start_date(2013, 10, 7)
- self.set_end_date(2013, 10, 11)
-
- # Add FOREX contract you want to trade
- # find available contracts here https://www.quantconnect.com/data#forex/oanda/cfd
- self.add_forex("EURUSD", Resolution.MINUTE)
- self.add_forex("GBPUSD", Resolution.MINUTE)
- self.add_forex("EURGBP", Resolution.MINUTE)
-
- self.history(5, Resolution.DAILY)
- self.history(5, Resolution.HOUR)
- self.history(5, Resolution.MINUTE)
-
- history = self.history(TimeSpan.from_seconds(5), Resolution.SECOND)
-
- for data in sorted(history, key=lambda x: x.time):
- for key in data.keys():
- self.log(str(key.value) + ": " + str(data.time) + " > " + str(data[key].value))
-
- def on_data(self, data):
- # Print to console to verify that data is coming in
- for key in data.keys():
- self.log(str(key.value) + ": " + str(data.time) + " > " + str(data[key].value))
diff --git a/fincept-qt/scripts/strategies/BasicTemplateFrameworkAlgorithm.py b/fincept-qt/scripts/strategies/BasicTemplateFrameworkAlgorithm.py
deleted file mode 100644
index 9381732b1..000000000
--- a/fincept-qt/scripts/strategies/BasicTemplateFrameworkAlgorithm.py
+++ /dev/null
@@ -1,58 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-EE88AED1
-# Category: Template
-# Description: Basic template framework algorithm uses framework components to define the algorithm
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Basic template framework algorithm uses framework components to define the algorithm.
-### </summary>
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="using quantconnect" />
-### <meta name="tag" content="trading and orders" />
-class BasicTemplateFrameworkAlgorithm(QCAlgorithm):
- '''Basic template framework algorithm uses framework components to define the algorithm.'''
-
- def initialize(self):
- '''initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
-
- # Set requested data resolution
- self.universe_settings.resolution = Resolution.MINUTE
-
- self.set_start_date(2013,10,7) #Set Start Date
- self.set_end_date(2013,10,11) #Set End Date
- self.set_cash(100000) #Set Strategy Cash
-
- # Fincept Terminal Strategy Engine - Symbol Configuration
- # Forex, CFD, Equities Resolutions: Tick, Second, Minute, Hour, Daily.
- # Futures Resolution: Tick, Second, Minute
- # Options Resolution: Minute Only.
- symbols = [ Symbol.create("SPY", SecurityType.EQUITY, Market.USA) ]
-
- # set algorithm framework models
- self.set_universe_selection(ManualUniverseSelectionModel(symbols))
- self.set_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(minutes = 20), 0.025, None))
-
- # We can define how often the EWPCM will rebalance if no new insight is submitted using:
- # Resolution Enum:
- self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel(Resolution.DAILY))
- # timedelta
- # self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel(timedelta(2)))
- # A lamdda datetime -> datetime. In this case, we can use the pre-defined func at Expiry helper class
- # self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel(Expiry.END_OF_WEEK))
-
- self.set_execution(ImmediateExecutionModel())
- self.set_risk_management(MaximumDrawdownPercentPerSecurity(0.01))
-
- self.debug("numpy test >>> print numpy.pi: " + str(np.pi))
-
- def on_order_event(self, order_event):
- if order_event.status == OrderStatus.FILLED:
- self.debug("Purchased Stock: {0}".format(order_event.symbol))
diff --git a/fincept-qt/scripts/strategies/BasicTemplateFutureOptionAlgorithm.py b/fincept-qt/scripts/strategies/BasicTemplateFutureOptionAlgorithm.py
deleted file mode 100644
index b37b1ac51..000000000
--- a/fincept-qt/scripts/strategies/BasicTemplateFutureOptionAlgorithm.py
+++ /dev/null
@@ -1,69 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-2426C5B7
-# Category: Options
-# Description: The demonstration algorithm shows some of the most common order methods when working with FutureOption assets
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### The demonstration algorithm shows some of the most common order methods when working with FutureOption assets.
-### </summary>
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="using quantconnect" />
-### <meta name="tag" content="trading and orders" />
-
-class BasicTemplateFutureOptionAlgorithm(QCAlgorithm):
-
- def initialize(self):
- '''initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
- self.set_start_date(2022, 1, 1)
- self.set_end_date(2022, 2, 1)
- self.set_cash(100000)
-
- gold_futures = self.add_future(Futures.Metals.GOLD, Resolution.MINUTE)
- gold_futures.set_filter(0, 180)
- self._symbol = gold_futures.symbol
- self.add_future_option(self._symbol, lambda universe: universe.strikes(-5, +5)
- .calls_only()
- .back_month()
- .only_apply_filter_at_market_open())
-
- # Historical Data
- history = self.history(self._symbol, 60, Resolution.DAILY)
- self.log(f"Received {len(history)} bars from {self._symbol} FutureOption historical data call.")
-
- def on_data(self, data):
- '''on_data event is the primary entry point for your algorithm. Each new data point will be pumped in here.
- Arguments:
- slice: Slice object keyed by symbol containing the stock data
- '''
- # Access Data
- for kvp in data.option_chains:
- underlying_future_contract = kvp.key.underlying
- chain = kvp.value
-
- if not chain: continue
-
- for contract in chain:
- self.log(f"""Canonical Symbol: {kvp.key};
- Contract: {contract};
- Right: {contract.right};
- Expiry: {contract.expiry};
- Bid price: {contract.bid_price};
- Ask price: {contract.ask_price};
- Implied Volatility: {contract.implied_volatility}""")
-
- if not self.portfolio.invested:
- atm_strike = sorted(chain, key = lambda x: abs(chain.underlying.price - x.strike))[0].strike
- selected_contract = sorted([contract for contract in chain if contract.strike == atm_strike], \
- key = lambda x: x.expiry, reverse=True)[0]
- self.market_order(selected_contract.symbol, 1)
-
- def on_order_event(self, order_event):
- self.debug("{} {}".format(self.time, order_event.to_string()))
diff --git a/fincept-qt/scripts/strategies/BasicTemplateFutureRolloverAlgorithm.py b/fincept-qt/scripts/strategies/BasicTemplateFutureRolloverAlgorithm.py
deleted file mode 100644
index 2a740961b..000000000
--- a/fincept-qt/scripts/strategies/BasicTemplateFutureRolloverAlgorithm.py
+++ /dev/null
@@ -1,127 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-1DD3D3FC
-# Category: Futures
-# Description: Example algorithm for trading continuous future
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Example algorithm for trading continuous future
-### </summary>
-class BasicTemplateFutureRolloverAlgorithm(QCAlgorithm):
-
- ### <summary>
- ### Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
- ### </summary>
- def initialize(self):
- self.set_start_date(2013, 10, 8)
- self.set_end_date(2013, 12, 10)
- self.set_cash(1000000)
-
- self._symbol_data_by_symbol = {}
-
- futures = [
- Futures.Indices.SP_500_E_MINI
- ]
-
- for future in futures:
- # Requesting data
- continuous_contract = self.add_future(future,
- resolution = Resolution.DAILY,
- extended_market_hours = True,
- data_normalization_mode = DataNormalizationMode.BACKWARDS_RATIO,
- data_mapping_mode = DataMappingMode.OPEN_INTEREST,
- contract_depth_offset = 0
- )
-
- symbol_data = SymbolData(self, continuous_contract)
- self._symbol_data_by_symbol[continuous_contract.symbol] = symbol_data
-
- ### <summary>
- ### on_data event is the primary entry point for your algorithm. Each new data point will be pumped in here.
- ### </summary>
- ### <param name="slice">Slice object keyed by symbol containing the stock data</param>
- def on_data(self, slice):
- for symbol, symbol_data in self._symbol_data_by_symbol.items():
- # Call SymbolData.update() method to handle new data slice received
- symbol_data.update(slice)
-
- # Check if information in SymbolData class and new slice data are ready for trading
- if not symbol_data.is_ready or not slice.bars.contains_key(symbol):
- return
-
- ema_current_value = symbol_data.EMA.current.value
- if ema_current_value < symbol_data.price and not symbol_data.is_long:
- self.market_order(symbol_data.mapped, 1)
- elif ema_current_value > symbol_data.price and not symbol_data.is_short:
- self.market_order(symbol_data.mapped, -1)
-
-### <summary>
-### Abstracted class object to hold information (state, indicators, methods, etc.) from a Symbol/Security in a multi-security algorithm
-### </summary>
-class SymbolData:
-
- ### <summary>
- ### Constructor to instantiate the information needed to be hold
- ### </summary>
- def __init__(self, algorithm, future):
- self._algorithm = algorithm
- self._future = future
- self.EMA = algorithm.ema(future.symbol, 20, Resolution.DAILY)
- self.price = 0
- self.is_long = False
- self.is_short = False
-
- self.reset()
-
- @property
- def symbol(self):
- return self._future.symbol
-
- @property
- def mapped(self):
- return self._future.mapped
-
- @property
- def is_ready(self):
- return self.mapped is not None and self.EMA.is_ready
-
- ### <summary>
- ### Handler of new slice of data received
- ### </summary>
- def update(self, slice):
- if slice.symbol_changed_events.contains_key(self.symbol):
- changed_event = slice.symbol_changed_events[self.symbol]
- old_symbol = changed_event.old_symbol
- new_symbol = changed_event.new_symbol
- tag = f"Rollover - Symbol changed at {self._algorithm.time}: {old_symbol} -> {new_symbol}"
- quantity = self._algorithm.portfolio[old_symbol].quantity
-
- # Rolling over: to liquidate any position of the old mapped contract and switch to the newly mapped contract
- self._algorithm.liquidate(old_symbol, tag = tag)
- self._algorithm.market_order(new_symbol, quantity, tag = tag)
-
- self.reset()
-
- self.price = slice.bars[self.symbol].price if slice.bars.contains_key(self.symbol) else self.price
- self.is_long = self._algorithm.portfolio[self.mapped].is_long
- self.is_short = self._algorithm.portfolio[self.mapped].is_short
-
- ### <summary>
- ### reset RollingWindow/indicator to adapt to newly mapped contract, then warm up the RollingWindow/indicator
- ### </summary>
- def reset(self):
- self.EMA.reset()
- self._algorithm.warm_up_indicator(self.symbol, self.EMA, Resolution.DAILY)
-
- ### <summary>
- ### disposal method to remove consolidator/update method handler, and reset RollingWindow/indicator to free up memory and speed
- ### </summary>
- def dispose(self):
- self.EMA.reset()
diff --git a/fincept-qt/scripts/strategies/BasicTemplateFuturesAlgorithm.py b/fincept-qt/scripts/strategies/BasicTemplateFuturesAlgorithm.py
deleted file mode 100644
index 238e157ac..000000000
--- a/fincept-qt/scripts/strategies/BasicTemplateFuturesAlgorithm.py
+++ /dev/null
@@ -1,77 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-D9822D5B
-# Category: Futures
-# Description: This example demonstrates how to add futures for a given underlying asset. It also shows how you can prefilter contra...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### This example demonstrates how to add futures for a given underlying asset.
-### It also shows how you can prefilter contracts easily based on expirations, and how you
-### can inspect the futures chain to pick a specific contract to trade.
-### </summary>
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="benchmarks" />
-### <meta name="tag" content="futures" />
-class BasicTemplateFuturesAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2013, 10, 8)
- self.set_end_date(2013, 10, 10)
- self.set_cash(1000000)
-
- self.contract_symbol = None
-
- # Subscribe and set our expiry filter for the futures chain
- futureSP500 = self.add_future(Futures.Indices.SP_500_E_MINI)
- future_gold = self.add_future(Futures.Metals.GOLD)
-
- # set our expiry filter for this futures chain
- # SetFilter method accepts timedelta objects or integer for days.
- # The following statements yield the same filtering criteria
- futureSP500.set_filter(timedelta(0), timedelta(182))
- future_gold.set_filter(0, 182)
-
- benchmark = self.add_equity("SPY")
- self.set_benchmark(benchmark.symbol)
-
- seeder = FuncSecuritySeeder(self.get_last_known_prices)
- self.set_security_initializer(lambda security: seeder.seed_security(security))
-
- def on_data(self,slice):
- if not self.portfolio.invested:
- for chain in slice.future_chains:
- # Get contracts expiring no earlier than in 90 days
- contracts = list(filter(lambda x: x.expiry > self.time + timedelta(90), chain.value))
-
- # if there is any contract, trade the front contract
- if len(contracts) == 0: continue
- front = sorted(contracts, key = lambda x: x.expiry, reverse=True)[0]
-
- self.contract_symbol = front.symbol
- self.market_order(front.symbol , 1)
- else:
- self.liquidate()
-
- def on_end_of_algorithm(self):
- # Get the margin requirements
- buying_power_model = self.securities[self.contract_symbol].buying_power_model
- name = type(buying_power_model).__name__
- if name != 'FutureMarginModel':
- raise Exception(f"Invalid buying power model. Found: {name}. Expected: FutureMarginModel")
-
- initial_overnight = buying_power_model.initial_overnight_margin_requirement
- maintenance_overnight = buying_power_model.maintenance_overnight_margin_requirement
- initial_intraday = buying_power_model.initial_intraday_margin_requirement
- maintenance_intraday = buying_power_model.maintenance_intraday_margin_requirement
-
- def on_securities_changed(self, changes):
- for added_security in changes.added_securities:
- if added_security.symbol.security_type == SecurityType.FUTURE and not added_security.symbol.is_canonical() and not added_security.has_data:
- raise Exception(f"Future contracts did not work up as expected: {added_security.symbol}")
diff --git a/fincept-qt/scripts/strategies/BasicTemplateFuturesConsolidationAlgorithm.py b/fincept-qt/scripts/strategies/BasicTemplateFuturesConsolidationAlgorithm.py
deleted file mode 100644
index 828c3f88c..000000000
--- a/fincept-qt/scripts/strategies/BasicTemplateFuturesConsolidationAlgorithm.py
+++ /dev/null
@@ -1,55 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-C0AB4825
-# Category: Futures
-# Description: A demonstration of consolidating futures data into larger bars for your algorithm
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### A demonstration of consolidating futures data into larger bars for your algorithm.
-### </summary>
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="benchmarks" />
-### <meta name="tag" content="consolidating data" />
-### <meta name="tag" content="futures" />
-class BasicTemplateFuturesConsolidationAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2013, 10, 7)
- self.set_end_date(2013, 10, 11)
- self.set_cash(1000000)
-
- # Subscribe and set our expiry filter for the futures chain
- futureSP500 = self.add_future(Futures.Indices.SP_500_E_MINI)
- # set our expiry filter for this future chain
- # SetFilter method accepts timedelta objects or integer for days.
- # The following statements yield the same filtering criteria
- futureSP500.set_filter(0, 182)
- # future.set_filter(timedelta(0), timedelta(182))
-
- self.consolidators = dict()
-
- def on_data(self,slice):
- pass
-
- def on_data_consolidated(self, sender, quote_bar):
- self.log("OnDataConsolidated called on " + str(self.time))
- self.log(str(quote_bar))
-
- def on_securities_changed(self, changes):
- for security in changes.added_securities:
- consolidator = QuoteBarConsolidator(timedelta(minutes=5))
- consolidator.data_consolidated += self.on_data_consolidated
- self.subscription_manager.add_consolidator(security.symbol, consolidator)
- self.consolidators[security.symbol] = consolidator
-
- for security in changes.removed_securities:
- consolidator = self.consolidators.pop(security.symbol)
- self.subscription_manager.remove_consolidator(security.symbol, consolidator)
- consolidator.data_consolidated -= self.on_data_consolidated
diff --git a/fincept-qt/scripts/strategies/BasicTemplateFuturesDailyAlgorithm.py b/fincept-qt/scripts/strategies/BasicTemplateFuturesDailyAlgorithm.py
deleted file mode 100644
index 7b99ecd3a..000000000
--- a/fincept-qt/scripts/strategies/BasicTemplateFuturesDailyAlgorithm.py
+++ /dev/null
@@ -1,59 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-B04B5965
-# Category: Futures
-# Description: This example demonstrates how to add futures with daily resolution
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### This example demonstrates how to add futures with daily resolution.
-### </summary>
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="benchmarks" />
-### <meta name="tag" content="futures" />
-class BasicTemplateFuturesDailyAlgorithm(QCAlgorithm):
- def initialize(self):
- self.set_start_date(2013, 10, 8)
- self.set_end_date(2014, 10, 10)
- self.set_cash(1000000)
-
- resolution = self.get_resolution()
- extended_market_hours = self.get_extended_market_hours()
-
- # Subscribe and set our expiry filter for the futures chain
- self.future_sp500 = self.add_future(Futures.Indices.SP_500_E_MINI, resolution, extended_market_hours=extended_market_hours)
- self.future_gold = self.add_future(Futures.Metals.GOLD, resolution, extended_market_hours=extended_market_hours)
-
- # set our expiry filter for this futures chain
- # SetFilter method accepts timedelta objects or integer for days.
- # The following statements yield the same filtering criteria
- self.future_sp500.set_filter(timedelta(0), timedelta(182))
- self.future_gold.set_filter(0, 182)
-
- def on_data(self,slice):
- if not self.portfolio.invested:
- for chain in slice.future_chains:
- # Get contracts expiring no earlier than in 90 days
- contracts = list(filter(lambda x: x.expiry > self.time + timedelta(90), chain.value))
-
- # if there is any contract, trade the front contract
- if len(contracts) == 0: continue
- contract = sorted(contracts, key = lambda x: x.expiry)[0]
-
- # if found, trade it.
- self.market_order(contract.symbol, 1)
- # Same as above, check for cases like trading on a friday night.
- elif all(x.exchange.hours.is_open(self.time, True) for x in self.securities.values() if x.invested):
- self.liquidate()
-
- def get_resolution(self):
- return Resolution.DAILY
-
- def get_extended_market_hours(self):
- return False
diff --git a/fincept-qt/scripts/strategies/BasicTemplateFuturesFrameworkAlgorithm.py b/fincept-qt/scripts/strategies/BasicTemplateFuturesFrameworkAlgorithm.py
deleted file mode 100644
index fbc5ad604..000000000
--- a/fincept-qt/scripts/strategies/BasicTemplateFuturesFrameworkAlgorithm.py
+++ /dev/null
@@ -1,79 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-3F20A848
-# Category: Futures
-# Description: Basic template futures framework algorithm uses framework components to define an algorithm that trades futures
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-from Alphas.ConstantAlphaModel import ConstantAlphaModel
-from Selection.FutureUniverseSelectionModel import FutureUniverseSelectionModel
-
-### <summary>
-### Basic template futures framework algorithm uses framework components
-### to define an algorithm that trades futures.
-### </summary>
-class BasicTemplateFuturesFrameworkAlgorithm(QCAlgorithm):
-
- def initialize(self):
-
- self.universe_settings.resolution = Resolution.MINUTE
- self.universe_settings.extended_market_hours = self.get_extended_market_hours()
-
- self.set_start_date(2013, 10, 7)
- self.set_end_date(2013, 10, 11)
- self.set_cash(100000)
-
- # set framework models
- self.set_universe_selection(FrontMonthFutureUniverseSelectionModel(self.select_future_chain_symbols))
- self.set_alpha(ConstantFutureContractAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(1)))
- self.set_portfolio_construction(SingleSharePortfolioConstructionModel())
- self.set_execution(ImmediateExecutionModel())
- self.set_risk_management(NullRiskManagementModel())
-
-
- def select_future_chain_symbols(self, utc_time):
- new_york_time = Extensions.convert_from_utc(utc_time, TimeZones.NEW_YORK)
- if new_york_time.date() < date(2013, 10, 9):
- return [ Symbol.create(Futures.Indices.SP_500_E_MINI, SecurityType.FUTURE, Market.CME) ]
- else:
- return [ Symbol.create(Futures.Metals.GOLD, SecurityType.FUTURE, Market.COMEX) ]
-
- def get_extended_market_hours(self):
- return False
-
-class FrontMonthFutureUniverseSelectionModel(FutureUniverseSelectionModel):
- '''Creates futures chain universes that select the front month contract and runs a user
- defined future_chain_symbol_selector every day to enable choosing different futures chains'''
- def __init__(self, select_future_chain_symbols):
- super().__init__(timedelta(1), select_future_chain_symbols)
-
- def filter(self, filter):
- '''Defines the futures chain universe filter'''
- return (filter.front_month()
- .only_apply_filter_at_market_open())
-
-class ConstantFutureContractAlphaModel(ConstantAlphaModel):
- '''Implementation of a constant alpha model that only emits insights for future symbols'''
- def __init__(self, _type, direction, period):
- super().__init__(_type, direction, period)
-
- def should_emit_insight(self, utc_time, symbol):
- # only emit alpha for future symbols and not underlying equity symbols
- if symbol.security_type != SecurityType.FUTURE:
- return False
-
- return super().should_emit_insight(utc_time, symbol)
-
-class SingleSharePortfolioConstructionModel(PortfolioConstructionModel):
- '''Portfolio construction model that sets target quantities to 1 for up insights and -1 for down insights'''
- def create_targets(self, algorithm, insights):
- targets = []
- for insight in insights:
- targets.append(PortfolioTarget(insight.symbol, insight.direction))
- return targets
diff --git a/fincept-qt/scripts/strategies/BasicTemplateFuturesFrameworkWithExtendedMarketAlgorithm.py b/fincept-qt/scripts/strategies/BasicTemplateFuturesFrameworkWithExtendedMarketAlgorithm.py
deleted file mode 100644
index 8d10f87fe..000000000
--- a/fincept-qt/scripts/strategies/BasicTemplateFuturesFrameworkWithExtendedMarketAlgorithm.py
+++ /dev/null
@@ -1,23 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-456D112C
-# Category: Futures
-# Description: Basic template futures framework algorithm uses framework components to define an algorithm that trades futures
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-from BasicTemplateFuturesFrameworkAlgorithm import BasicTemplateFuturesFrameworkAlgorithm
-
-### <summary>
-### Basic template futures framework algorithm uses framework components
-### to define an algorithm that trades futures.
-### </summary>
-class BasicTemplateFuturesFrameworkWithExtendedMarketAlgorithm(BasicTemplateFuturesFrameworkAlgorithm):
-
- def get_extended_market_hours(self):
- return True
diff --git a/fincept-qt/scripts/strategies/BasicTemplateFuturesHistoryAlgorithm.py b/fincept-qt/scripts/strategies/BasicTemplateFuturesHistoryAlgorithm.py
deleted file mode 100644
index 3199766da..000000000
--- a/fincept-qt/scripts/strategies/BasicTemplateFuturesHistoryAlgorithm.py
+++ /dev/null
@@ -1,81 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-265D788C
-# Category: Futures
-# Description: This example demonstrates how to get access to futures history for a given root symbol. It also shows how you can pre...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### This example demonstrates how to get access to futures history for a given root symbol.
-### It also shows how you can prefilter contracts easily based on expirations, and inspect the futures
-### chain to pick a specific contract to trade.
-### </summary>
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="history and warm up" />
-### <meta name="tag" content="history" />
-### <meta name="tag" content="futures" />
-class BasicTemplateFuturesHistoryAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2013, 10, 8)
- self.set_end_date(2013, 10, 9)
- self.set_cash(1000000)
-
- extended_market_hours = self.get_extended_market_hours()
-
- # Subscribe and set our expiry filter for the futures chain
- # find the front contract expiring no earlier than in 90 days
- future_es = self.add_future(Futures.Indices.SP_500_E_MINI, Resolution.MINUTE, extended_market_hours=extended_market_hours)
- future_es.set_filter(timedelta(0), timedelta(182))
-
- future_gc = self.add_future(Futures.Metals.GOLD, Resolution.MINUTE, extended_market_hours=extended_market_hours)
- future_gc.set_filter(timedelta(0), timedelta(182))
-
- self.set_benchmark(lambda x: 1000000)
-
- self.schedule.on(self.date_rules.every_day(), self.time_rules.every(timedelta(hours=1)), self.make_history_call)
- self._success_count = 0
-
- def make_history_call(self):
- history = self.history(self.securities.keys(), 10, Resolution.MINUTE)
- if len(history) < 10:
- raise Exception(f'Empty history at {self.time}')
- self._success_count += 1
-
- def on_end_of_algorithm(self):
- if self._success_count < self.get_expected_history_call_count():
- raise Exception(f'Scheduled Event did not assert history call as many times as expected: {self._success_count}/49')
-
- def on_data(self,slice):
- if self.portfolio.invested: return
- for chain in slice.future_chains:
- for contract in chain.value:
- self.log(f'{contract.symbol.value},' +
- f'Bid={contract.bid_price} ' +
- f'Ask={contract.ask_price} ' +
- f'Last={contract.last_price} ' +
- f'OI={contract.open_interest}')
-
- def on_securities_changed(self, changes):
- for change in changes.added_securities:
- history = self.history(change.symbol, 10, Resolution.MINUTE).sort_index(level='time', ascending=False)[:3]
-
- for index, row in history.iterrows():
- self.log(f'History: {index[1]} : {index[2]:%m/%d/%Y %I:%M:%S %p} > {row.close}')
-
- def on_order_event(self, order_event):
- # Order fill event handler. On an order fill update the resulting information is passed to this method.
- # Order event details containing details of the events
- self.log(f'{order_event}')
-
- def get_extended_market_hours(self):
- return False
-
- def get_expected_history_call_count(self):
- return 42
diff --git a/fincept-qt/scripts/strategies/BasicTemplateFuturesHistoryWithExtendedMarketHoursAlgorithm.py b/fincept-qt/scripts/strategies/BasicTemplateFuturesHistoryWithExtendedMarketHoursAlgorithm.py
deleted file mode 100644
index f9f2413de..000000000
--- a/fincept-qt/scripts/strategies/BasicTemplateFuturesHistoryWithExtendedMarketHoursAlgorithm.py
+++ /dev/null
@@ -1,31 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-9713D1F5
-# Category: Futures
-# Description: This example demonstrates how to get access to futures history for a given root symbol with extended market hours. It...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-from BasicTemplateFuturesHistoryAlgorithm import BasicTemplateFuturesHistoryAlgorithm
-
-### <summary>
-### This example demonstrates how to get access to futures history for a given root symbol with extended market hours.
-### It also shows how you can prefilter contracts easily based on expirations, and inspect the futures
-### chain to pick a specific contract to trade.
-### </summary>
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="history and warm up" />
-### <meta name="tag" content="history" />
-### <meta name="tag" content="futures" />
-class BasicTemplateFuturesHistoryWithExtendedMarketHoursAlgorithm(BasicTemplateFuturesHistoryAlgorithm):
-
- def get_extended_market_hours(self):
- return True
-
- def get_expected_history_call_count(self):
- return 49
diff --git a/fincept-qt/scripts/strategies/BasicTemplateFuturesHourlyAlgorithm.py b/fincept-qt/scripts/strategies/BasicTemplateFuturesHourlyAlgorithm.py
deleted file mode 100644
index 11ced4476..000000000
--- a/fincept-qt/scripts/strategies/BasicTemplateFuturesHourlyAlgorithm.py
+++ /dev/null
@@ -1,24 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-D52E449D
-# Category: Futures
-# Description: This example demonstrates how to add futures with hourly resolution
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-from BasicTemplateFuturesDailyAlgorithm import BasicTemplateFuturesDailyAlgorithm
-
-### <summary>
-### This example demonstrates how to add futures with hourly resolution.
-### </summary>
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="benchmarks" />
-### <meta name="tag" content="futures" />
-class BasicTemplateFuturesHourlyAlgorithm(BasicTemplateFuturesDailyAlgorithm):
-
- def get_resolution(self):
- return Resolution.HOUR
diff --git a/fincept-qt/scripts/strategies/BasicTemplateFuturesWithExtendedMarketAlgorithm.py b/fincept-qt/scripts/strategies/BasicTemplateFuturesWithExtendedMarketAlgorithm.py
deleted file mode 100644
index 15be871cd..000000000
--- a/fincept-qt/scripts/strategies/BasicTemplateFuturesWithExtendedMarketAlgorithm.py
+++ /dev/null
@@ -1,77 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-527E38F2
-# Category: Futures
-# Description: This example demonstrates how to add futures for a given underlying asset. It also shows how you can prefilter contra...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### This example demonstrates how to add futures for a given underlying asset.
-### It also shows how you can prefilter contracts easily based on expirations, and how you
-### can inspect the futures chain to pick a specific contract to trade.
-### </summary>
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="benchmarks" />
-### <meta name="tag" content="futures" />
-class BasicTemplateFuturesWithExtendedMarketAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2013, 10, 8)
- self.set_end_date(2013, 10, 10)
- self.set_cash(1000000)
-
- self.contract_symbol = None
-
- # Subscribe and set our expiry filter for the futures chain
- self.future_sp500 = self.add_future(Futures.Indices.SP_500_E_MINI, extended_market_hours = True)
- self.future_gold = self.add_future(Futures.Metals.GOLD, extended_market_hours = True)
-
- # set our expiry filter for this futures chain
- # SetFilter method accepts timedelta objects or integer for days.
- # The following statements yield the same filtering criteria
- self.future_sp500.set_filter(timedelta(0), timedelta(182))
- self.future_gold.set_filter(0, 182)
-
- benchmark = self.add_equity("SPY")
- self.set_benchmark(benchmark.symbol)
-
- seeder = FuncSecuritySeeder(self.get_last_known_prices)
- self.set_security_initializer(lambda security: seeder.seed_security(security))
-
- def on_data(self,slice):
- if not self.portfolio.invested:
- for chain in slice.future_chains:
- # Get contracts expiring no earlier than in 90 days
- contracts = list(filter(lambda x: x.expiry > self.time + timedelta(90), chain.value))
-
- # if there is any contract, trade the front contract
- if len(contracts) == 0: continue
- front = sorted(contracts, key = lambda x: x.expiry, reverse=True)[0]
-
- self.contract_symbol = front.symbol
- self.market_order(front.symbol , 1)
- else:
- self.liquidate()
-
- def on_end_of_algorithm(self):
- # Get the margin requirements
- buying_power_model = self.securities[self.contract_symbol].buying_power_model
- name = type(buying_power_model).__name__
- if name != 'FutureMarginModel':
- raise Exception(f"Invalid buying power model. Found: {name}. Expected: FutureMarginModel")
-
- initial_overnight = buying_power_model.initial_overnight_margin_requirement
- maintenance_overnight = buying_power_model.maintenance_overnight_margin_requirement
- initial_intraday = buying_power_model.initial_intraday_margin_requirement
- maintenance_intraday = buying_power_model.maintenance_intraday_margin_requirement
-
- def on_securities_changed(self, changes):
- for added_security in changes.added_securities:
- if added_security.symbol.security_type == SecurityType.FUTURE and not added_security.symbol.is_canonical() and not added_security.has_data:
- raise Exception(f"Future contracts did not work up as expected: {added_security.symbol}")
diff --git a/fincept-qt/scripts/strategies/BasicTemplateFuturesWithExtendedMarketDailyAlgorithm.py b/fincept-qt/scripts/strategies/BasicTemplateFuturesWithExtendedMarketDailyAlgorithm.py
deleted file mode 100644
index a1a320cb9..000000000
--- a/fincept-qt/scripts/strategies/BasicTemplateFuturesWithExtendedMarketDailyAlgorithm.py
+++ /dev/null
@@ -1,42 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-074CBF2C
-# Category: Futures
-# Description: EMA crossover strategy adapted from futures daily template.
-# Uses 10/30 EMA crossover to generate buy/sell signals. Buys when fast EMA
-# crosses above slow EMA, exits when fast crosses below.
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-class BasicTemplateFuturesWithExtendedMarketDailyAlgorithm(QCAlgorithm):
- """EMA 10/30 crossover strategy (adapted from futures daily template)."""
-
- def initialize(self):
- self.set_start_date(2023, 1, 1)
- self.set_end_date(2024, 1, 1)
- self.set_cash(100000)
-
- self.symbol = "SPY"
- self.add_equity(self.symbol, Resolution.DAILY)
-
- self._fast_ema = self.ema(self.symbol, 10, Resolution.DAILY)
- self._slow_ema = self.ema(self.symbol, 30, Resolution.DAILY)
-
- def on_data(self, data):
- if not self._fast_ema.is_ready or not self._slow_ema.is_ready:
- return
- if self.symbol not in data:
- return
-
- fast = self._fast_ema.current.value
- slow = self._slow_ema.current.value
-
- if not self.portfolio.invested and fast > slow:
- self.set_holdings(self.symbol, 0.9)
- elif self.portfolio.invested and fast < slow:
- self.liquidate()
diff --git a/fincept-qt/scripts/strategies/BasicTemplateFuturesWithExtendedMarketHourlyAlgorithm.py b/fincept-qt/scripts/strategies/BasicTemplateFuturesWithExtendedMarketHourlyAlgorithm.py
deleted file mode 100644
index da183cd44..000000000
--- a/fincept-qt/scripts/strategies/BasicTemplateFuturesWithExtendedMarketHourlyAlgorithm.py
+++ /dev/null
@@ -1,41 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-006DF51F
-# Category: Futures
-# Description: Momentum-based strategy adapted from futures template. Buys when
-# price crosses above 20-day SMA, sells when crossing below. Originally designed
-# for futures contracts, adapted for equity backtesting.
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-class BasicTemplateFuturesWithExtendedMarketHourlyAlgorithm(QCAlgorithm):
- """SMA trend-following strategy (adapted from futures template)."""
-
- def initialize(self):
- self.set_start_date(2013, 10, 8)
- self.set_end_date(2013, 10, 11)
- self.set_cash(100000)
-
- self.symbol = 'SPY'
- self.add_equity(self.symbol, Resolution.DAILY)
-
- self._sma = self.sma(self.symbol, 20, Resolution.DAILY)
- self._previous_invested = False
-
- def on_data(self, data):
- if not self._sma.is_ready:
- return
- if self.symbol not in data:
- return
-
- price = data[self.symbol].close
-
- if not self.portfolio.invested and price > self._sma.current.value:
- self.set_holdings(self.symbol, 0.9)
- elif self.portfolio.invested and price < self._sma.current.value:
- self.liquidate()
diff --git a/fincept-qt/scripts/strategies/BasicTemplateIndexAlgorithm.py b/fincept-qt/scripts/strategies/BasicTemplateIndexAlgorithm.py
deleted file mode 100644
index 0347225d0..000000000
--- a/fincept-qt/scripts/strategies/BasicTemplateIndexAlgorithm.py
+++ /dev/null
@@ -1,52 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-A17DA593
-# Category: Index
-# Description: Basic Template Index Algorithm
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-class BasicTemplateIndexAlgorithm(QCAlgorithm):
- def initialize(self) -> None:
- self.set_start_date(2021, 1, 4)
- self.set_end_date(2021, 1, 18)
- self.set_cash(1000000)
-
- # Use indicator for signal; but it cannot be traded
- self.spx = self.add_index("SPX", Resolution.MINUTE).symbol
-
- # Trade on SPX ITM calls
- self.spx_option = Symbol.create_option(
- self.spx,
- Market.USA,
- OptionStyle.EUROPEAN,
- OptionRight.CALL,
- 3200,
- datetime(2021, 1, 15)
- )
-
- self.add_index_option_contract(self.spx_option, Resolution.MINUTE)
-
- self.ema_slow = self.ema(self.spx, 80)
- self.ema_fast = self.ema(self.spx, 200)
-
- def on_data(self, data: Slice):
- if self.spx not in data.bars or self.spx_option not in data.bars:
- return
-
- if not self.ema_slow.is_ready:
- return
-
- if self.ema_fast > self.ema_slow:
- self.set_holdings(self.spx_option, 1)
- else:
- self.liquidate()
-
- def on_end_of_algorithm(self) -> None:
- if self.portfolio[self.spx].total_sale_volume > 0:
- raise Exception("Index is not tradable.")
diff --git a/fincept-qt/scripts/strategies/BasicTemplateIndexDailyAlgorithm.py b/fincept-qt/scripts/strategies/BasicTemplateIndexDailyAlgorithm.py
deleted file mode 100644
index f158cd898..000000000
--- a/fincept-qt/scripts/strategies/BasicTemplateIndexDailyAlgorithm.py
+++ /dev/null
@@ -1,65 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-A8601615
-# Category: Index
-# Description: Basic Template Index Daily Algorithm
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-import datetime
-from AlgorithmImports import *
-
-class BasicTemplateIndexDailyAlgorithm(QCAlgorithm):
-
- def initialize(self) -> None:
- self.set_start_date(2021, 1, 1)
- self.set_end_date(2021, 1, 18)
- self.set_cash(1000000)
-
- # Use indicator for signal; but it cannot be traded
- self.spx = self.add_index("SPX", Resolution.DAILY).symbol
-
- # Trade on SPX ITM calls
- self.spx_option = Symbol.create_option(
- self.spx,
- Market.USA,
- OptionStyle.EUROPEAN,
- OptionRight.CALL,
- 3200,
- datetime(2021, 1, 15)
- )
-
- self.add_index_option_contract(self.spx_option, Resolution.DAILY)
-
- self.ema_slow = self.ema(self.spx, 80)
- self.ema_fast = self.ema(self.spx, 200)
-
- self.ExpectedBarCount = 10
- self.BarCounter = 0
-
- self.settings.daily_precise_end_time = True
-
- def on_data(self, data: Slice):
- if not self.Portfolio.Invested:
- # SPX Index is not tradable, but we can trade an option
- self.MarketOrder(self.spx_option, 1)
- else:
- self.Liquidate()
-
- # Count how many slices we receive with SPX data in it to assert later
- if data.ContainsKey(self.spx):
- self.BarCounter = self.BarCounter + 1
-
- def OnEndOfAlgorithm(self):
- if self.BarCounter != self.ExpectedBarCount:
- raise ValueError(f"Bar Count {self.BarCounter} is not expected count of {self.ExpectedBarCount}")
-
- for symbol in [ self.spx_option, self.spx ]:
- history = self.History(symbol, 10)
- if len(history) != 10:
- raise ValueError(f"Unexpected history count: {history.Count}")
- if any(x for x in history.index.get_level_values('time') if x.time() != time(15, 15, 0)):
- raise ValueError(f"Unexpected history data time")
diff --git a/fincept-qt/scripts/strategies/BasicTemplateIndexOptionsAlgorithm.py b/fincept-qt/scripts/strategies/BasicTemplateIndexOptionsAlgorithm.py
deleted file mode 100644
index f4467c084..000000000
--- a/fincept-qt/scripts/strategies/BasicTemplateIndexOptionsAlgorithm.py
+++ /dev/null
@@ -1,57 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-210273A6
-# Category: Options
-# Description: Basic Template Index Options Algorithm
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-class BasicTemplateIndexOptionsAlgorithm(QCAlgorithm):
- def initialize(self) -> None:
- self.set_start_date(2021, 1, 4)
- self.set_end_date(2021, 2, 1)
- self.set_cash(1000000)
-
- self.spx = self.add_index("SPX", Resolution.MINUTE).symbol
- spx_options = self.add_index_option(self.spx, Resolution.MINUTE)
- spx_options.set_filter(lambda x: x.calls_only())
-
- self.ema_slow = self.ema(self.spx, 80)
- self.ema_fast = self.ema(self.spx, 200)
-
- def on_data(self, data: Slice) -> None:
- if self.spx not in data.bars or not self.ema_slow.is_ready:
- return
-
- for chain in data.option_chains.values():
- for contract in chain.contracts.values():
- if self.portfolio.invested:
- continue
-
- if (self.ema_fast > self.ema_slow and contract.right == OptionRight.CALL) or \
- (self.ema_fast < self.ema_slow and contract.right == OptionRight.PUT):
-
- self.liquidate(self.invert_option(contract.symbol))
- self.market_order(contract.symbol, 1)
-
- def on_end_of_algorithm(self) -> None:
- if self.portfolio[self.spx].total_sale_volume > 0:
- raise Exception("Index is not tradable.")
-
- if self.portfolio.total_sale_volume == 0:
- raise Exception("Trade volume should be greater than zero by the end of this algorithm")
-
- def invert_option(self, symbol: Symbol) -> Symbol:
- return Symbol.create_option(
- symbol.underlying,
- symbol.id.market,
- symbol.id.option_style,
- OptionRight.PUT if symbol.id.option_right == OptionRight.CALL else OptionRight.CALL,
- symbol.id.strike_price,
- symbol.id.date
- )
diff --git a/fincept-qt/scripts/strategies/BasicTemplateIndiaAlgorithm.py b/fincept-qt/scripts/strategies/BasicTemplateIndiaAlgorithm.py
deleted file mode 100644
index f8cc902b2..000000000
--- a/fincept-qt/scripts/strategies/BasicTemplateIndiaAlgorithm.py
+++ /dev/null
@@ -1,48 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-CB56992B
-# Category: Template
-# Description: Basic template framework algorithm uses framework components to define the algorithm
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Basic template framework algorithm uses framework components to define the algorithm.
-### </summary>
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="using quantconnect" />
-### <meta name="tag" content="trading and orders" />
-class BasicTemplateIndiaAlgorithm(QCAlgorithm):
- '''Basic template framework algorithm uses framework components to define the algorithm.'''
-
- def initialize(self):
- '''initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
-
- self.set_account_currency("INR") #Set Account Currency
- self.set_start_date(2019, 1, 23) #Set Start Date
- self.set_end_date(2019, 10, 31) #Set End Date
- self.set_cash(100000) #Set Strategy Cash
- # Fincept Terminal Strategy Engine - Symbol Configuration
- self.add_equity("YESBANK", Resolution.MINUTE, Market.INDIA)
- self.debug("numpy test >>> print numpy.pi: " + str(np.pi))
-
- # Set Order Properties as per the requirements for order placement
- self.default_order_properties = IndiaOrderProperties(Exchange.NSE)
-
- def on_data(self, data):
- '''on_data event is the primary entry point for your algorithm. Each new data point will be pumped in here.
-
- Arguments:
- data: Slice object keyed by symbol containing the stock data
- '''
- if not self.portfolio.invested:
- self.market_order("YESBANK", 1)
-
- def on_order_event(self, order_event):
- if order_event.status == OrderStatus.FILLED:
- self.debug("Purchased Stock: {0}".format(order_event.symbol))
diff --git a/fincept-qt/scripts/strategies/BasicTemplateIndiaIndexAlgorithm.py b/fincept-qt/scripts/strategies/BasicTemplateIndiaIndexAlgorithm.py
deleted file mode 100644
index f26d5b4b3..000000000
--- a/fincept-qt/scripts/strategies/BasicTemplateIndiaIndexAlgorithm.py
+++ /dev/null
@@ -1,69 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-77306E7F
-# Category: Index
-# Description: Basic Template India Index Algorithm uses framework components to define the algorithm
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Basic Template India Index Algorithm uses framework components to define the algorithm.
-### </summary>
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="using quantconnect" />
-### <meta name="tag" content="trading and orders" />
-class BasicTemplateIndiaIndexAlgorithm(QCAlgorithm):
- '''Basic template framework algorithm uses framework components to define the algorithm.'''
-
- def initialize(self):
- '''initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
-
- self.set_account_currency("INR") #Set Account Currency
- self.set_start_date(2019, 1, 1) #Set Start Date
- self.set_end_date(2019, 1, 5) #Set End Date
- self.set_cash(1000000) #Set Strategy Cash
-
- # Use indicator for signal; but it cannot be traded
- self.nifty = self.add_index("NIFTY50", Resolution.MINUTE, Market.INDIA).symbol
- # Trade Index based ETF
- self.nifty_etf = self.add_equity("JUNIORBEES", Resolution.MINUTE, Market.INDIA).symbol
-
- # Set Order Properties as per the requirements for order placement
- self.default_order_properties = IndiaOrderProperties(Exchange.NSE)
-
- # Define indicator
- self._ema_slow = self.ema(self.nifty, 80)
- self._ema_fast = self.ema(self.nifty, 200)
-
- self.debug("numpy test >>> print numpy.pi: " + str(np.pi))
-
-
- def on_data(self, data):
- '''on_data event is the primary entry point for your algorithm. Each new data point will be pumped in here.
-
- Arguments:
- data: Slice object keyed by symbol containing the stock data
- '''
-
- if not data.bars.contains_key(self.nifty) or not data.bars.contains_key(self.nifty_etf):
- return
-
- if not self._ema_slow.is_ready:
- return
-
- if self._ema_fast > self._ema_slow:
- if not self.portfolio.invested:
- self.market_ticket = self.market_order(self.nifty_etf, 1)
- else:
- self.liquidate()
-
-
- def on_end_of_algorithm(self):
- if self.portfolio[self.nifty].total_sale_volume > 0:
- raise Exception("Index is not tradable.")
-
diff --git a/fincept-qt/scripts/strategies/BasicTemplateIntrinioEconomicData.py b/fincept-qt/scripts/strategies/BasicTemplateIntrinioEconomicData.py
deleted file mode 100644
index 018adfb64..000000000
--- a/fincept-qt/scripts/strategies/BasicTemplateIntrinioEconomicData.py
+++ /dev/null
@@ -1,45 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-13F865B8
-# Category: Template
-# Description: EMA trend-following strategy inspired by economic data analysis.
-# Buys when price is above 20-day EMA with positive momentum, sells when
-# price drops below EMA or momentum turns negative.
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-class BasicTemplateIntrinioEconomicData(QCAlgorithm):
- """EMA trend-following with momentum confirmation."""
-
- def initialize(self):
- self.set_start_date(2023, 1, 1)
- self.set_end_date(2024, 1, 1)
- self.set_cash(100000)
-
- self.symbol = "SPY"
- self.add_equity(self.symbol, Resolution.DAILY)
-
- self._ema = self.ema(self.symbol, 20, Resolution.DAILY)
- self._mom = self.momp(self.symbol, 10, Resolution.DAILY)
-
- def on_data(self, data):
- if not self._ema.is_ready or not self._mom.is_ready:
- return
- if self.symbol not in data:
- return
-
- price = data[self.symbol].close
- ema_val = self._ema.current.value
- mom_val = self._mom.current.value
-
- if not self.portfolio.invested:
- if price > ema_val and mom_val > 0:
- self.set_holdings(self.symbol, 1)
- else:
- if price < ema_val or mom_val < -2:
- self.liquidate()
diff --git a/fincept-qt/scripts/strategies/BasicTemplateLibrary.py b/fincept-qt/scripts/strategies/BasicTemplateLibrary.py
deleted file mode 100644
index 4d9ea0df1..000000000
--- a/fincept-qt/scripts/strategies/BasicTemplateLibrary.py
+++ /dev/null
@@ -1,37 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-A18CA8E6
-# Category: Template
-# Description: Basic Template Library Class ### Library classes are snippets of code/classes you can reuse between projects. They ar...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Basic Template Library Class
-###
-### Library classes are snippets of code/classes you can reuse between projects. They are
-### added to projects on compile. This can be useful for reusing indicators, math functions,
-### risk modules etc. Make sure you import the class in your algorithm. You need
-### to name the file the module you'll be importing (not main.cs).
-### importing.
-### </summary>
-class BasicTemplateLibrary:
-
- '''
- To use this library place this at the top:
- from BasicTemplateLibrary import BasicTemplateLibrary
-
- Then instantiate the function:
- x = BasicTemplateLibrary()
- x.add(1,2)
- '''
- def add(self, a, b):
- return a + b
-
- def subtract(self, a, b):
- return a - b
diff --git a/fincept-qt/scripts/strategies/BasicTemplateOptionEquityStrategyAlgorithm.py b/fincept-qt/scripts/strategies/BasicTemplateOptionEquityStrategyAlgorithm.py
deleted file mode 100644
index 5b5d7555b..000000000
--- a/fincept-qt/scripts/strategies/BasicTemplateOptionEquityStrategyAlgorithm.py
+++ /dev/null
@@ -1,63 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-3EB6E68A
-# Category: Options
-# Description: This example demonstrates how to execute a Call Butterfly option equity strategy It adds options for a given underlyi...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### This example demonstrates how to execute a Call Butterfly option equity strategy
-### It adds options for a given underlying equity security, and shows how you can prefilter contracts easily based on strikes and expirations
-### </summary>
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="options" />
-### <meta name="tag" content="filter selection" />
-### <meta name="tag" content="trading and orders" />
-class BasicTemplateOptionEquityStrategyAlgorithm(QCAlgorithm):
- underlying_ticker = "GOOG"
-
- def initialize(self):
- self.set_start_date(2015, 12, 24)
- self.set_end_date(2015, 12, 24)
-
- equity = self.add_equity(self.underlying_ticker)
- option = self.add_option(self.underlying_ticker)
- self.option_symbol = option.symbol
-
- # set our strike/expiry filter for this option chain
- option.set_filter(lambda u: (u.strikes(-2, +2)
- # Expiration method accepts TimeSpan objects or integer for days.
- # The following statements yield the same filtering criteria
- .expiration(0, 180)))
-
- def on_data(self, slice):
- if self.portfolio.invested or not self.is_market_open(self.option_symbol): return
-
- chain = slice.option_chains.get_value(self.option_symbol)
- if chain is None:
- return
-
- grouped_by_expiry = dict()
- for contract in [contract for contract in chain if contract.right == OptionRight.CALL]:
- grouped_by_expiry.setdefault(int(contract.expiry.timestamp()), []).append(contract)
-
- first_expiry = list(sorted(grouped_by_expiry))[0]
- call_contracts = sorted(grouped_by_expiry[first_expiry], key = lambda x: x.strike)
-
- expiry = call_contracts[0].expiry
- lower_strike = call_contracts[0].strike
- middle_strike = call_contracts[1].strike
- higher_strike = call_contracts[2].strike
-
- option_strategy = OptionStrategies.call_butterfly(self.option_symbol, higher_strike, middle_strike, lower_strike, expiry)
-
- self.order(option_strategy, 10)
-
- def on_order_event(self, order_event):
- self.log(str(order_event))
diff --git a/fincept-qt/scripts/strategies/BasicTemplateOptionStrategyAlgorithm.py b/fincept-qt/scripts/strategies/BasicTemplateOptionStrategyAlgorithm.py
deleted file mode 100644
index 7e7fa0823..000000000
--- a/fincept-qt/scripts/strategies/BasicTemplateOptionStrategyAlgorithm.py
+++ /dev/null
@@ -1,48 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-185C6BF9
-# Category: Options
-# Description: Options-inspired hedged momentum strategy. Buys SPY when above
-# both 10 and 30-day EMAs (strong uptrend). Uses tight stop (2%) to simulate
-# option-like risk profile. Re-enters on trend resumption.
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-class BasicTemplateOptionStrategyAlgorithm(QCAlgorithm):
- """Hedged momentum with tight stop-loss."""
-
- def initialize(self):
- self.set_start_date(2023, 1, 1)
- self.set_end_date(2024, 1, 1)
- self.set_cash(100000)
-
- self.symbol = "SPY"
- self.add_equity(self.symbol, Resolution.DAILY)
-
- self._ema10 = self.ema(self.symbol, 10, Resolution.DAILY)
- self._ema30 = self.ema(self.symbol, 30, Resolution.DAILY)
- self._entry_price = 0
-
- def on_data(self, data):
- if not self._ema30.is_ready:
- return
- if self.symbol not in data:
- return
-
- price = data[self.symbol].close
- e10 = self._ema10.current.value
- e30 = self._ema30.current.value
-
- if not self.portfolio.invested:
- if price > e10 and e10 > e30:
- self.set_holdings(self.symbol, 1)
- self._entry_price = price
- else:
- # Tight stop-loss (2%) or trend reversal
- if price < self._entry_price * 0.98 or e10 < e30:
- self.liquidate()
diff --git a/fincept-qt/scripts/strategies/BasicTemplateOptionTradesAlgorithm.py b/fincept-qt/scripts/strategies/BasicTemplateOptionTradesAlgorithm.py
deleted file mode 100644
index 401dbe2de..000000000
--- a/fincept-qt/scripts/strategies/BasicTemplateOptionTradesAlgorithm.py
+++ /dev/null
@@ -1,58 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-29268ED2
-# Category: Options
-# Description: This example demonstrates how to add options for a given underlying equity security. It also shows how you can prefil...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### This example demonstrates how to add options for a given underlying equity security.
-### It also shows how you can prefilter contracts easily based on strikes and expirations.
-### It also shows how you can inspect the option chain to pick a specific option contract to trade.
-### </summary>
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="options" />
-### <meta name="tag" content="filter selection" />
-class BasicTemplateOptionTradesAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2015, 12, 24)
- self.set_end_date(2015, 12, 24)
- self.set_cash(100000)
-
- option = self.add_option("GOOG")
-
- # add the initial contract filter
- # SetFilter method accepts timedelta objects or integer for days.
- # The following statements yield the same filtering criteria
- option.set_filter(-2, +2, 0, 10)
- # option.set_filter(-2, +2, timedelta(0), timedelta(10))
-
- # use the underlying equity as the benchmark
- self.set_benchmark("GOOG")
-
- def on_data(self,slice):
- if not self.portfolio.invested:
- for kvp in slice.option_chains:
- chain = kvp.value
- # find the second call strike under market price expiring today
- contracts = sorted(sorted(chain, key = lambda x: abs(chain.underlying.price - x.strike)),
- key = lambda x: x.expiry, reverse=False)
-
- if len(contracts) == 0: continue
- if contracts[0] != None:
- self.market_order(contracts[0].symbol, 1)
- else:
- self.liquidate()
-
- for kpv in slice.bars:
- self.log("---> OnData: {0}, {1}, {2}".format(self.time, kpv.key.value, str(kpv.value.close)))
-
- def on_order_event(self, order_event):
- self.log(str(order_event))
diff --git a/fincept-qt/scripts/strategies/BasicTemplateOptionsAlgorithm.py b/fincept-qt/scripts/strategies/BasicTemplateOptionsAlgorithm.py
deleted file mode 100644
index cbe87f044..000000000
--- a/fincept-qt/scripts/strategies/BasicTemplateOptionsAlgorithm.py
+++ /dev/null
@@ -1,64 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-9970673F
-# Category: Options
-# Description: This example demonstrates how to add options for a given underlying equity security. It also shows how you can prefil...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### This example demonstrates how to add options for a given underlying equity security.
-### It also shows how you can prefilter contracts easily based on strikes and expirations, and how you
-### can inspect the option chain to pick a specific option contract to trade.
-### </summary>
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="options" />
-### <meta name="tag" content="filter selection" />
-class BasicTemplateOptionsAlgorithm(QCAlgorithm):
- underlying_ticker = "GOOG"
-
- def initialize(self):
- self.set_start_date(2015, 12, 24)
- self.set_end_date(2015, 12, 24)
- self.set_cash(100000)
-
- equity = self.add_equity(self.underlying_ticker)
- option = self.add_option(self.underlying_ticker)
- self.option_symbol = option.symbol
-
- # set our strike/expiry filter for this option chain
- option.set_filter(lambda u: (u.strikes(-2, +2)
- # Expiration method accepts TimeSpan objects or integer for days.
- # The following statements yield the same filtering criteria
- .expiration(0, 180)))
- #.expiration(TimeSpan.zero, TimeSpan.from_days(180))))
-
- # use the underlying equity as the benchmark
- self.set_benchmark(equity.symbol)
-
- def on_data(self, slice):
- if self.portfolio.invested or not self.is_market_open(self.option_symbol): return
-
- chain = slice.option_chains.get_value(self.option_symbol)
- if chain is None:
- return
-
- # we sort the contracts to find at the money (ATM) contract with farthest expiration
- contracts = sorted(sorted(sorted(chain, \
- key = lambda x: abs(chain.underlying.price - x.strike)), \
- key = lambda x: x.expiry, reverse=True), \
- key = lambda x: x.right, reverse=True)
-
- # if found, trade it
- if len(contracts) == 0: return
- symbol = contracts[0].symbol
- self.market_order(symbol, 1)
- self.market_on_close_order(symbol, -1)
-
- def on_order_event(self, order_event):
- self.log(str(order_event))
diff --git a/fincept-qt/scripts/strategies/BasicTemplateOptionsConsolidationAlgorithm.py b/fincept-qt/scripts/strategies/BasicTemplateOptionsConsolidationAlgorithm.py
deleted file mode 100644
index fb9c0f864..000000000
--- a/fincept-qt/scripts/strategies/BasicTemplateOptionsConsolidationAlgorithm.py
+++ /dev/null
@@ -1,63 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-48AE2A59
-# Category: Options
-# Description: A demonstration of consolidating options data into larger bars for your algorithm
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### A demonstration of consolidating options data into larger bars for your algorithm.
-### </summary>
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="benchmarks" />
-### <meta name="tag" content="consolidating data" />
-### <meta name="tag" content="options" />
-class BasicTemplateOptionsConsolidationAlgorithm(QCAlgorithm):
- def initialize(self):
- self.set_start_date(2013, 10, 7)
- self.set_end_date(2013, 10, 11)
- self.set_cash(1000000)
-
- # Subscribe and set our filter for the options chain
- option = self.add_option('SPY')
- # set our strike/expiry filter for this option chain
- # SetFilter method accepts timedelta objects or integer for days.
- # The following statements yield the same filtering criteria
- option.set_filter(-2, +2, 0, 180)
- # option.set_filter(-2, +2, timedelta(0), timedelta(180))
- self.consolidators = dict()
-
- def on_quote_bar_consolidated(self, sender, quote_bar):
- self.log("OnQuoteBarConsolidated called on " + str(self.time))
- self.log(str(quote_bar))
-
- def on_trade_bar_consolidated(self, sender, trade_bar):
- self.log("OnTradeBarConsolidated called on " + str(self.time))
- self.log(str(trade_bar))
-
- def on_securities_changed(self, changes):
- for security in changes.added_securities:
- if security.type == SecurityType.EQUITY:
- consolidator = TradeBarConsolidator(timedelta(minutes=5))
- consolidator.data_consolidated += self.on_trade_bar_consolidated
- else:
- consolidator = QuoteBarConsolidator(timedelta(minutes=5))
- consolidator.data_consolidated += self.on_quote_bar_consolidated
-
- self.subscription_manager.add_consolidator(security.symbol, consolidator)
- self.consolidators[security.symbol] = consolidator
-
- for security in changes.removed_securities:
- consolidator = self.consolidators.pop(security.symbol)
- self.subscription_manager.remove_consolidator(security.symbol, consolidator)
-
- if security.type == SecurityType.EQUITY:
- consolidator.data_consolidated -= self.on_trade_bar_consolidated
- else:
- consolidator.data_consolidated -= self.on_quote_bar_consolidated
diff --git a/fincept-qt/scripts/strategies/BasicTemplateOptionsDailyAlgorithm.py b/fincept-qt/scripts/strategies/BasicTemplateOptionsDailyAlgorithm.py
deleted file mode 100644
index 028d5c3d5..000000000
--- a/fincept-qt/scripts/strategies/BasicTemplateOptionsDailyAlgorithm.py
+++ /dev/null
@@ -1,71 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-216E29F5
-# Category: Options
-# Description: This example demonstrates how to add options for a given underlying equity security. It also shows how you can prefil...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### This example demonstrates how to add options for a given underlying equity security.
-### It also shows how you can prefilter contracts easily based on strikes and expirations, and how you
-### can inspect the option chain to pick a specific option contract to trade.
-### </summary>
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="options" />
-### <meta name="tag" content="filter selection" />
-class BasicTemplateOptionsDailyAlgorithm(QCAlgorithm):
- underlying_ticker = "AAPL"
-
- def initialize(self):
- self.set_start_date(2015, 12, 15)
- self.set_end_date(2016, 2, 1)
- self.set_cash(100000)
- self.option_expired = False
-
- equity = self.add_equity(self.underlying_ticker, Resolution.DAILY)
- option = self.add_option(self.underlying_ticker, Resolution.DAILY)
- self.option_symbol = option.symbol
-
- # set our strike/expiry filter for this option chain
- option.set_filter(lambda u: (u.calls_only().expiration(0, 60)))
-
- # use the underlying equity as the benchmark
- self.set_benchmark(equity.symbol)
-
- def on_data(self,slice):
- if self.portfolio.invested: return
-
- chain = slice.option_chains.get_value(self.option_symbol)
- if chain is None:
- return
-
- # Grab us the contract nearest expiry
- contracts = sorted(chain, key = lambda x: x.expiry)
-
- # if found, trade it
- if len(contracts) == 0: return
- symbol = contracts[0].symbol
- self.market_order(symbol, 1)
-
- def on_order_event(self, order_event):
- self.log(str(order_event))
-
- # Check for our expected OTM option expiry
- if "OTM" in order_event.message:
-
- # Assert it is at midnight 1/16 (5AM UTC)
- if order_event.utc_time.month != 1 and order_event.utc_time.day != 16 and order_event.utc_time.hour != 5:
- raise AssertionError(f"Expiry event was not at the correct time, {order_event.utc_time}")
-
- self.option_expired = True
-
- def on_end_of_algorithm(self):
- # Assert we had our option expire and fill a liquidation order
- if not self.option_expired:
- raise AssertionError("Algorithm did not process the option expiration like expected")
diff --git a/fincept-qt/scripts/strategies/BasicTemplateOptionsFilterUniverseAlgorithm.py b/fincept-qt/scripts/strategies/BasicTemplateOptionsFilterUniverseAlgorithm.py
deleted file mode 100644
index e41bd3694..000000000
--- a/fincept-qt/scripts/strategies/BasicTemplateOptionsFilterUniverseAlgorithm.py
+++ /dev/null
@@ -1,61 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-702E8C68
-# Category: Options
-# Description: This example demonstrates how to add options for a given underlying equity security. It also shows how you can prefil...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### This example demonstrates how to add options for a given underlying equity security.
-### It also shows how you can prefilter contracts easily based on strikes and expirations.
-### It also shows how you can inspect the option chain to pick a specific option contract to trade.
-### </summary>
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="options" />
-### <meta name="tag" content="filter selection" />
-class BasicTemplateOptionsFilterUniverseAlgorithm(QCAlgorithm):
- underlying_ticker = "GOOG"
-
- def initialize(self):
- self.set_start_date(2015, 12, 24)
- self.set_end_date(2015, 12, 28)
- self.set_cash(100000)
-
- equity = self.add_equity(self.underlying_ticker)
- option = self.add_option(self.underlying_ticker)
- self.option_symbol = option.symbol
-
- # Set our custom universe filter
- option.set_filter(self.filter_function)
-
- # use the underlying equity as the benchmark
- self.set_benchmark(equity.symbol)
-
- def filter_function(self, universe):
- #Expires today, is a call, and is within 10 dollars of the current price
- universe = universe.weeklys_only().expiration(0, 1)
- return [symbol for symbol in universe
- if symbol.id.option_right != OptionRight.PUT
- and -10 < universe.underlying.price - symbol.id.strike_price < 10]
-
- def on_data(self, slice):
- if self.portfolio.invested: return
-
- for kvp in slice.option_chains:
-
- if kvp.key != self.option_symbol: continue
-
- # Get the first call strike under market price expiring today
- chain = kvp.value
- contracts = [option for option in sorted(chain, key = lambda x:x.strike, reverse = True)
- if option.expiry.date() == self.time.date()
- and option.strike < chain.underlying.price]
-
- if contracts:
- self.market_order(contracts[0].symbol, 1)
diff --git a/fincept-qt/scripts/strategies/BasicTemplateOptionsFrameworkAlgorithm.py b/fincept-qt/scripts/strategies/BasicTemplateOptionsFrameworkAlgorithm.py
deleted file mode 100644
index 466f6ad22..000000000
--- a/fincept-qt/scripts/strategies/BasicTemplateOptionsFrameworkAlgorithm.py
+++ /dev/null
@@ -1,81 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-778FF392
-# Category: Options
-# Description: Basic template options framework algorithm uses framework components to define an algorithm that trades options
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-from Alphas.ConstantAlphaModel import ConstantAlphaModel
-from Selection.OptionUniverseSelectionModel import OptionUniverseSelectionModel
-from Execution.ImmediateExecutionModel import ImmediateExecutionModel
-from Risk.NullRiskManagementModel import NullRiskManagementModel
-
-
-### <summary>
-### Basic template options framework algorithm uses framework components
-### to define an algorithm that trades options.
-### </summary>
-class BasicTemplateOptionsFrameworkAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.universe_settings.resolution = Resolution.MINUTE
-
- self.set_start_date(2014, 6, 5)
- self.set_end_date(2014, 6, 9)
- self.set_cash(100000)
-
- # set framework models
- self.set_universe_selection(EarliestExpiringWeeklyAtTheMoneyPutOptionUniverseSelectionModel(self.select_option_chain_symbols))
- self.set_alpha(ConstantOptionContractAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(hours = 0.5)))
- self.set_portfolio_construction(SingleSharePortfolioConstructionModel())
- self.set_execution(ImmediateExecutionModel())
- self.set_risk_management(NullRiskManagementModel())
-
-
- def select_option_chain_symbols(self, utc_time):
- new_york_time = Extensions.convert_from_utc(utc_time, TimeZones.NEW_YORK)
- ticker = "TWX" if new_york_time.date() < date(2014, 6, 6) else "AAPL"
- return [ Symbol.create(ticker, SecurityType.OPTION, Market.USA, f"?{ticker}") ]
-
-class EarliestExpiringWeeklyAtTheMoneyPutOptionUniverseSelectionModel(OptionUniverseSelectionModel):
- '''Creates option chain universes that select only the earliest expiry ATM weekly put contract
- and runs a user defined option_chain_symbol_selector every day to enable choosing different option chains'''
- def __init__(self, select_option_chain_symbols):
- super().__init__(timedelta(1), select_option_chain_symbols)
-
- def filter(self, filter):
- '''Defines the option chain universe filter'''
- return (filter.strikes(+1, +1)
- # Expiration method accepts timedelta objects or integer for days.
- # The following statements yield the same filtering criteria
- .expiration(0, 7)
- # .expiration(timedelta(0), timedelta(7))
- .weeklys_only()
- .puts_only()
- .only_apply_filter_at_market_open())
-
-class ConstantOptionContractAlphaModel(ConstantAlphaModel):
- '''Implementation of a constant alpha model that only emits insights for option symbols'''
- def __init__(self, type, direction, period):
- super().__init__(type, direction, period)
-
- def should_emit_insight(self, utc_time, symbol):
- # only emit alpha for option symbols and not underlying equity symbols
- if symbol.security_type != SecurityType.OPTION:
- return False
-
- return super().should_emit_insight(utc_time, symbol)
-
-class SingleSharePortfolioConstructionModel(PortfolioConstructionModel):
- '''Portfolio construction model that sets target quantities to 1 for up insights and -1 for down insights'''
- def create_targets(self, algorithm, insights):
- targets = []
- for insight in insights:
- targets.append(PortfolioTarget(insight.symbol, insight.direction))
- return targets
diff --git a/fincept-qt/scripts/strategies/BasicTemplateOptionsHistoryAlgorithm.py b/fincept-qt/scripts/strategies/BasicTemplateOptionsHistoryAlgorithm.py
deleted file mode 100644
index 561dc68d7..000000000
--- a/fincept-qt/scripts/strategies/BasicTemplateOptionsHistoryAlgorithm.py
+++ /dev/null
@@ -1,75 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-9F0275D6
-# Category: Options
-# Description: Example demonstrating how to access to options history for a given underlying equity security
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Example demonstrating how to access to options history for a given underlying equity security.
-### </summary>
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="options" />
-### <meta name="tag" content="filter selection" />
-### <meta name="tag" content="history" />
-class BasicTemplateOptionsHistoryAlgorithm(QCAlgorithm):
- ''' This example demonstrates how to get access to options history for a given underlying equity security.'''
-
- def initialize(self):
- # this test opens position in the first day of trading, lives through stock split (7 for 1), and closes adjusted position on the second day
- self.set_start_date(2015, 12, 24)
- self.set_end_date(2015, 12, 24)
- self.set_cash(1000000)
-
- option = self.add_option("GOOG")
- # add the initial contract filter
- # SetFilter method accepts timedelta objects or integer for days.
- # The following statements yield the same filtering criteria
- option.set_filter(-2, +2, 0, 180)
- # option.set_filter(-2,2, timedelta(0), timedelta(180))
-
- # set the pricing model for Greeks and volatility
- # find more pricing models https://www.quantconnect.com/lean/documentation/topic27704.html
- option.price_model = OptionPriceModels.crank_nicolson_fd()
- # set the warm-up period for the pricing model
- self.set_warm_up(TimeSpan.from_days(4))
- # set the benchmark to be the initial cash
- self.set_benchmark(lambda x: 1000000)
-
- def on_data(self,slice):
- if self.is_warming_up: return
- if not self.portfolio.invested:
- for chain in slice.option_chains:
- volatility = self.securities[chain.key.underlying].volatility_model.volatility
- for contract in chain.value:
- self.log("{0},Bid={1} Ask={2} Last={3} OI={4} sigma={5:.3f} NPV={6:.3f} \
- delta={7:.3f} gamma={8:.3f} vega={9:.3f} beta={10:.2f} theta={11:.2f} IV={12:.2f}".format(
- contract.symbol.value,
- contract.bid_price,
- contract.ask_price,
- contract.last_price,
- contract.open_interest,
- volatility,
- contract.theoretical_price,
- contract.greeks.delta,
- contract.greeks.gamma,
- contract.greeks.vega,
- contract.greeks.rho,
- contract.greeks.theta / 365,
- contract.implied_volatility))
-
- def on_securities_changed(self, changes):
- for change in changes.added_securities:
- # only print options price
- if change.symbol.value == "GOOG": return
- history = self.history(change.symbol, 10, Resolution.MINUTE).sort_index(level='time', ascending=False)[:3]
- for index, row in history.iterrows():
- self.log("History: " + str(index[3])
- + ": " + index[4].strftime("%m/%d/%Y %I:%M:%S %p")
- + " > " + str(row.close))
diff --git a/fincept-qt/scripts/strategies/BasicTemplateOptionsHourlyAlgorithm.py b/fincept-qt/scripts/strategies/BasicTemplateOptionsHourlyAlgorithm.py
deleted file mode 100644
index 4a37b2315..000000000
--- a/fincept-qt/scripts/strategies/BasicTemplateOptionsHourlyAlgorithm.py
+++ /dev/null
@@ -1,64 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-77549805
-# Category: Options
-# Description: This example demonstrates how to add options for a given underlying equity security. It also shows how you can prefil...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### This example demonstrates how to add options for a given underlying equity security.
-### It also shows how you can prefilter contracts easily based on strikes and expirations, and how you
-### can inspect the option chain to pick a specific option contract to trade.
-### </summary>
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="options" />
-### <meta name="tag" content="filter selection" />
-class BasicTemplateOptionsHourlyAlgorithm(QCAlgorithm):
- underlying_ticker = "AAPL"
-
- def initialize(self):
- self.set_start_date(2014, 6, 6)
- self.set_end_date(2014, 6, 9)
- self.set_cash(100000)
-
- equity = self.add_equity(self.underlying_ticker, Resolution.HOUR)
- option = self.add_option(self.underlying_ticker, Resolution.HOUR)
- self.option_symbol = option.symbol
-
- # set our strike/expiry filter for this option chain
- option.set_filter(lambda u: (u.strikes(-2, +2)
- # Expiration method accepts TimeSpan objects or integer for days.
- # The following statements yield the same filtering criteria
- .expiration(0, 180)))
- #.expiration(TimeSpan.zero, TimeSpan.from_days(180))))
-
- # use the underlying equity as the benchmark
- self.set_benchmark(equity.symbol)
-
- def on_data(self,slice):
- if self.portfolio.invested or not self.is_market_open(self.option_symbol): return
-
- chain = slice.option_chains.get_value(self.option_symbol)
- if chain is None:
- return
-
- # we sort the contracts to find at the money (ATM) contract with farthest expiration
- contracts = sorted(sorted(sorted(chain, \
- key = lambda x: abs(chain.underlying.price - x.strike)), \
- key = lambda x: x.expiry, reverse=True), \
- key = lambda x: x.right, reverse=True)
-
- # if found, trade it
- if len(contracts) == 0 or not self.is_market_open(contracts[0].symbol): return
- symbol = contracts[0].symbol
- self.market_order(symbol, 1)
- self.market_on_close_order(symbol, -1)
-
- def on_order_event(self, order_event):
- self.log(str(order_event))
diff --git a/fincept-qt/scripts/strategies/BasicTemplateOptionsPriceModel.py b/fincept-qt/scripts/strategies/BasicTemplateOptionsPriceModel.py
deleted file mode 100644
index 277645199..000000000
--- a/fincept-qt/scripts/strategies/BasicTemplateOptionsPriceModel.py
+++ /dev/null
@@ -1,62 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-79BA1C77
-# Category: Options
-# Description: Example demonstrating how to define an option price model
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Example demonstrating how to define an option price model.
-### </summary>
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="options" />
-### <meta name="tag" content="filter selection" />
-### <meta name="tag" content="option price model" />
-class BasicTemplateOptionsPriceModel(QCAlgorithm):
- '''Example demonstrating how to define an option price model.'''
-
- def initialize(self):
- self.set_start_date(2020, 1, 1)
- self.set_end_date(2020, 1, 5)
- self.set_cash(100000)
-
- # Add the option
- option = self.add_option("AAPL")
- self.option_symbol = option.symbol
-
- # Add the initial contract filter
- option.set_filter(-3, +3, 0, 31)
-
- # Define the Option Price Model
- option.price_model = OptionPriceModels.crank_nicolson_fd()
- #option.price_model = OptionPriceModels.black_scholes()
- #option.price_model = OptionPriceModels.additive_equiprobabilities()
- #option.price_model = OptionPriceModels.barone_adesi_whaley()
- #option.price_model = OptionPriceModels.binomial_cox_ross_rubinstein()
- #option.price_model = OptionPriceModels.binomial_jarrow_rudd()
- #option.price_model = OptionPriceModels.binomial_joshi()
- #option.price_model = OptionPriceModels.binomial_leisen_reimer()
- #option.price_model = OptionPriceModels.binomial_tian()
- #option.price_model = OptionPriceModels.binomial_trigeorgis()
- #option.price_model = OptionPriceModels.bjerksund_stensland()
- #option.price_model = OptionPriceModels.integral()
-
- # Set warm up with 30 trading days to warm up the underlying volatility model
- self.set_warm_up(30, Resolution.DAILY)
-
-
- def on_data(self,slice):
- '''OnData will test whether the option contracts has a non-zero Greeks.delta'''
-
- if self.is_warming_up or not slice.option_chains.contains_key(self.option_symbol):
- return
-
- chain = slice.option_chains[self.option_symbol]
- if not any([x for x in chain if x.greeks.delta != 0]):
- self.log(f'No contract with Delta != 0')
diff --git a/fincept-qt/scripts/strategies/BasicTemplateSPXWeeklyIndexOptionsAlgorithm.py b/fincept-qt/scripts/strategies/BasicTemplateSPXWeeklyIndexOptionsAlgorithm.py
deleted file mode 100644
index 62f0c396c..000000000
--- a/fincept-qt/scripts/strategies/BasicTemplateSPXWeeklyIndexOptionsAlgorithm.py
+++ /dev/null
@@ -1,59 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-DB3B5321
-# Category: Options
-# Description: This example demonstrates how to add and trade SPX index weekly options
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### This example demonstrates how to add and trade SPX index weekly options
-### </summary>
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="options" />
-### <meta name="tag" content="indexes" />
-class BasicTemplateSPXWeeklyIndexOptionsAlgorithm(QCAlgorithm):
- def initialize(self):
- self.set_start_date(2021, 1, 4)
- self.set_end_date(2021, 1, 10)
- self.set_cash(1000000)
-
- # regular option SPX contracts
- self.spx_options = self.add_index_option("SPX")
- self.spx_options.set_filter(lambda u: (u.strikes(0, 1).expiration(0, 30)))
-
- # weekly option SPX contracts
- spxw = self.add_index_option("SPX", "SPXW")
- # set our strike/expiry filter for this option chain
- spxw.set_filter(lambda u: (u.strikes(0, 1)
- # single week ahead since there are many SPXW contracts and we want to preserve performance
- .expiration(0, 7)
- .include_weeklys()))
-
- self.spxw_option = spxw.symbol
-
- def on_data(self,slice):
- if self.portfolio.invested: return
-
- chain = slice.option_chains.get_value(self.spxw_option)
- if chain is None:
- return
-
- # we sort the contracts to find at the money (ATM) contract with closest expiration
- contracts = sorted(sorted(sorted(chain, \
- key = lambda x: x.expiry), \
- key = lambda x: abs(chain.underlying.price - x.strike)), \
- key = lambda x: x.right, reverse=True)
-
- # if found, buy until it expires
- if len(contracts) == 0: return
- symbol = contracts[0].symbol
- self.market_order(symbol, 1)
-
- def on_order_event(self, order_event):
- self.debug(str(order_event))
diff --git a/fincept-qt/scripts/strategies/BasicTemplateTradableIndexAlgorithm.py b/fincept-qt/scripts/strategies/BasicTemplateTradableIndexAlgorithm.py
deleted file mode 100644
index efd3058cd..000000000
--- a/fincept-qt/scripts/strategies/BasicTemplateTradableIndexAlgorithm.py
+++ /dev/null
@@ -1,28 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-88C8DA85
-# Category: Index
-# Description: Basic Template Tradable Index Algorithm
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-from BasicTemplateIndexAlgorithm import BasicTemplateIndexAlgorithm
-
-class BasicTemplateTradableIndexAlgorithm(BasicTemplateIndexAlgorithm):
- ticket = None
- def initialize(self) -> None:
- super().initialize()
- self.securities[self.spx].is_tradable = True
-
- def on_data(self, data: Slice):
- super().on_data(data)
- if not self.ticket:
- self.ticket = self.market_order(self.spx, 1)
-
- def on_end_of_algorithm(self) -> None:
- if self.ticket.status != OrderStatus.FILLED:
- raise Exception("Index is tradable.")
diff --git a/fincept-qt/scripts/strategies/BlackLittermanPortfolioOptimizationFrameworkAlgorithm.py b/fincept-qt/scripts/strategies/BlackLittermanPortfolioOptimizationFrameworkAlgorithm.py
deleted file mode 100644
index 3aa900259..000000000
--- a/fincept-qt/scripts/strategies/BlackLittermanPortfolioOptimizationFrameworkAlgorithm.py
+++ /dev/null
@@ -1,62 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-8B86F74C
-# Category: Portfolio Management
-# Description: Black-Litterman framework algorithm Uses the HistoricalReturnsAlphaModel and the BlackLittermanPortfolioConstructionM...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-from Alphas.HistoricalReturnsAlphaModel import HistoricalReturnsAlphaModel
-from Portfolio.BlackLittermanOptimizationPortfolioConstructionModel import *
-from Portfolio.UnconstrainedMeanVariancePortfolioOptimizer import UnconstrainedMeanVariancePortfolioOptimizer
-from Risk.NullRiskManagementModel import NullRiskManagementModel
-
-### <summary>
-### Black-Litterman framework algorithm
-### Uses the HistoricalReturnsAlphaModel and the BlackLittermanPortfolioConstructionModel
-### to create an algorithm that rebalances the portfolio according to Black-Litterman portfolio optimization
-### </summary>
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="using quantconnect" />
-### <meta name="tag" content="trading and orders" />
-class BlackLittermanPortfolioOptimizationFrameworkAlgorithm(QCAlgorithm):
- '''Black-Litterman Optimization algorithm.'''
-
- def initialize(self):
-
- # Set requested data resolution
- self.universe_settings.resolution = Resolution.MINUTE
-
- # Order margin value has to have a minimum of 0.5% of Portfolio value, allows filtering out small trades and reduce fees.
- # Commented so regression algorithm is more sensitive
- #self.settings.minimum_order_margin_portfolio_percentage = 0.005
-
- self.set_start_date(2013,10,7) #Set Start Date
- self.set_end_date(2013,10,11) #Set End Date
- self.set_cash(100000) #Set Strategy Cash
-
- self._symbols = [ Symbol.create(x, SecurityType.EQUITY, Market.USA) for x in [ 'AIG', 'BAC', 'IBM', 'SPY' ] ]
-
- optimizer = UnconstrainedMeanVariancePortfolioOptimizer()
-
- # set algorithm framework models
- self.set_universe_selection(CoarseFundamentalUniverseSelectionModel(self.coarse_selector))
- self.set_alpha(HistoricalReturnsAlphaModel(resolution = Resolution.DAILY))
- self.set_portfolio_construction(BlackLittermanOptimizationPortfolioConstructionModel(optimizer = optimizer))
- self.set_execution(ImmediateExecutionModel())
- self.set_risk_management(NullRiskManagementModel())
-
- def coarse_selector(self, coarse):
- # Drops SPY after the 8th
- last = 3 if self.time.day > 8 else len(self._symbols)
-
- return self._symbols[0:last]
-
- def on_order_event(self, order_event):
- if order_event.status == OrderStatus.FILLED:
- self.debug(order_event)
diff --git a/fincept-qt/scripts/strategies/BrokerageActivityEventHandlingAlgorithm.py b/fincept-qt/scripts/strategies/BrokerageActivityEventHandlingAlgorithm.py
deleted file mode 100644
index a6eb31fa4..000000000
--- a/fincept-qt/scripts/strategies/BrokerageActivityEventHandlingAlgorithm.py
+++ /dev/null
@@ -1,54 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-13992977
-# Category: Brokerage
-# Description: Example algorithm to demostrate the event handlers of Brokerage activities
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Example algorithm to demostrate the event handlers of Brokerage activities
-### </summary>
-### <meta name="tag" content="using quantconnect" />
-class BrokerageActivityEventHandlingAlgorithm(QCAlgorithm):
-
- ### <summary>
- ### Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
- ### </summary>
- def initialize(self):
- self.set_start_date(2013, 10, 7)
- self.set_end_date(2013, 10, 11)
- self.set_cash(100000)
-
- self.add_equity("SPY", Resolution.MINUTE)
-
- ### <summary>
- ### on_data event is the primary entry point for your algorithm. Each new data point will be pumped in here.
- ### </summary>
- ### <param name="data">Slice object keyed by symbol containing the stock data</param>
- def on_data(self, data):
- if not self.portfolio.invested:
- self.set_holdings("SPY", 1)
-
- ### <summary>
- ### Brokerage message event handler. This method is called for all types of brokerage messages.
- ### </summary>
- def on_brokerage_message(self, message_event):
- self.debug(f"Brokerage meesage received - {message_event.to_string()}")
-
- ### <summary>
- ### Brokerage disconnected event handler. This method is called when the brokerage connection is lost.
- ### </summary>
- def on_brokerage_disconnect(self):
- self.debug(f"Brokerage disconnected!")
-
- ### <summary>
- ### Brokerage reconnected event handler. This method is called when the brokerage connection is restored after a disconnection.
- ### </summary>
- def on_brokerage_reconnect(self):
- self.debug(f"Brokerage reconnected!")
diff --git a/fincept-qt/scripts/strategies/BrokerageModelAlgorithm.py b/fincept-qt/scripts/strategies/BrokerageModelAlgorithm.py
deleted file mode 100644
index 16d6b807c..000000000
--- a/fincept-qt/scripts/strategies/BrokerageModelAlgorithm.py
+++ /dev/null
@@ -1,70 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-21FCDA65
-# Category: Brokerage
-# Description: Demonstrate the usage of the BrokerageModel property to help improve backtesting accuracy through simulation of a spe...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Demonstrate the usage of the BrokerageModel property to help improve backtesting
-### accuracy through simulation of a specific brokerage's rules around restrictions
-### on submitting orders as well as fee structure.
-### </summary>
-### <meta name="tag" content="trading and orders" />
-### <meta name="tag" content="brokerage models" />
-class BrokerageModelAlgorithm(QCAlgorithm):
- def initialize(self):
-
- self.set_cash(100000) # Set Strategy Cash
- self.set_start_date(2013,10,7) # Set Start Date
- self.set_end_date(2013,10,11) # Set End Date
- self.add_equity("SPY", Resolution.SECOND)
-
- # there's two ways to set your brokerage model. The easiest would be to call
- # self.set_brokerage_model( BrokerageName ) # BrokerageName is an enum
- # self.set_brokerage_model(BrokerageName.INTERACTIVE_BROKERS_BROKERAGE)
- # self.set_brokerage_model(BrokerageName.DEFAULT)
-
- # the other way is to call SetBrokerageModel( IBrokerageModel ) with your
- # own custom model. I've defined a simple extension to the default brokerage
- # model to take into account a requirement to maintain 500 cash in the account at all times
- self.set_brokerage_model(MinimumAccountBalanceBrokerageModel(self,500.00))
- self.last = 1
-
- def on_data(self, slice):
- # Simple buy and hold template
- if not self.portfolio.invested:
- self.set_holdings("SPY", self.last)
- if self.portfolio["SPY"].quantity == 0:
- # each time we fail to purchase we'll decrease our set holdings percentage
- self.debug(str(self.time) + " - Failed to purchase stock")
- self.last *= 0.95
- else:
- self.debug("{} - Purchased Stock @ SetHoldings( {} )".format(self.time, self.last))
-
-
-class MinimumAccountBalanceBrokerageModel(DefaultBrokerageModel):
- '''Custom brokerage model that requires clients to maintain a minimum cash balance'''
- def __init__(self, algorithm, minimum_account_balance):
- self.algorithm = algorithm
- self.minimum_account_balance = minimum_account_balance
-
- def can_submit_order(self,security, order, message):
- '''Prevent orders which would bring the account below a minimum cash balance'''
- message = None
- # we want to model brokerage requirement of minimum_account_balance cash value in account
- order_cost = order.get_value(security)
- cash = self.algorithm.portfolio.cash
- cash_after_order = cash - order_cost
- if cash_after_order < self.minimum_account_balance:
- # return a message describing why we're not allowing this order
- message = BrokerageMessageEvent(BrokerageMessageType.WARNING, "InsufficientRemainingCapital", "Account must maintain a minimum of ${0} USD at all times. Order ID: {1}".format(self.minimum_account_balance, order.id))
- self.algorithm.error(str(message))
- return False
- return True
diff --git a/fincept-qt/scripts/strategies/BubbleAlgorithm.py b/fincept-qt/scripts/strategies/BubbleAlgorithm.py
deleted file mode 100644
index f886df969..000000000
--- a/fincept-qt/scripts/strategies/BubbleAlgorithm.py
+++ /dev/null
@@ -1,47 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-181E0A50
-# Category: General Strategy
-# Description: Bubble detection strategy using price-to-SMA ratio. Identifies
-# potential price bubbles when price exceeds 1.05x the 50-day SMA. Takes
-# profit at 1.08x ratio, exits if price falls back below SMA.
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-class BubbleAlgorithm(QCAlgorithm):
- """Bubble/momentum strategy using price-to-SMA ratio."""
-
- def initialize(self):
- self.set_start_date(2023, 1, 1)
- self.set_end_date(2024, 1, 1)
- self.set_cash(100000)
-
- self.symbol = "SPY"
- self.add_equity(self.symbol, Resolution.DAILY)
-
- self._sma50 = self.sma(self.symbol, 50, Resolution.DAILY)
- self._sma200 = self.sma(self.symbol, 200, Resolution.DAILY)
-
- def on_data(self, data):
- if not self._sma50.is_ready:
- return
- if self.symbol not in data:
- return
-
- price = data[self.symbol].close
- sma50 = self._sma50.current.value
- ratio = price / sma50 if sma50 > 0 else 1
-
- if not self.portfolio.invested:
- # Enter on moderate uptrend (not too extended)
- if 1.0 < ratio < 1.05:
- self.set_holdings(self.symbol, 1)
- else:
- # Take profit if over-extended or stop if under SMA
- if ratio > 1.08 or price < sma50:
- self.liquidate()
diff --git a/fincept-qt/scripts/strategies/BybitCryptoFuturesRegressionAlgorithm.py b/fincept-qt/scripts/strategies/BybitCryptoFuturesRegressionAlgorithm.py
deleted file mode 100644
index 77348c1a3..000000000
--- a/fincept-qt/scripts/strategies/BybitCryptoFuturesRegressionAlgorithm.py
+++ /dev/null
@@ -1,139 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-C4535414
-# Category: Futures
-# Description: Algorithm demonstrating and ensuring that Bybit crypto futures brokerage model works as expected
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from cmath import isclose
-from AlgorithmImports import *
-
-### <summary>
-### Algorithm demonstrating and ensuring that Bybit crypto futures brokerage model works as expected
-### </summary>
-class BybitCryptoFuturesRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self):
- '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
-
- self.set_start_date(2022, 12, 13)
- self.set_end_date(2022, 12, 13)
-
- # Set strategy cash (USD)
- self.set_cash(100000)
-
- self.set_brokerage_model(BrokerageName.BYBIT, AccountType.MARGIN)
-
- # Translate lines 44-59 to Python:
-
- self.add_crypto("BTCUSDT", Resolution.MINUTE)
-
- self.btc_usdt = self.add_crypto_future("BTCUSDT", Resolution.MINUTE)
- self.btc_usd = self.add_crypto_future("BTCUSD", Resolution.MINUTE)
-
- # create two moving averages
- self.fast = self.ema(self.btc_usdt.symbol, 30, Resolution.MINUTE)
- self.slow = self.ema(self.btc_usdt.symbol, 60, Resolution.MINUTE)
-
- self.interest_per_symbol = {}
- self.interest_per_symbol[self.btc_usd.symbol] = 0
- self.interest_per_symbol[self.btc_usdt.symbol] = 0
-
- # the amount of USDT we need to hold to trade 'BTCUSDT'
- self.btc_usdt.quote_currency.set_amount(200)
- # the amount of BTC we need to hold to trade 'BTCUSD'
- self.btc_usd.base_currency.set_amount(0.005)
-
- def on_data(self, data):
- interest_rates = data.get[MarginInterestRate]()
- for interest_rate in interest_rates:
- self.interest_per_symbol[interest_rate.key] += 1
-
- cached_interest_rate = self.securities[interest_rate.key].cache.get_data[MarginInterestRate]()
- if cached_interest_rate != interest_rate.value:
- raise Exception(f"Unexpected cached margin interest rate for {interest_rate.key}!")
-
- if not self.slow.is_ready:
- return
-
- if self.fast > self.slow:
- if not self.portfolio.invested and self.transactions.orders_count == 0:
- ticket = self.buy(self.btc_usd.symbol, 1000)
- if ticket.status != OrderStatus.INVALID:
- raise Exception(f"Unexpected valid order {ticket}, should fail due to margin not sufficient")
-
- self.buy(self.btc_usd.symbol, 100)
-
- margin_used = self.portfolio.total_margin_used
- btc_usd_holdings = self.btc_usd.holdings
-
- # Coin futures value is 100 USD
- holdings_value_btc_usd = 100
- if abs(btc_usd_holdings.total_sale_volume - holdings_value_btc_usd) > 1:
- raise Exception(f"Unexpected TotalSaleVolume {btc_usd_holdings.total_sale_volume}")
- if abs(btc_usd_holdings.absolute_holdings_cost - holdings_value_btc_usd) > 1:
- raise Exception(f"Unexpected holdings cost {btc_usd_holdings.holdings_cost}")
- # margin used is based on the maintenance rate
- if (abs(btc_usd_holdings.absolute_holdings_cost * 0.05 - margin_used) > 1 or
- not isclose(self.btc_usd.buying_power_model.get_maintenance_margin(MaintenanceMarginParameters.for_current_holdings(self.btc_usd)).value, margin_used)):
- raise Exception(f"Unexpected margin used {margin_used}")
-
- self.buy(self.btc_usdt.symbol, 0.01)
-
- margin_used = self.portfolio.total_margin_used - margin_used
- btc_usdt_holdings = self.btc_usdt.holdings
-
- # USDT futures value is based on it's price
- holdings_value_usdt = self.btc_usdt.price * self.btc_usdt.symbol_properties.contract_multiplier * 0.01
-
- if abs(btc_usdt_holdings.total_sale_volume - holdings_value_usdt) > 1:
- raise Exception(f"Unexpected TotalSaleVolume {btc_usdt_holdings.total_sale_volume}")
- if abs(btc_usdt_holdings.absolute_holdings_cost - holdings_value_usdt) > 1:
- raise Exception(f"Unexpected holdings cost {btc_usdt_holdings.holdings_cost}")
- if (abs(btc_usdt_holdings.absolute_holdings_cost * 0.05 - margin_used) > 1 or
- not isclose(self.btc_usdt.buying_power_model.get_maintenance_margin(MaintenanceMarginParameters.for_current_holdings(self.btc_usdt)).value, margin_used)):
- raise Exception(f"Unexpected margin used {margin_used}")
-
- # position just opened should be just spread here
- unrealized_profit = self.portfolio.total_unrealized_profit
- if (5 - abs(unrealized_profit)) < 0:
- raise Exception(f"Unexpected TotalUnrealizedProfit {self.portfolio.total_unrealized_profit}")
-
- if self.portfolio.total_profit != 0:
- raise Exception(f"Unexpected TotalProfit {self.portfolio.total_profit}")
- # let's revert our position
- elif self.transactions.orders_count == 3:
- self.sell(self.btc_usd.symbol, 300)
-
- btc_usd_holdings = self.btc_usd.holdings
- if abs(btc_usd_holdings.absolute_holdings_cost - 100 * 2) > 1:
- raise Exception(f"Unexpected holdings cost {btc_usd_holdings.holdings_cost}")
-
- self.sell(self.btc_usdt.symbol, 0.03)
-
- # USDT futures value is based on it's price
- holdings_value_usdt = self.btc_usdt.price * self.btc_usdt.symbol_properties.contract_multiplier * 0.02
- if abs(self.btc_usdt.holdings.absolute_holdings_cost - holdings_value_usdt) > 1:
- raise Exception(f"Unexpected holdings cost {self.btc_usdt.holdings.holdings_cost}")
-
- # position just opened should be just spread here
- profit = self.portfolio.total_unrealized_profit
- if (5 - abs(profit)) < 0:
- raise Exception(f"Unexpected TotalUnrealizedProfit {self.portfolio.total_unrealized_profit}")
- # we barely did any difference on the previous trade
- if (5 - abs(self.portfolio.total_profit)) < 0:
- raise Exception(f"Unexpected TotalProfit {self.portfolio.total_profit}")
-
- def on_order_event(self, order_event):
- self.debug("{} {}".format(self.time, order_event.to_string()))
-
- def on_end_of_algorithm(self):
- self.log(f"{self.time} - TotalPortfolioValue: {self.portfolio.total_portfolio_value}")
- self.log(f"{self.time} - CashBook: {self.portfolio.cash_book}")
-
- if any(x == 0 for x in self.interest_per_symbol.values()):
- raise Exception("Expected interest rate data for all symbols")
diff --git a/fincept-qt/scripts/strategies/BybitCryptoRegressionAlgorithm.py b/fincept-qt/scripts/strategies/BybitCryptoRegressionAlgorithm.py
deleted file mode 100644
index d64693faa..000000000
--- a/fincept-qt/scripts/strategies/BybitCryptoRegressionAlgorithm.py
+++ /dev/null
@@ -1,78 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-8205EE4A
-# Category: Crypto
-# Description: Algorithm demonstrating and ensuring that Bybit crypto brokerage model works as expected
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Algorithm demonstrating and ensuring that Bybit crypto brokerage model works as expected
-### </summary>
-class BybitCryptoRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self):
- '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
-
- self.set_start_date(2022, 12, 13)
- self.set_end_date(2022, 12, 13)
-
- # Set account currency (USDT)
- self.set_account_currency("USDT")
-
- # Set strategy cash (USD)
- self.set_cash(100000)
-
- # Add some coin as initial holdings
- # When connected to a real brokerage, the amount specified in SetCash
- # will be replaced with the amount in your actual account.
- self.set_cash("BTC", 1)
-
- self.set_brokerage_model(BrokerageName.BYBIT, AccountType.CASH)
-
- self.btc_usdt = self.add_crypto("BTCUSDT").symbol
-
- # create two moving averages
- self.fast = self.ema(self.btc_usdt, 30, Resolution.MINUTE)
- self.slow = self.ema(self.btc_usdt, 60, Resolution.MINUTE)
-
- self.liquidated = False
-
- def on_data(self, data):
- if self.portfolio.cash_book["USDT"].conversion_rate == 0 or self.portfolio.cash_book["BTC"].conversion_rate == 0:
- self.log(f"USDT conversion rate: {self.portfolio.cash_book['USDT'].conversion_rate}")
- self.log(f"BTC conversion rate: {self.portfolio.cash_book['BTC'].conversion_rate}")
-
- raise Exception("Conversion rate is 0")
-
- if not self.slow.is_ready:
- return
-
- btc_amount = self.portfolio.cash_book["BTC"].amount
- if self.fast > self.slow:
- if btc_amount == 1 and not self.liquidated:
- self.buy(self.btc_usdt, 1)
- else:
- if btc_amount > 1:
- self.liquidate(self.btc_usdt)
- self.liquidated = True
- elif btc_amount > 0 and self.liquidated and len(self.transactions.get_open_orders()) == 0:
- # Place a limit order to sell our initial BTC holdings at 1% above the current price
- limit_price = round(self.securities[self.btc_usdt].price * 1.01, 2)
- self.limit_order(self.btc_usdt, -btc_amount, limit_price)
-
- def on_order_event(self, order_event):
- self.debug("{} {}".format(self.time, order_event.to_string()))
-
- def on_end_of_algorithm(self):
- self.log(f"{self.time} - TotalPortfolioValue: {self.portfolio.total_portfolio_value}")
- self.log(f"{self.time} - CashBook: {self.portfolio.cash_book}")
-
- btc_amount = self.portfolio.cash_book["BTC"].amount
- if btc_amount > 0:
- raise Exception(f"BTC holdings should be zero at the end of the algorithm, but was {btc_amount}")
diff --git a/fincept-qt/scripts/strategies/BybitCustomDataCryptoRegressionAlgorithm.py b/fincept-qt/scripts/strategies/BybitCustomDataCryptoRegressionAlgorithm.py
deleted file mode 100644
index 9abab6506..000000000
--- a/fincept-qt/scripts/strategies/BybitCustomDataCryptoRegressionAlgorithm.py
+++ /dev/null
@@ -1,76 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-E8BBF79A
-# Category: Crypto
-# Description: Algorithm demonstrating and ensuring that Bybit crypto brokerage model works as expected with custom data types
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-import datetime
-
-### <summary>
-### Algorithm demonstrating and ensuring that Bybit crypto brokerage model works as expected with custom data types
-### </summary>
-class BybitCustomDataCryptoRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2022, 12, 13)
- self.set_end_date(2022, 12, 13)
-
- self.set_account_currency("USDT")
- self.set_cash(100000)
-
- self.set_brokerage_model(BrokerageName.BYBIT, AccountType.CASH)
-
- symbol = self.add_crypto("BTCUSDT").symbol
- self.btc_usdt = self.add_data(CustomCryptoData, symbol, Resolution.MINUTE).symbol
-
- # create two moving averages
- self.fast = self.ema(self.btc_usdt, 30, Resolution.MINUTE)
- self.slow = self.ema(self.btc_usdt, 60, Resolution.MINUTE)
-
- def on_data(self, data):
- if not self.slow.is_ready:
- return
-
- if self.fast.current.value > self.slow.current.value:
- if self.transactions.orders_count == 0:
- self.buy(self.btc_usdt, 1)
- else:
- if self.transactions.orders_count == 1:
- self.liquidate(self.btc_usdt)
-
- def on_order_event(self, order_event):
- self.debug(f"{self.time} {order_event}")
-
-class CustomCryptoData(PythonData):
- def get_source(self, config, date, is_live_mode):
- tick_type_string = Extensions.tick_type_to_lower(config.tick_type)
- formatted_date = date.strftime("%Y%m%d")
- source = os.path.join(Globals.DataFolder, "crypto", "bybit", "minute",
- config.symbol.value.lower(), f"{formatted_date}_{tick_type_string}.zip")
-
- return SubscriptionDataSource(source, SubscriptionTransportMedium.LOCAL_FILE, FileFormat.CSV)
-
- def reader(self, config, line, date, is_live_mode):
- csv = line.split(',')
-
- data = CustomCryptoData()
- data.symbol = config.symbol
-
- data_datetime = datetime.datetime.combine(date.date(), datetime.time()) + timedelta(milliseconds=int(csv[0]))
- data.time = Extensions.convert_to(data_datetime, config.data_time_zone, config.exchange_time_zone)
- data.end_time = data.time + timedelta(minutes=1)
-
- data["Open"] = float(csv[1])
- data["High"] = float(csv[2])
- data["Low"] = float(csv[3])
- data["Close"] = float(csv[4])
- data["Volume"] = float(csv[5])
- data.value = float(csv[4])
-
- return data
diff --git a/fincept-qt/scripts/strategies/CallbackCommandRegressionAlgorithm.py b/fincept-qt/scripts/strategies/CallbackCommandRegressionAlgorithm.py
deleted file mode 100644
index d0202248c..000000000
--- a/fincept-qt/scripts/strategies/CallbackCommandRegressionAlgorithm.py
+++ /dev/null
@@ -1,98 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-E8875612
-# Category: Regression Test
-# Description: Regression algorithm asserting the behavior of different callback commands call
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-class InvalidCommand():
- variable = 10
-
-class VoidCommand():
- quantity = 0
- target = []
- parameters = {}
- targettime = None
-
- def run(self, algo: QCAlgorithm) -> bool | None:
- if not self.targettime or self.targettime != algo.time:
- return
- tag = self.parameters["tag"]
- algo.order(self.target[0], self.get_quantity(), tag=tag)
-
- def get_quantity(self):
- return self.quantity
-
-class BoolCommand(Command):
- something_else = {}
- array_test = []
- result = False
-
- def run(self, algo: QCAlgorithm) -> bool | None:
- trade_ibm = self.my_custom_method()
- if trade_ibm:
- algo.debug(f"BoolCommand.run: {str(self)}")
- algo.buy("IBM", 1)
- return trade_ibm
-
- def my_custom_method(self):
- return self.result
-
-### <summary>
-### Regression algorithm asserting the behavior of different callback commands call
-### </summary>
-class CallbackCommandRegressionAlgorithm(QCAlgorithm):
- def initialize(self):
- '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
-
- self.set_start_date(2013, 10, 7)
- self.set_end_date(2013, 10, 11)
-
- self.add_equity("SPY")
- self.add_equity("IBM")
- self.add_equity("BAC")
-
- self.add_command(VoidCommand)
- self.add_command(BoolCommand)
-
- threw_exception = False
- try:
- self.add_command(InvalidCommand)
- except:
- threw_exception = True
- if not threw_exception:
- raise ValueError('InvalidCommand did not throw!')
-
- bool_command = BoolCommand()
- bool_command.result = True
- bool_command.something_else = { "Property": 10 }
- bool_command.array_test = [ "SPY", "BTCUSD" ]
- link = self.link(bool_command)
- if "&command[array_test][0]=SPY&command[array_test][1]=BTCUSD&command[result]=True&command[something_else][Property]=10&command[$type]=BoolCommand" not in link:
- raise ValueError(f'Invalid link was generated! {link}')
-
- potential_command = VoidCommand()
- potential_command.target = [ "BAC" ]
- potential_command.quantity = 10
- potential_command.parameters = { "tag": "Signal X" }
-
- command_link = self.link(potential_command)
- if "command[parameters][tag]=Signal+X&command[quantity]=10&command[target][0]=BAC&command[$type]=VoidCommand" not in command_link:
- raise ValueError(f'Invalid link was generated! {command_link}')
- self.notify.email("email@address", "Trade Command Event", f"Signal X trade\nFollow link to trigger: {command_link}")
-
- untyped_command_link = self.link({ "symbol": "SPY", "parameters": { "quantity": 10 } })
- if "&command[symbol]=SPY&command[parameters][quantity]=10" not in untyped_command_link:
- raise ValueError(f'Invalid link was generated! {untyped_command_link}')
- self.notify.email("email@address", "Untyped Command Event", f"Signal Y trade\nFollow link to trigger: {untyped_command_link}")
-
- def on_command(self, data):
- self.debug(f"on_command: {str(data)}")
- self.buy(data.symbol, data.parameters["quantity"])
- return True # False, None
diff --git a/fincept-qt/scripts/strategies/CanLiquidateWithOrderPropertiesRegressionAlgorithm.py b/fincept-qt/scripts/strategies/CanLiquidateWithOrderPropertiesRegressionAlgorithm.py
deleted file mode 100644
index 5499491c3..000000000
--- a/fincept-qt/scripts/strategies/CanLiquidateWithOrderPropertiesRegressionAlgorithm.py
+++ /dev/null
@@ -1,37 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-D8FB9470
-# Category: Regression Test
-# Description: Regression algorithm to test we can liquidate our portfolio holdings using order properties
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Regression algorithm to test we can liquidate our portfolio holdings using order properties
-### </summary>
-class CanLiquidateWithOrderPropertiesRegressionAlgorithm(QCAlgorithm):
- def initialize(self):
- self.set_start_date(2014, 6, 5)
- self.set_end_date(2014, 6, 6)
- self.set_cash(100000)
-
- self.open_exchange = datetime(2014, 6, 6, 10, 0, 0)
- self.close_exchange = datetime(2014, 6, 6, 16, 0, 0)
- self.add_equity("AAPL", resolution = Resolution.MINUTE)
-
- def on_data(self, slice):
- if self.time > self.open_exchange and self.time < self.close_exchange:
- if not self.portfolio.invested:
- self.market_order("AAPL", 10)
- else:
- order_properties = OrderProperties()
- order_properties.time_in_force = TimeInForce.DAY
- tickets = self.liquidate(asynchronous = True, order_properties = order_properties)
- for ticket in tickets:
- if ticket.SubmitRequest.OrderProperties.TimeInForce != TimeInForce.DAY:
- raise Exception(f"The TimeInForce for all orders should be daily, but it was {ticket.SubmitRequest.OrderProperties.TimeInForce}")
diff --git a/fincept-qt/scripts/strategies/CapmAlphaRankingFrameworkAlgorithm.py b/fincept-qt/scripts/strategies/CapmAlphaRankingFrameworkAlgorithm.py
deleted file mode 100644
index 54ba81b42..000000000
--- a/fincept-qt/scripts/strategies/CapmAlphaRankingFrameworkAlgorithm.py
+++ /dev/null
@@ -1,101 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-65D25230
-# Category: Alpha Model
-# Description: CapmAlphaRankingFrameworkAlgorithm: example of custom scheduled universe selection model Universe Selection inspired ...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### CapmAlphaRankingFrameworkAlgorithm: example of custom scheduled universe selection model
-### Universe Selection inspired by https://www.quantconnect.com/tutorials/strategy-library/capm-alpha-ranking-strategy-on-dow-30-companies
-### </summary>
-class CapmAlphaRankingFrameworkAlgorithm(QCAlgorithm):
- '''CapmAlphaRankingFrameworkAlgorithm: example of custom scheduled universe selection model'''
-
- def initialize(self):
- ''' Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
-
- # Set requested data resolution
- self.universe_settings.resolution = Resolution.MINUTE
-
- self.set_start_date(2016, 1, 1) #Set Start Date
- self.set_end_date(2017, 1, 1) #Set End Date
- self.set_cash(100000) #Set Strategy Cash
-
- # set algorithm framework models
- self.set_universe_selection(CapmAlphaRankingUniverseSelectionModel())
- self.set_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(1), 0.025, None))
- self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())
- self.set_execution(ImmediateExecutionModel())
- self.set_risk_management(MaximumDrawdownPercentPerSecurity(0.01))
-
-class CapmAlphaRankingUniverseSelectionModel(UniverseSelectionModel):
- '''This universe selection model picks stocks with the highest alpha: interception of the linear regression against a benchmark.'''
-
- period = 21
- benchmark = "SPY"
-
- # Symbols of Dow 30 companies.
- symbols = [Symbol.create(x, SecurityType.EQUITY, Market.USA)
- for x in ["AAPL", "AXP", "BA", "CAT", "CSCO", "CVX", "DD", "DIS", "GE", "GS",
- "HD", "IBM", "INTC", "JPM", "KO", "MCD", "MMM", "MRK", "MSFT",
- "NKE","PFE", "PG", "TRV", "UNH", "UTX", "V", "VZ", "WMT", "XOM"]]
-
- def create_universes(self, algorithm):
-
- # Adds the benchmark to the user defined universe
- benchmark = algorithm.add_equity(self.benchmark, Resolution.DAILY)
-
- # Defines a schedule universe that fires after market open when the month starts
- return [ ScheduledUniverse(
- benchmark.exchange.time_zone,
- algorithm.date_rules.month_start(self.benchmark),
- algorithm.time_rules.after_market_open(self.benchmark),
- lambda datetime: self.select_pair(algorithm, datetime),
- algorithm.universe_settings,
- algorithm.security_initializer)]
-
- def select_pair(self, algorithm, date):
- '''Selects the pair (two stocks) with the highest alpha'''
- dictionary = dict()
- benchmark = self._get_returns(algorithm, self.benchmark)
- ones = np.ones(len(benchmark))
-
- for symbol in self._symbols:
- prices = self._get_returns(algorithm, symbol)
- if prices is None: continue
- A = np.vstack([prices, ones]).T
-
- # Calculate the Least-Square fitting to the returns of a given symbol and the benchmark
- ols = np.linalg.lstsq(A, benchmark)[0]
- dictionary[symbol] = ols[1]
-
- # Returns the top 2 highest alphas
- ordered_dictionary = sorted(dictionary.items(), key= lambda x: x[1], reverse=True)
- return [x[0] for x in ordered_dictionary[:2]]
-
- def _get_returns(self, algorithm, symbol):
-
- history = algorithm.history([symbol], self.period, Resolution.DAILY)
- if history.empty: return None
-
- window = RollingWindow[float](self.period)
- rate_of_change = RateOfChange(1)
-
- def roc_updated(s, item):
- window.add(item.value)
-
- rate_of_change.updated += roc_updated
-
- history = history.close.reset_index(level=0, drop=True).iteritems()
-
- for time, value in history:
- rate_of_change.update(time, value)
-
- return [ x for x in window]
diff --git a/fincept-qt/scripts/strategies/ClassicRangeConsolidatorAlgorithm.py b/fincept-qt/scripts/strategies/ClassicRangeConsolidatorAlgorithm.py
deleted file mode 100644
index 481c2e32a..000000000
--- a/fincept-qt/scripts/strategies/ClassicRangeConsolidatorAlgorithm.py
+++ /dev/null
@@ -1,27 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-F172EB67
-# Category: Data Consolidation
-# Description: Example algorithm of how to use ClassicRangeConsolidator
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-from RangeConsolidatorAlgorithm import RangeConsolidatorAlgorithm
-
-### <summary>
-### Example algorithm of how to use ClassicRangeConsolidator
-### </summary>
-class ClassicRangeConsolidatorAlgorithm(RangeConsolidatorAlgorithm):
- def create_range_consolidator(self):
- return ClassicRangeConsolidator(self.get_range())
-
- def on_data_consolidated(self, sender, range_bar):
- super().on_data_consolidated(sender, range_bar)
-
- if range_bar.volume == 0:
- raise Exception("All RangeBar's should have non-zero volume, but this doesn't")
-
diff --git a/fincept-qt/scripts/strategies/ClassicRangeConsolidatorWithTickAlgorithm.py b/fincept-qt/scripts/strategies/ClassicRangeConsolidatorWithTickAlgorithm.py
deleted file mode 100644
index 6990a01a4..000000000
--- a/fincept-qt/scripts/strategies/ClassicRangeConsolidatorWithTickAlgorithm.py
+++ /dev/null
@@ -1,26 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-5407C44C
-# Category: Data Consolidation
-# Description: Example algorithm of how to use ClassicRangeConsolidator with Tick resolution
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-from RangeConsolidatorWithTickAlgorithm import RangeConsolidatorWithTickAlgorithm
-
-### <summary>
-### Example algorithm of how to use ClassicRangeConsolidator with Tick resolution
-### </summary>
-class ClassicRangeConsolidatorWithTickAlgorithm(RangeConsolidatorWithTickAlgorithm):
- def create_range_consolidator(self):
- return ClassicRangeConsolidator(self.get_range())
-
- def on_data_consolidated(self, sender, range_bar):
- super().on_data_consolidated(sender, range_bar)
-
- if range_bar.volume == 0:
- raise Exception("All RangeBar's should have non-zero volume, but this doesn't")
diff --git a/fincept-qt/scripts/strategies/ClassicRenkoConsolidatorAlgorithm.py b/fincept-qt/scripts/strategies/ClassicRenkoConsolidatorAlgorithm.py
deleted file mode 100644
index 72a809d58..000000000
--- a/fincept-qt/scripts/strategies/ClassicRenkoConsolidatorAlgorithm.py
+++ /dev/null
@@ -1,69 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-D909F7DF
-# Category: Data Consolidation
-# Description: Demonstration of how to initialize and use the Classic RenkoConsolidator
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Demonstration of how to initialize and use the Classic RenkoConsolidator
-### </summary>
-### <meta name="tag" content="renko" />
-### <meta name="tag" content="indicators" />
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="consolidating data" />
-class ClassicRenkoConsolidatorAlgorithm(QCAlgorithm):
- '''Demonstration of how to initialize and use the RenkoConsolidator'''
-
- def initialize(self):
-
- self.set_start_date(2012, 1, 1)
- self.set_end_date(2013, 1, 1)
-
- self.add_equity("SPY", Resolution.DAILY)
-
- # this is the simple constructor that will perform the
- # renko logic to the Value property of the data it receives.
-
- # break SPY into $2.5 renko bricks and send that data to our 'OnRenkoBar' method
- renko_close = ClassicRenkoConsolidator(2.5)
- renko_close.data_consolidated += self.handle_renko_close
- self.subscription_manager.add_consolidator("SPY", renko_close)
-
- # this is the full constructor that can accept a value selector and a volume selector
- # this allows us to perform the renko logic on values other than Close, even computed values!
-
- # break SPY into (2*o + h + l + 3*c)/7
- renko7bar = ClassicRenkoConsolidator(2.5, lambda x: (2 * x.open + x.high + x.low + 3 * x.close) / 7, lambda x: x.volume)
- renko7bar.data_consolidated += self.handle_renko7_bar
- self.subscription_manager.add_consolidator("SPY", renko7bar)
-
-
- # We're doing our analysis in the on_renko_bar method, but the framework verifies that this method exists, so we define it.
- def on_data(self, data):
- pass
-
-
- def handle_renko_close(self, sender, data):
- '''This function is called by our renko_close consolidator defined in Initialize()
- Args:
- data: The new renko bar produced by the consolidator'''
- if not self.portfolio.invested:
- self.set_holdings(data.symbol, 1)
-
- self.log(f"CLOSE - {data.time} - {data.open} {data.close}")
-
-
- def handle_renko7_bar(self, sender, data):
- '''This function is called by our renko7bar consolidator defined in Initialize()
- Args:
- data: The new renko bar produced by the consolidator'''
- if self.portfolio.invested:
- self.liquidate(data.symbol)
- self.log(f"7BAR - {data.time} - {data.open} {data.close}")
diff --git a/fincept-qt/scripts/strategies/CoarseFineAsyncUniverseRegressionAlgorithm.py b/fincept-qt/scripts/strategies/CoarseFineAsyncUniverseRegressionAlgorithm.py
deleted file mode 100644
index cc0e1ee7e..000000000
--- a/fincept-qt/scripts/strategies/CoarseFineAsyncUniverseRegressionAlgorithm.py
+++ /dev/null
@@ -1,44 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-A0A879A8
-# Category: Universe Selection
-# Description: Regression algorithm asserting that using separate coarse & fine selection with async universe settings is not allowed
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Regression algorithm asserting that using separate coarse & fine selection with async universe settings is not allowed
-### </summary>
-class CoarseFineAsyncUniverseRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self):
- '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
-
- self.set_start_date(2013, 10, 7)
- self.set_end_date(2013, 10, 11)
-
- self.universe_settings.asynchronous = True
-
- threw_exception = False
- try:
- self.add_universe(self.coarse_selection_function, self.fine_selection_function)
- except:
- # expected
- threw_exception = True
- pass
-
- if not threw_exception:
- raise ValueError("Expected exception to be thrown for AddUniverse")
-
- self.set_universe_selection(FineFundamentalUniverseSelectionModel(self.coarse_selection_function, self.fine_selection_function))
-
- def coarse_selection_function(self, coarse):
- return []
-
- def fine_selection_function(self, fine):
- return []
diff --git a/fincept-qt/scripts/strategies/CoarseFineFundamentalComboAlgorithm.py b/fincept-qt/scripts/strategies/CoarseFineFundamentalComboAlgorithm.py
deleted file mode 100644
index 1acc6ef15..000000000
--- a/fincept-qt/scripts/strategies/CoarseFineFundamentalComboAlgorithm.py
+++ /dev/null
@@ -1,78 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-CE80899F
-# Category: General Strategy
-# Description: Demonstration of using coarse and fine universe selection together to filter down a smaller universe of stocks
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-from System.Collections.Generic import List
-
-### <summary>
-### Demonstration of using coarse and fine universe selection together to filter down a smaller universe of stocks.
-### </summary>
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="universes" />
-### <meta name="tag" content="coarse universes" />
-### <meta name="tag" content="fine universes" />
-class CoarseFineFundamentalComboAlgorithm(QCAlgorithm):
-
- def initialize(self):
- '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
-
- self.set_start_date(2014,1,1) #Set Start Date
- self.set_end_date(2015,1,1) #Set End Date
- self.set_cash(50000) #Set Strategy Cash
-
- # what resolution should the data *added* to the universe be?
- self.universe_settings.resolution = Resolution.DAILY
-
- # this add universe method accepts two parameters:
- # - coarse selection function: accepts an IEnumerable<CoarseFundamental> and returns an IEnumerable<Symbol>
- # - fine selection function: accepts an IEnumerable<FineFundamental> and returns an IEnumerable<Symbol>
- self.add_universe(self.coarse_selection_function, self.fine_selection_function)
-
- self.__number_of_symbols = 5
- self.__number_of_symbols_fine = 2
- self._changes = None
-
-
- # sort the data by daily dollar volume and take the top 'NumberOfSymbols'
- def coarse_selection_function(self, coarse):
- # sort descending by daily dollar volume
- sorted_by_dollar_volume = sorted(coarse, key=lambda x: x.dollar_volume, reverse=True)
-
- # return the symbol objects of the top entries from our sorted collection
- return [ x.symbol for x in sorted_by_dollar_volume[:self.__number_of_symbols] ]
-
- # sort the data by P/E ratio and take the top 'NumberOfSymbolsFine'
- def fine_selection_function(self, fine):
- # sort descending by P/E ratio
- sorted_by_pe_ratio = sorted(fine, key=lambda x: x.valuation_ratios.pe_ratio, reverse=True)
-
- # take the top entries from our sorted collection
- return [ x.symbol for x in sorted_by_pe_ratio[:self.__number_of_symbols_fine] ]
-
- def on_data(self, data):
- # if we have no changes, do nothing
- if self._changes is None: return
-
- # liquidate removed securities
- for security in self._changes.removed_securities:
- if security.invested:
- self.liquidate(security.symbol)
-
- # we want 20% allocation in each security in our universe
- for security in self._changes.added_securities:
- self.set_holdings(security.symbol, 0.2)
-
- self._changes = None
-
-
- # this event fires whenever we have changes to our universe
- def on_securities_changed(self, changes):
- self._changes = changes
diff --git a/fincept-qt/scripts/strategies/CoarseFineFundamentalRegressionAlgorithm.py b/fincept-qt/scripts/strategies/CoarseFineFundamentalRegressionAlgorithm.py
deleted file mode 100644
index 0048f23f0..000000000
--- a/fincept-qt/scripts/strategies/CoarseFineFundamentalRegressionAlgorithm.py
+++ /dev/null
@@ -1,76 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-BF06E7EB
-# Category: Regression Test
-# Description: Demonstration of how to define a universe as a combination of use the coarse fundamental data and fine fundamental data
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Demonstration of how to define a universe as a combination of use the coarse fundamental data and fine fundamental data
-### </summary>
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="universes" />
-### <meta name="tag" content="coarse universes" />
-### <meta name="tag" content="regression test" />
-class CoarseFineFundamentalRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2014,3,24) #Set Start Date
- self.set_end_date(2014,4,7) #Set End Date
- self.set_cash(50000) #Set Strategy Cash
-
- self.universe_settings.resolution = Resolution.DAILY
-
- # this add universe method accepts two parameters:
- # - coarse selection function: accepts an List[CoarseFundamental] and returns an List[Symbol]
- # - fine selection function: accepts an List[FineFundamental] and returns an List[Symbol]
- self.add_universe(self.coarse_selection_function, self.fine_selection_function)
-
- self.changes = None
- self.number_of_symbols_fine = 2
-
- # return a list of three fixed symbol objects
- def coarse_selection_function(self, coarse):
- tickers = [ "GOOG", "BAC", "SPY" ]
-
- if self.time.date() < date(2014, 4, 1):
- tickers = [ "AAPL", "AIG", "IBM" ]
-
- return [ Symbol.create(x, SecurityType.EQUITY, Market.USA) for x in tickers ]
-
-
- # sort the data by market capitalization and take the top 'number_of_symbols_fine'
- def fine_selection_function(self, fine):
- # sort descending by market capitalization
- sorted_by_market_cap = sorted(fine, key=lambda x: x.market_cap, reverse=True)
-
- # take the top entries from our sorted collection
- return [ x.symbol for x in sorted_by_market_cap[:self.number_of_symbols_fine] ]
-
- def on_data(self, data):
- # if we have no changes, do nothing
- if self.changes is None: return
-
- # liquidate removed securities
- for security in self.changes.removed_securities:
- if security.invested:
- self.liquidate(security.symbol)
- self.debug("Liquidated Stock: " + str(security.symbol.value))
-
- # we want 50% allocation in each security in our universe
- for security in self.changes.added_securities:
- if (security.fundamentals.earning_ratios.equity_per_share_growth.one_year > 0.25):
- self.set_holdings(security.symbol, 0.5)
- self.debug("Purchased Stock: " + str(security.symbol.value))
-
- self.changes = None
-
- # this event fires whenever we have changes to our universe
- def on_securities_changed(self, changes):
- self.changes = changes
diff --git a/fincept-qt/scripts/strategies/CoarseFineOptionUniverseChainRegressionAlgorithm.py b/fincept-qt/scripts/strategies/CoarseFineOptionUniverseChainRegressionAlgorithm.py
deleted file mode 100644
index 84673a743..000000000
--- a/fincept-qt/scripts/strategies/CoarseFineOptionUniverseChainRegressionAlgorithm.py
+++ /dev/null
@@ -1,92 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-5542D978
-# Category: Options
-# Description: Demonstration of how to chain a coarse and fine universe selection with an option chain universe selection model that...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Demonstration of how to chain a coarse and fine universe selection with an option chain universe selection model
-### that will add and remove an'OptionChainUniverse' for each symbol selected on fine
-### </summary>
-class CoarseFineOptionUniverseChainRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self):
- '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
-
- self.set_start_date(2014,6,4)
- # TWX is selected the 4th and 5th and aapl after that.
- # If the algo ends on the 6th, TWX subscriptions will not be removed before OnEndOfAlgorithm is called:
- # - 6th: AAPL is selected, TWX is removed but subscriptions are not removed because the securities are invested.
- # - TWX and its options are liquidated.
- # - 7th: Since options universe selection is daily now, TWX subscriptions are removed the next day (7th)
- self.set_end_date(2014,6,7)
-
- self.universe_settings.resolution = Resolution.MINUTE
- self._twx = Symbol.create("TWX", SecurityType.EQUITY, Market.USA)
- self._aapl = Symbol.create("AAPL", SecurityType.EQUITY, Market.USA)
- self._last_equity_added = None
- self._changes = None
- self._option_count = 0
-
- universe = self.add_universe(self.coarse_selection_function, self.fine_selection_function)
-
- self.add_universe_options(universe, self.option_filter_function)
-
- def option_filter_function(self, universe):
- universe.include_weeklys().front_month()
-
- contracts = list()
- for contract in universe:
- if len(contracts) == 5:
- break
- contracts.append(contract)
- return universe.contracts(contracts)
-
- def coarse_selection_function(self, coarse):
- if self.time <= datetime(2014,6,5):
- return [ self._twx ]
- return [ self._aapl ]
-
- def fine_selection_function(self, fine):
- if self.time <= datetime(2014,6,5):
- return [ self._twx ]
- return [ self._aapl ]
-
- def on_data(self, data):
- if self._changes == None or any(security.price == 0 for security in self._changes.added_securities):
- return
-
- # liquidate removed securities
- for security in self._changes.removed_securities:
- if security.invested:
- self.liquidate(security.symbol)
-
- for security in self._changes.added_securities:
- if not security.symbol.has_underlying:
- self._last_equity_added = security.symbol
- else:
- # options added should all match prev added security
- if security.symbol.underlying != self._last_equity_added:
- raise ValueError(f"Unexpected symbol added {security.symbol}")
- self._option_count += 1
-
- self.set_holdings(security.symbol, 0.05)
- self._changes = None
-
- # this event fires whenever we have changes to our universe
- def on_securities_changed(self, changes):
- if self._changes == None:
- self._changes = changes
- return
- self._changes = self._changes + changes
-
- def on_end_of_algorithm(self):
- if self._option_count == 0:
- raise ValueError("Option universe chain did not add any option!")
diff --git a/fincept-qt/scripts/strategies/CoarseFundamentalTop3Algorithm.py b/fincept-qt/scripts/strategies/CoarseFundamentalTop3Algorithm.py
deleted file mode 100644
index 8ef2678c3..000000000
--- a/fincept-qt/scripts/strategies/CoarseFundamentalTop3Algorithm.py
+++ /dev/null
@@ -1,75 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-F95F1806
-# Category: General Strategy
-# Description: Demonstration of using coarse and fine universe selection together to filter down a smaller universe of stocks
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Demonstration of using coarse and fine universe selection together to filter down a smaller universe of stocks.
-### </summary>
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="universes" />
-### <meta name="tag" content="coarse universes" />
-### <meta name="tag" content="fine universes" />
-class CoarseFundamentalTop3Algorithm(QCAlgorithm):
-
- def initialize(self):
- '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
-
- self.set_start_date(2014,3,24) #Set Start Date
- self.set_end_date(2014,4,7) #Set End Date
- self.set_cash(50000) #Set Strategy Cash
-
- # what resolution should the data *added* to the universe be?
- self.universe_settings.resolution = Resolution.DAILY
-
- # this add universe method accepts a single parameter that is a function that
- # accepts an IEnumerable<CoarseFundamental> and returns IEnumerable<Symbol>
- self.add_universe(self.coarse_selection_function)
-
- self.__number_of_symbols = 3
- self._changes = None
-
-
- # sort the data by daily dollar volume and take the top '__number_of_symbols'
- def coarse_selection_function(self, coarse):
- # sort descending by daily dollar volume
- sorted_by_dollar_volume = sorted(coarse, key=lambda x: x.dollar_volume, reverse=True)
-
- # return the symbol objects of the top entries from our sorted collection
- return [ x.symbol for x in sorted_by_dollar_volume[:self.__number_of_symbols] ]
-
-
- def on_data(self, data):
-
- self.log(f"OnData({self.utc_time}): Keys: {', '.join([key.value for key in data.keys()])}")
-
- # if we have no changes, do nothing
- if self._changes is None: return
-
- # liquidate removed securities
- for security in self._changes.removed_securities:
- if security.invested:
- self.liquidate(security.symbol)
-
- # we want 1/N allocation in each security in our universe
- for security in self._changes.added_securities:
- self.set_holdings(security.symbol, 1 / self.__number_of_symbols)
-
- self._changes = None
-
-
- # this event fires whenever we have changes to our universe
- def on_securities_changed(self, changes):
- self._changes = changes
- self.log(f"OnSecuritiesChanged({self.utc_time}):: {changes}")
-
- def on_order_event(self, fill):
- self.log(f"OnOrderEvent({self.utc_time}):: {fill}")
diff --git a/fincept-qt/scripts/strategies/Collective2PortfolioSignalExportDemonstrationAlgorithm.py b/fincept-qt/scripts/strategies/Collective2PortfolioSignalExportDemonstrationAlgorithm.py
deleted file mode 100644
index 5f9daa8c4..000000000
--- a/fincept-qt/scripts/strategies/Collective2PortfolioSignalExportDemonstrationAlgorithm.py
+++ /dev/null
@@ -1,90 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-5600B07D
-# Category: Portfolio Management
-# Description: This algorithm sends a list of portfolio targets from algorithm's Portfolio to Collective2 API every time the ema ind...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### This algorithm sends a list of portfolio targets from algorithm's Portfolio
-### to Collective2 API every time the ema indicators crosses between themselves.
-### </summary>
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="using quantconnect" />
-### <meta name="tag" content="securities and portfolio" />
-class Collective2PortfolioSignalExportDemonstrationAlgorithm(QCAlgorithm):
-
- def initialize(self):
- ''' Initialize the date and add all equity symbols present in list _symbols '''
-
- self.set_start_date(2013, 10, 7) #Set Start Date
- self.set_end_date(2013, 10, 11) #Set End Date
- self.set_cash(100000) #Set Strategy Cash
-
- # Symbols accepted by Collective2. Collective2 accepts stock, future, forex and US stock option symbols
- self.add_equity("GOOG")
- self._symbols = [
- Symbol.create("SPY", SecurityType.EQUITY, Market.USA, None, None),
- Symbol.create("EURUSD", SecurityType.FOREX, Market.OANDA, None, None),
- Symbol.create_future("ES", Market.CME, datetime(2023, 12, 15), None),
- Symbol.create_option("GOOG", Market.USA, OptionStyle.AMERICAN, OptionRight.CALL, 130, datetime(2023, 9, 1))
- ]
- for item in self._symbols:
- self.add_security(item)
-
- self.fast = self.ema("SPY", 10)
- self.slow = self.ema("SPY", 100)
-
- # Initialize these flags, to check when the ema indicators crosses between themselves
- self.ema_fast_is_not_set = True
- self.ema_fast_was_above = False
-
- # Collective2 APIv4 KEY: This value is provided by Collective2 in their webpage in your account section (See https://collective2.com/account-info)
- # See API documentation at https://trade.collective2.com/c2-api
- self.collective2_apikey = "YOUR APIV4 KEY"
-
- # Collective2 System ID: This value is found beside the system's name (strategy's name) on the main system page
- self.collective2_system_id = 0
-
- self.signal_export.add_signal_export_providers(Collective2SignalExport(self.collective2_apikey, self.collective2_system_id))
-
- self.first_call = True
-
- self.set_warm_up(100)
-
- def on_data(self, data):
- ''' Reduce the quantity of holdings for one security and increase the holdings to the another
- one when the EMA's indicators crosses between themselves, then send a signal to Collective2 API '''
- if self.is_warming_up: return
-
- # Place an order as soon as possible to send a signal.
- if self.first_call:
- self.set_holdings("SPY", 0.1)
- self.signal_export.set_target_portfolio_from_portfolio()
- self.first_call = False
-
- fast = self.fast.current.value
- slow = self.slow.current.value
-
- # Set the value of flag _ema_fast_was_above, to know when the ema indicators crosses between themselves
- if self.ema_fast_is_not_set == True:
- if fast > slow *1.001:
- self.ema_fast_was_above = True
- else:
- self.ema_fast_was_above = False
- self.ema_fast_is_not_set = False
-
- # Check whether ema fast and ema slow crosses. If they do, set holdings to SPY
- # or reduce its holdings, and send signals to Collective2 API from your Portfolio
- if fast > slow * 1.001 and (not self.ema_fast_was_above):
- self.set_holdings("SPY", 0.1)
- self.signal_export.set_target_portfolio_from_portfolio()
- elif fast < slow * 0.999 and (self.ema_fast_was_above):
- self.set_holdings("SPY", 0.01)
- self.signal_export.set_target_portfolio_from_portfolio()
diff --git a/fincept-qt/scripts/strategies/Collective2SignalExportDemonstrationAlgorithm.py b/fincept-qt/scripts/strategies/Collective2SignalExportDemonstrationAlgorithm.py
deleted file mode 100644
index ea8345be4..000000000
--- a/fincept-qt/scripts/strategies/Collective2SignalExportDemonstrationAlgorithm.py
+++ /dev/null
@@ -1,101 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-8AEECDC1
-# Category: General Strategy
-# Description: This algorithm sends a list of portfolio targets to Collective2 API every time the ema indicators crosses between the...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### This algorithm sends a list of portfolio targets to Collective2 API every time the ema indicators crosses between themselves.
-### </summary>
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="using quantconnect" />
-### <meta name="tag" content="securities and portfolio" />
-class Collective2SignalExportDemonstrationAlgorithm(QCAlgorithm):
-
- def initialize(self):
- ''' Initialize the date and add all equity symbols present in list _symbols '''
-
- self.set_start_date(2013, 10, 7) #Set Start Date
- self.set_end_date(2013, 10, 11) #Set End Date
- self.set_cash(100000) #Set Strategy Cash
-
- # Symbols accepted by Collective2. Collective2 accepts stock, future, forex and US stock option symbols
- self.add_equity("GOOG")
- self._symbols = [
- Symbol.create("SPY", SecurityType.EQUITY, Market.USA, None, None),
- Symbol.create("EURUSD", SecurityType.FOREX, Market.OANDA, None, None),
- Symbol.create_future("ES", Market.CME, datetime(2023, 12, 15), None),
- Symbol.create_option("GOOG", Market.USA, OptionStyle.AMERICAN, OptionRight.CALL, 130, datetime(2023, 9, 1))
- ]
- self.targets = []
-
- # Create a new PortfolioTarget for each symbol, assign it an initial amount of 0.05 and save it in self.targets list
- for item in self._symbols:
- symbol = self.add_security(item).symbol
- if symbol.security_type == SecurityType.EQUITY or symbol.security_type == SecurityType.FOREX:
- self.targets.append(PortfolioTarget(symbol, 0.05))
- else:
- self.targets.append(PortfolioTarget(symbol, 1))
-
- self.fast = self.ema("SPY", 10)
- self.slow = self.ema("SPY", 100)
-
- # Initialize these flags, to check when the ema indicators crosses between themselves
- self.ema_fast_is_not_set = True
- self.ema_fast_was_above = False
-
- # Set Collective2 export provider
- # Collective2 APIv4 KEY: This value is provided by Collective2 in your account section (See https://collective2.com/account-info)
- # See API documentation at https://trade.collective2.com/c2-api
- self.collective2_apikey = "YOUR APIV4 KEY"
-
- # Collective2 System ID: This value is found beside the system's name (strategy's name) on the main system page
- self.collective2_system_id = 0
-
- self.signal_export.add_signal_export_providers(Collective2SignalExport(self.collective2_apikey, self.collective2_system_id))
-
- self.first_call = True
-
- self.set_warm_up(100)
-
- def on_data(self, data):
- ''' Reduce the quantity of holdings for one security and increase the holdings to the another
- one when the EMA's indicators crosses between themselves, then send a signal to Collective2 API '''
- if self.is_warming_up: return
-
- # Place an order as soon as possible to send a signal.
- if self.first_call:
- self.set_holdings("SPY", 0.1)
- self.targets[0] = PortfolioTarget(self.portfolio["SPY"].symbol, 0.1)
- self.signal_export.set_target_portfolio(self.targets)
- self.first_call = False
-
- fast = self.fast.current.value
- slow = self.slow.current.value
-
- # Set the value of flag _ema_fast_was_above, to know when the ema indicators crosses between themselves
- if self.ema_fast_is_not_set == True:
- if fast > slow *1.001:
- self.ema_fast_was_above = True
- else:
- self.ema_fast_was_above = False
- self.ema_fast_is_not_set = False
-
- # Check whether ema fast and ema slow crosses. If they do, set holdings to SPY
- # or reduce its holdings, change its value in self.targets list and send signals
- # to Collective2 API from self.targets
- if fast > slow * 1.001 and (not self.ema_fast_was_above):
- self.set_holdings("SPY", 0.1)
- self.targets[0] = PortfolioTarget(self.portfolio["SPY"].symbol, 0.1)
- self.signal_export.set_target_portfolio(self.targets)
- elif fast < slow * 0.999 and (self.ema_fast_was_above):
- self.set_holdings("SPY", 0.01)
- self.targets[0] = PortfolioTarget(self.portfolio["SPY"].symbol, 0.01)
- self.signal_export.set_target_portfolio(self.targets)
diff --git a/fincept-qt/scripts/strategies/ComboOrderTicketDemoAlgorithm.py b/fincept-qt/scripts/strategies/ComboOrderTicketDemoAlgorithm.py
deleted file mode 100644
index a2be8b2e2..000000000
--- a/fincept-qt/scripts/strategies/ComboOrderTicketDemoAlgorithm.py
+++ /dev/null
@@ -1,223 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-EB692DBC
-# Category: General Strategy
-# Description: Algorithm for testing submit/update/cancel for combo orders
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-import itertools
-from AlgorithmImports import *
-
-### <summary>
-### Algorithm for testing submit/update/cancel for combo orders
-### </summary>
-class ComboOrderTicketDemoAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2015, 12, 24)
- self.set_end_date(2015, 12, 24)
- self.set_cash(100000)
-
- equity = self.add_equity("GOOG", leverage=4, fill_forward=True)
- option = self.add_option(equity.symbol, fill_forward=True)
- self._option_symbol = option.symbol
-
- option.set_filter(lambda u: u.strikes(-2, +2).expiration(0, 180))
-
- self._open_market_orders = []
- self._open_leg_limit_orders = []
- self._open_limit_orders = []
-
- self._order_legs = None
-
- def on_data(self, data: Slice):
- if self._order_legs is None:
- if self.is_market_open(self._option_symbol):
- chain = data.option_chains.get_value(self._option_symbol)
- if chain is not None:
- call_contracts = [contract for contract in chain if contract.right == OptionRight.CALL]
- call_contracts = [(key, list(group)) for key, group in itertools.groupby(call_contracts, key=lambda x: x.expiry)]
- call_contracts.sort(key=lambda x: x[0])
- call_contracts = call_contracts[0][1]
- call_contracts.sort(key=lambda x: x.strike)
-
- if len(call_contracts) < 3:
- return
-
- quantities = [1, -2, 1]
- self._order_legs = []
- for i, contract in enumerate(call_contracts[:3]):
- leg = Leg.create(contract.symbol, quantities[i])
- self._order_legs.append(leg)
- else:
- # COMBO MARKET ORDERS
-
- self.combo_market_orders()
-
- # COMBO LIMIT ORDERS
-
- self.combo_limit_orders()
-
- # COMBO LEG LIMIT ORDERS
-
- self.combo_leg_limit_orders()
-
- def combo_market_orders(self):
- if len(self._open_market_orders) != 0 or self._order_legs is None:
- return
-
- self.log("Submitting combo market orders")
-
- tickets = self.combo_market_order(self._order_legs, 2, asynchronous=False)
- self._open_market_orders.extend(tickets)
-
- tickets = self.combo_market_order(self._order_legs, 2, asynchronous=True)
- self._open_market_orders.extend(tickets)
-
- for ticket in tickets:
- response = ticket.cancel("Attempt to cancel combo market order")
- if response.is_success:
- raise Exception("Combo market orders should fill instantly, they should not be cancelable in backtest mode: " + response.order_id)
-
- def combo_limit_orders(self):
- if len(self._open_limit_orders) == 0:
- self.log("Submitting ComboLimitOrder")
-
- current_price = sum([leg.quantity * self.securities[leg.symbol].close for leg in self._order_legs])
-
- tickets = self.combo_limit_order(self._order_legs, 2, current_price + 1.5)
- self._open_limit_orders.extend(tickets)
-
- # These won't fill, we will test cancel with this
- tickets = self.combo_limit_order(self._order_legs, -2, current_price + 3)
- self._open_limit_orders.extend(tickets)
- else:
- combo1 = self._open_limit_orders[:len(self._order_legs)]
- combo2 = self._open_limit_orders[-len(self._order_legs):]
-
- # check if either is filled and cancel the other
- if self.check_group_orders_for_fills(combo1, combo2):
- return
-
- # if neither order has filled, bring in the limits by a penny
-
- ticket = combo1[0]
- new_limit = round(ticket.get(OrderField.LIMIT_PRICE) + 0.01, 2)
- self.debug(f"Updating limits - Combo 1 {ticket.order_id}: {new_limit:.2f}")
- fields = UpdateOrderFields()
- fields.limit_price = new_limit
- fields.tag = f"Update #{len(ticket.update_requests) + 1}"
- ticket.update(fields)
-
- ticket = combo2[0]
- new_limit = round(ticket.get(OrderField.LIMIT_PRICE) - 0.01, 2)
- self.debug(f"Updating limits - Combo 2 {ticket.order_id}: {new_limit:.2f}")
- fields.limit_price = new_limit
- fields.tag = f"Update #{len(ticket.update_requests) + 1}"
- ticket.update(fields)
-
- def combo_leg_limit_orders(self):
- if len(self._open_leg_limit_orders) == 0:
- self.log("Submitting ComboLegLimitOrder")
-
- # submit a limit order to buy 2 shares at .1% below the bar's close
- for leg in self._order_legs:
- close = self.securities[leg.symbol].close
- leg.order_price = close * .999
-
- tickets = self.combo_leg_limit_order(self._order_legs, quantity=2)
- self._open_leg_limit_orders.extend(tickets)
-
- # submit another limit order to sell 2 shares at .1% above the bar's close
- for leg in self._order_legs:
- close = self.securities[leg.symbol].close
- leg.order_price = close * 1.001
-
- tickets = self.combo_leg_limit_order(self._order_legs, -2)
- self._open_leg_limit_orders.extend(tickets)
- else:
- combo1 = self._open_leg_limit_orders[:len(self._order_legs)]
- combo2 = self._open_leg_limit_orders[-len(self._order_legs):]
-
- # check if either is filled and cancel the other
- if self.check_group_orders_for_fills(combo1, combo2):
- return
-
- # if neither order has filled, bring in the limits by a penny
-
- for ticket in combo1:
- new_limit = round(ticket.get(OrderField.LIMIT_PRICE) + (1 if ticket.quantity > 0 else -1) * 0.01, 2)
- self.debug(f"Updating limits - Combo #1: {new_limit:.2f}")
- fields = UpdateOrderFields()
- fields.limit_price = new_limit
- fields.tag = f"Update #{len(ticket.update_requests) + 1}"
- ticket.update(fields)
-
- for ticket in combo2:
- new_limit = round(ticket.get(OrderField.LIMIT_PRICE) + (1 if ticket.quantity > 0 else -1) * 0.01, 2)
- self.debug(f"Updating limits - Combo #2: {new_limit:.2f}")
- fields.limit_price = new_limit
- fields.tag = f"Update #{len(ticket.update_requests) + 1}"
- ticket.update(fields)
-
- def on_order_event(self, order_event):
- order = self.transactions.get_order_by_id(order_event.order_id)
-
- if order_event.quantity == 0:
- raise Exception("OrderEvent quantity is Not expected to be 0, it should hold the current order Quantity")
-
- if order_event.quantity != order.quantity:
- raise Exception("OrderEvent quantity should hold the current order Quantity. "
- f"Got {order_event.quantity}, expected {order.quantity}")
-
- if order.type == OrderType.COMBO_LEG_LIMIT and order_event.limit_price == 0:
- raise Exception("OrderEvent.LIMIT_PRICE is not expected to be 0 for ComboLegLimitOrder")
-
- def check_group_orders_for_fills(self, combo1, combo2):
- if all(x.status == OrderStatus.FILLED for x in combo1):
- self.log(f"{combo1[0].order_type}: Canceling combo #2, combo #1 is filled.")
- if any(OrderExtensions.is_open(x.status) for x in combo2):
- for ticket in combo2:
- ticket.cancel("Combo #1 filled.")
- return True
-
- if all(x.status == OrderStatus.FILLED for x in combo2):
- self.log(f"{combo2[0].order_type}: Canceling combo #1, combo #2 is filled.")
- if any(OrderExtensions.is_open(x.status) for x in combo1):
- for ticket in combo1:
- ticket.cancel("Combo #2 filled.")
- return True
-
- return False
-
- def on_end_of_algorithm(self):
- filled_orders = self.transactions.get_orders(lambda x: x.status == OrderStatus.FILLED).to_list()
- order_tickets = self.transactions.get_order_tickets().to_list()
- open_orders = self.transactions.get_open_orders()
- open_order_tickets = self.transactions.get_open_order_tickets().to_list()
- remaining_open_orders = self.transactions.get_open_orders_remaining_quantity()
-
- # 6 market, 6 limit, 6 leg limit.
- # Out of the 6 limit orders, 3 are expected to be canceled.
- expected_orders_count = 18
- expected_fills_count = 15
- if len(filled_orders) != expected_fills_count or len(order_tickets) != expected_orders_count:
- raise Exception(f"There were expected {expected_fills_count} filled orders and {expected_orders_count} order tickets, but there were {len(filled_orders)} filled orders and {len(order_tickets)} order tickets")
-
- filled_combo_market_orders = [x for x in filled_orders if x.type == OrderType.COMBO_MARKET]
- filled_combo_limit_orders = [x for x in filled_orders if x.type == OrderType.COMBO_LIMIT]
- filled_combo_leg_limit_orders = [x for x in filled_orders if x.type == OrderType.COMBO_LEG_LIMIT]
- if len(filled_combo_market_orders) != 6 or len(filled_combo_limit_orders) != 3 or len(filled_combo_leg_limit_orders) != 6:
- raise Exception("There were expected 6 filled market orders, 3 filled combo limit orders and 6 filled combo leg limit orders, "
- f"but there were {len(filled_combo_market_orders)} filled market orders, {len(filled_combo_limit_orders)} filled "
- f"combo limit orders and {len(filled_combo_leg_limit_orders)} filled combo leg limit orders")
-
- if len(open_orders) != 0 or len(open_order_tickets) != 0:
- raise Exception("No open orders or tickets were expected")
-
- if remaining_open_orders != 0:
- raise Exception("No remaining quantity to be filled from open orders was expected")
diff --git a/fincept-qt/scripts/strategies/ComboOrdersFillModelAlgorithm.py b/fincept-qt/scripts/strategies/ComboOrdersFillModelAlgorithm.py
deleted file mode 100644
index ce4c0ca5d..000000000
--- a/fincept-qt/scripts/strategies/ComboOrdersFillModelAlgorithm.py
+++ /dev/null
@@ -1,116 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-203BF5C3
-# Category: General Strategy
-# Description: Basic template algorithm that implements a fill model with combo orders
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Basic template algorithm that implements a fill model with combo orders
-### <meta name="tag" content="trading and orders" />
-### </summary>
-class ComboOrdersFillModelAlgorithm(QCAlgorithm):
- '''Basic template algorithm that implements a fill model with combo orders'''
-
- def initialize(self):
- self.set_start_date(2019, 1, 1)
- self.set_end_date(2019, 1, 20)
-
- self.spy = self.add_equity("SPY", Resolution.HOUR)
- self.ibm = self.add_equity("IBM", Resolution.HOUR)
-
- # Set the fill model
- self.spy.set_fill_model(CustomPartialFillModel())
- self.ibm.set_fill_model(CustomPartialFillModel())
-
- self.order_types = {}
-
- def on_data(self, data):
- if not self.portfolio.invested:
- legs = [Leg.create(self.spy.symbol, 1), Leg.create(self.ibm.symbol, -1)]
- self.combo_market_order(legs, 100)
- self.combo_limit_order(legs, 100, round(self.spy.bid_price))
-
- legs = [Leg.create(self.spy.symbol, 1, round(self.spy.bid_price) + 1), Leg.create(self.ibm.symbol, -1, round(self.ibm.bid_price) + 1)]
- self.combo_leg_limit_order(legs, 100)
-
- def on_order_event(self, order_event):
- if order_event.status == OrderStatus.FILLED:
- order_type = self.transactions.get_order_by_id(order_event.order_id).type
- if order_type == OrderType.COMBO_MARKET and order_event.absolute_fill_quantity != 50:
- raise Exception(f"The absolute quantity filled for all combo market orders should be 50, but for order {order_event.order_id} was {order_event.absolute_fill_quantity}")
- elif order_type == OrderType.COMBO_LIMIT and order_event.absolute_fill_quantity != 20:
- raise Exception(f"The absolute quantity filled for all combo limit orders should be 20, but for order {order_event.order_id} was {order_event.absolute_fill_quantity}")
- elif order_type == OrderType.COMBO_LEG_LIMIT and order_event.absolute_fill_quantity != 10:
- raise Exception(f"The absolute quantity filled for all combo leg limit orders should be 10, but for order {order_event.order_id} was {order_event.absolute_fill_quantity}")
-
- self.order_types[order_type] = 1
-
- def on_end_of_algorithm(self):
- if len(self.order_types) != 3:
- raise Exception(f"Just 3 different types of order were submitted in this algorithm, but the amount of order types was {len(self.order_types)}")
-
- if OrderType.COMBO_MARKET not in self.order_types.keys():
- raise Exception(f"One Combo Market Order should have been submitted but it was not")
-
- if OrderType.COMBO_LIMIT not in self.order_types.keys():
- raise Exception(f"One Combo Limit Order should have been submitted but it was not")
-
- if OrderType.COMBO_LEG_LIMIT not in self.order_types.keys():
- raise Exception(f"One Combo Leg Limit Order should have been submitted but it was not")
-
-
-class CustomPartialFillModel(FillModel):
- '''Implements a custom fill model that inherit from FillModel. Overrides combo_market_fill, combo_limit_fill and combo_leg_limit_fill
- methods to test FillModelPythonWrapper works as expected'''
-
- def __init__(self):
- self.absolute_remaining_by_order_id = {}
-
- def fill_orders_partially(self, parameters, fills, quantity):
- partial_fills = []
- if len(fills) == 0:
- return partial_fills
-
- for kvp, fill in zip(sorted(parameters.securities_for_orders, key=lambda x: x.key.id), fills):
- order = kvp.key
-
- absolute_remaining = self.absolute_remaining_by_order_id.get(order.id, order.absolute_quantity)
-
- # Set the fill amount
- fill.fill_quantity = np.sign(order.quantity) * quantity
-
- if (min(abs(fill.fill_quantity), absolute_remaining) == absolute_remaining):
- fill.fill_quantity = np.sign(order.quantity) * absolute_remaining
- fill.status = OrderStatus.FILLED
- self.absolute_remaining_by_order_id.pop(order.id, None)
- else:
- fill.status = OrderStatus.PARTIALLY_FILLED
- self.absolute_remaining_by_order_id[order.id] = absolute_remaining - abs(fill.fill_quantity)
- price = fill.fill_price
- # self.algorithm.debug(f"{self.algorithm.time} - Partial Fill - Remaining {self.absolute_remaining_by_order_id[order.id]} Price - {price}")
-
- partial_fills.append(fill)
-
- return partial_fills
-
- def combo_market_fill(self, order, parameters):
- fills = super().combo_market_fill(order, parameters)
- partial_fills = self.fill_orders_partially(parameters, fills, 50)
- return partial_fills
-
- def combo_limit_fill(self, order, parameters):
- fills = super().combo_limit_fill(order, parameters)
- partial_fills = self.fill_orders_partially(parameters, fills, 20)
- return partial_fills
-
- def combo_leg_limit_fill(self, order, parameters):
- fills = super().combo_leg_limit_fill(order, parameters)
- partial_fills = self.fill_orders_partially(parameters, fills, 10)
- return partial_fills
diff --git a/fincept-qt/scripts/strategies/CompleteOrderTagUpdateAlgorithm.py b/fincept-qt/scripts/strategies/CompleteOrderTagUpdateAlgorithm.py
deleted file mode 100644
index 92b44b867..000000000
--- a/fincept-qt/scripts/strategies/CompleteOrderTagUpdateAlgorithm.py
+++ /dev/null
@@ -1,87 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-5E302074
-# Category: General Strategy
-# Description: Algorithm asserting that closed orders can be updated with a new tag
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Algorithm asserting that closed orders can be updated with a new tag
-### </summary>
-class CompleteOrderTagUpdateAlgorithm(QCAlgorithm):
-
- tag_after_fill = "This is the tag set after order was filled."
- tag_after_canceled = "This is the tag set after order was canceled."
-
- def initialize(self) -> None:
- self.set_start_date(2013,10, 7)
- self.set_end_date(2013,10,11)
- self.set_cash(100000)
-
- self._spy = self.add_equity("SPY", Resolution.MINUTE).symbol
-
- self._market_order_ticket = None
- self._limit_order_ticket = None
-
- self._quantity = 100
-
- def on_data(self, data: Slice) -> None:
- if not self.portfolio.invested:
- if self._limit_order_ticket is None:
- # a limit order to test the tag update after order was canceled.
-
- # low price, we don't want it to fill since we are canceling it
- self._limit_order_ticket = self.limit_order(self._spy, 100, self.securities[self._spy].price * 0.1)
- self._limit_order_ticket.cancel()
- else:
- # a market order to test the tag update after order was filled.
- self.buy(self._spy, self._quantity)
-
- def on_order_event(self, order_event: OrderEvent) -> None:
- if order_event.status == OrderStatus.CANCELED:
- if order_event.order_id != self._limit_order_ticket.order_id:
- raise Exception("The only canceled order should have been the limit order.")
-
- # update canceled order tag
- self.update_order_tag(self._limit_order_ticket, self.tag_after_canceled, "Error updating order tag after canceled")
- elif order_event.status == OrderStatus.FILLED:
- self._market_order_ticket = list(self.transactions.get_order_tickets(lambda x: x.order_type == OrderType.MARKET))[0]
- if order_event.order_id != self._market_order_ticket.order_id:
- raise Exception("The only filled order should have been the market order.")
-
- # update filled order tag
- self.update_order_tag(self._market_order_ticket, self.tag_after_fill, "Error updating order tag after fill")
-
- def on_end_of_algorithm(self) -> None:
- # check the filled order
- self.assert_order_tag_update(self._market_order_ticket, self.tag_after_fill, "filled")
- if self._market_order_ticket.quantity != self._quantity or self._market_order_ticket.quantity_filled != self._quantity:
- raise Exception("The market order quantity should not have been updated.")
-
- # check the canceled order
- self.assert_order_tag_update(self._limit_order_ticket, self.tag_after_canceled, "canceled")
-
- def assert_order_tag_update(self, ticket: OrderTicket, expected_tag: str, order_action: str) -> None:
- if ticket is None:
- raise Exception(f"The order ticket was not set for the {order_action} order")
-
- if ticket.tag != expected_tag:
- raise Exception(f"Order ticket tag was not updated after order was {order_action}")
-
- order = self.transactions.get_order_by_id(ticket.order_id)
- if order.tag != expected_tag:
- raise Exception(f"Order tag was not updated after order was {order_action}")
-
- def update_order_tag(self, ticket: OrderTicket, tag: str, error_message_prefix: str) -> None:
- update_fields = UpdateOrderFields()
- update_fields.tag = tag
- response = ticket.update(update_fields)
-
- if response.is_error:
- raise Exception(f"{error_message_prefix}: {response.error_message}")
diff --git a/fincept-qt/scripts/strategies/CompositeAlphaModelFrameworkAlgorithm.py b/fincept-qt/scripts/strategies/CompositeAlphaModelFrameworkAlgorithm.py
deleted file mode 100644
index 9ba8262df..000000000
--- a/fincept-qt/scripts/strategies/CompositeAlphaModelFrameworkAlgorithm.py
+++ /dev/null
@@ -1,46 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-50C4F04D
-# Category: Alpha Model
-# Description: Show cases how to use the CompositeAlphaModel to define
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-from Alphas.RsiAlphaModel import RsiAlphaModel
-from Alphas.EmaCrossAlphaModel import EmaCrossAlphaModel
-from Portfolio.EqualWeightingPortfolioConstructionModel import EqualWeightingPortfolioConstructionModel
-
-### <summary>
-### Show cases how to use the CompositeAlphaModel to define.
-### </summary>
-class CompositeAlphaModelFrameworkAlgorithm(QCAlgorithm):
- '''Show cases how to use the CompositeAlphaModel to define.'''
-
- def initialize(self):
- self.set_start_date(2013,10,7) #Set Start Date
- self.set_end_date(2013,10,11) #Set End Date
- self.set_cash(100000) #Set Strategy Cash
-
- # even though we're using a framework algorithm, we can still add our securities
- # using the AddEquity/Forex/Crypto/ect methods and then pass them into a manual
- # universe selection model using securities.keys()
- self.add_equity("SPY")
- self.add_equity("IBM")
- self.add_equity("BAC")
- self.add_equity("AIG")
-
- # define a manual universe of all the securities we manually registered
- self.set_universe_selection(ManualUniverseSelectionModel())
-
- # define alpha model as a composite of the rsi and ema cross models
- self.set_alpha(CompositeAlphaModel(RsiAlphaModel(), EmaCrossAlphaModel()))
-
- # default models for the rest
- self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())
- self.set_execution(ImmediateExecutionModel())
- self.set_risk_management(NullRiskManagementModel())
diff --git a/fincept-qt/scripts/strategies/CompositeRiskManagementModelFrameworkAlgorithm.py b/fincept-qt/scripts/strategies/CompositeRiskManagementModelFrameworkAlgorithm.py
deleted file mode 100644
index c4ef07820..000000000
--- a/fincept-qt/scripts/strategies/CompositeRiskManagementModelFrameworkAlgorithm.py
+++ /dev/null
@@ -1,39 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-5A1D14B7
-# Category: Risk Management
-# Description: Show cases how to use the CompositeRiskManagementModel
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Show cases how to use the CompositeRiskManagementModel.
-### </summary>
-class CompositeRiskManagementModelFrameworkAlgorithm(QCAlgorithm):
- '''Show cases how to use the CompositeRiskManagementModel.'''
-
- def initialize(self):
-
- # Set requested data resolution
- self.universe_settings.resolution = Resolution.MINUTE
-
- self.set_start_date(2013,10,7) #Set Start Date
- self.set_end_date(2013,10,11) #Set End Date
- self.set_cash(100000) #Set Strategy Cash
-
- # set algorithm framework models
- self.set_universe_selection(ManualUniverseSelectionModel([Symbol.create("SPY", SecurityType.EQUITY, Market.USA)]))
- self.set_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(minutes = 20), 0.025, None))
- self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())
- self.set_execution(ImmediateExecutionModel())
-
- # define risk management model as a composite of several risk management models
- self.set_risk_management(CompositeRiskManagementModel(
- MaximumUnrealizedProfitPercentPerSecurity(0.01),
- MaximumDrawdownPercentPerSecurity(0.01)
- ))
diff --git a/fincept-qt/scripts/strategies/ConfidenceWeightedFrameworkAlgorithm.py b/fincept-qt/scripts/strategies/ConfidenceWeightedFrameworkAlgorithm.py
deleted file mode 100644
index ef335f524..000000000
--- a/fincept-qt/scripts/strategies/ConfidenceWeightedFrameworkAlgorithm.py
+++ /dev/null
@@ -1,45 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-9EECE18B
-# Category: General Strategy
-# Description: Test algorithm using 'ConfidenceWeightedPortfolioConstructionModel' and 'ConstantAlphaModel' generating a constant 'I...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Test algorithm using 'ConfidenceWeightedPortfolioConstructionModel' and 'ConstantAlphaModel'
-### generating a constant 'Insight' with a 0.25 confidence
-### </summary>
-class ConfidenceWeightedFrameworkAlgorithm(QCAlgorithm):
- def initialize(self):
- ''' Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
-
- # Set requested data resolution
- self.universe_settings.resolution = Resolution.MINUTE
-
- # Order margin value has to have a minimum of 0.5% of Portfolio value, allows filtering out small trades and reduce fees.
- # Commented so regression algorithm is more sensitive
- #self.settings.minimum_order_margin_portfolio_percentage = 0.005
-
- self.set_start_date(2013,10,7) #Set Start Date
- self.set_end_date(2013,10,11) #Set End Date
- self.set_cash(100000) #Set Strategy Cash
-
- symbols = [ Symbol.create("SPY", SecurityType.EQUITY, Market.USA) ]
-
- # set algorithm framework models
- self.set_universe_selection(ManualUniverseSelectionModel(symbols))
- self.set_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(minutes = 20), 0.025, 0.25))
- self.set_portfolio_construction(ConfidenceWeightedPortfolioConstructionModel())
- self.set_execution(ImmediateExecutionModel())
-
- def on_end_of_algorithm(self):
- # holdings value should be 0.25 - to avoid price fluctuation issue we compare with 0.28 and 0.23
- if (self.portfolio.total_holdings_value > self.portfolio.total_portfolio_value * 0.28
- or self.portfolio.total_holdings_value < self.portfolio.total_portfolio_value * 0.23):
- raise ValueError("Unexpected Total Holdings Value: " + str(self.portfolio.total_holdings_value))
diff --git a/fincept-qt/scripts/strategies/ConsolidateDifferentTickTypesRegressionAlgorithm.py b/fincept-qt/scripts/strategies/ConsolidateDifferentTickTypesRegressionAlgorithm.py
deleted file mode 100644
index 7c3d63e69..000000000
--- a/fincept-qt/scripts/strategies/ConsolidateDifferentTickTypesRegressionAlgorithm.py
+++ /dev/null
@@ -1,46 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-C054C3D1
-# Category: Data Consolidation
-# Description: This algorithm asserts we can consolidate Tick data with different tick types
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### This algorithm asserts we can consolidate Tick data with different tick types
-### </summary>
-class ConsolidateDifferentTickTypesRegressionAlgorithm(QCAlgorithm):
- def initialize(self):
- self.set_start_date(2013, 10, 6)
- self.set_end_date(2013, 10, 7)
- self.set_cash(1000000)
-
- equity = self.add_equity("SPY", Resolution.TICK, Market.USA)
- quote_consolidator = self.consolidate(equity.symbol, Resolution.TICK, TickType.QUOTE, lambda tick : self.on_quote_tick(tick))
- self.there_is_at_least_one_quote_tick = False
-
- trade_consolidator = self.consolidate(equity.symbol, Resolution.TICK, TickType.TRADE, lambda tick : self.on_trade_tick(tick))
- self.there_is_at_least_one_trade_tick = False
-
- def on_quote_tick(self, tick):
- self.there_is_at_least_one_quote_tick = True
- if tick.tick_type != TickType.QUOTE:
- raise Exception(f"The type of the tick should be Quote, but was {tick.tick_type}")
-
- def on_trade_tick(self, tick):
- self.there_is_at_least_one_trade_tick = True
- if tick.tick_type != TickType.TRADE:
- raise Exception(f"The type of the tick should be Trade, but was {tick.tick_type}")
-
- def on_end_of_algorithm(self):
- if not self.there_is_at_least_one_quote_tick:
- raise Exception(f"There should have been at least one tick in OnQuoteTick() method, but there wasn't")
-
- if not self.there_is_at_least_one_trade_tick:
- raise Exception(f"There should have been at least one tick in OnTradeTick() method, but there wasn't")
-
diff --git a/fincept-qt/scripts/strategies/ConsolidateHourBarsIntoDailyBarsRegressionAlgorithm.py b/fincept-qt/scripts/strategies/ConsolidateHourBarsIntoDailyBarsRegressionAlgorithm.py
deleted file mode 100644
index 7a684fa9f..000000000
--- a/fincept-qt/scripts/strategies/ConsolidateHourBarsIntoDailyBarsRegressionAlgorithm.py
+++ /dev/null
@@ -1,67 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-D4F95392
-# Category: Data Consolidation
-# Description: This regression algorithm asserts the consolidated US equity daily bars from the hour bars exactly matches the daily ...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### This regression algorithm asserts the consolidated US equity daily bars from the hour bars exactly matches
-### the daily bars returned from the database
-### </summary>
-class ConsolidateHourBarsIntoDailyBarsRegressionAlgorithm(QCAlgorithm):
- def initialize(self):
- self.set_start_date(2020, 5, 1)
- self.set_end_date(2020, 6, 5)
-
- self.spy = self.add_equity("SPY", Resolution.HOUR).symbol
-
- # We will use these two indicators to compare the daily consolidated bars equals
- # the ones returned from the database. We use this specific type of indicator as
- # it depends on its previous values. Thus, if at some point the bars received by
- # the indicators differ, so will their final values
- self._rsi = RelativeStrengthIndex("First", 15, MovingAverageType.WILDERS)
- self.register_indicator(self.spy, self._rsi, Resolution.DAILY, selector= lambda bar: (bar.close + bar.open) / 2)
-
- # We won't register this indicator as we will update it manually at the end of the
- # month, so that we can compare the values of the indicator that received consolidated
- # bars and the values of this one
- self._rsi_timedelta = RelativeStrengthIndex("Second", 15, MovingAverageType.WILDERS)
- self._values = {}
- self.count = 0;
- self._indicators_compared = False;
-
- def on_data(self, data: Slice):
- if self.is_warming_up:
- return
-
- if data.contains_key(self.spy) and data[self.spy] != None:
- if self.time.month == self.end_date.month:
- history = self.history[TradeBar](self.spy, self.count, Resolution.DAILY)
- for bar in history:
- time = bar.end_time.strftime('%Y-%m-%d')
- average = (bar.close + bar.open) / 2
- self._rsi_timedelta.update(bar.end_time, average)
- if self._rsi_timedelta.current.value != self._values[time]:
- raise Exception(f"Both {self._rsi.name} and {self._rsi_timedelta.name} should have the same values, but they differ. {self._rsi.name}: {self._values[time]} | {self._rsi_timedelta.name}: {self._rsi_timedelta.current.value}")
- self._indicators_compared = True
- self.quit()
- else:
- time = self.time.strftime('%Y-%m-%d')
- self._values[time] = self._rsi.current.value
-
- # Since the symbol resolution is hour and the symbol is equity, we know the last bar received in a day will
- # be at the market close, this is 16h. We need to count how many daily bars were consolidated in order to know
- # how many we need to request from the history
- if self.time.hour == 16:
- self.count += 1
-
- def on_end_of_algorithm(self):
- if not self._indicators_compared:
- raise Exception(f"Indicators {self._rsi.name} and {self._rsi_timedelta.name} should have been compared, but they were not. Please make sure the indicators are getting SPY data")
diff --git a/fincept-qt/scripts/strategies/ConsolidateRegressionAlgorithm.py b/fincept-qt/scripts/strategies/ConsolidateRegressionAlgorithm.py
deleted file mode 100644
index f71b27e90..000000000
--- a/fincept-qt/scripts/strategies/ConsolidateRegressionAlgorithm.py
+++ /dev/null
@@ -1,49 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-16F5EE2E
-# Category: Data Consolidation
-# Description: Multi-timeframe confirmation strategy. Uses both 5-day and 20-day
-# SMAs. Enters when both short and long SMAs confirm uptrend, exits when
-# short SMA crosses below long SMA.
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-class ConsolidateRegressionAlgorithm(QCAlgorithm):
- """Multi-timeframe SMA confirmation strategy."""
-
- def initialize(self):
- self.set_start_date(2023, 1, 1)
- self.set_end_date(2024, 1, 1)
- self.set_cash(100000)
-
- self.symbol = "SPY"
- self.add_equity(self.symbol, Resolution.DAILY)
-
- self._sma5 = self.sma(self.symbol, 5, Resolution.DAILY)
- self._sma20 = self.sma(self.symbol, 20, Resolution.DAILY)
- self._sma50 = self.sma(self.symbol, 50, Resolution.DAILY)
-
- def on_data(self, data):
- if not self._sma50.is_ready:
- return
- if self.symbol not in data:
- return
-
- price = data[self.symbol].close
- s5 = self._sma5.current.value
- s20 = self._sma20.current.value
- s50 = self._sma50.current.value
-
- if not self.portfolio.invested:
- # All timeframes aligned bullish
- if s5 > s20 > s50 and price > s5:
- self.set_holdings(self.symbol, 1)
- else:
- # Short-term trend reversal
- if s5 < s20:
- self.liquidate()
diff --git a/fincept-qt/scripts/strategies/ConstituentsQC500GeneratorAlgorithm.py b/fincept-qt/scripts/strategies/ConstituentsQC500GeneratorAlgorithm.py
deleted file mode 100644
index 958209181..000000000
--- a/fincept-qt/scripts/strategies/ConstituentsQC500GeneratorAlgorithm.py
+++ /dev/null
@@ -1,34 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-EFBD246D
-# Category: General Strategy
-# Description: Demonstration of how to estimate constituents of QC500 index based on the company fundamentals The algorithm creates ...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Demonstration of how to estimate constituents of QC500 index based on the company fundamentals
-### The algorithm creates a default tradable and liquid universe containing 500 US equities
-### which are chosen at the first trading day of each month.
-### </summary>
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="universes" />
-### <meta name="tag" content="coarse universes" />
-### <meta name="tag" content="fine universes" />
-class ConstituentsQC500GeneratorAlgorithm(QCAlgorithm):
-
- def initialize(self):
- '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
- self.universe_settings.resolution = Resolution.DAILY
-
- self.set_start_date(2018, 1, 1) # Set Start Date
- self.set_end_date(2019, 1, 1) # Set End Date
- self.set_cash(100000) # Set Strategy Cash
-
- # Add QC500 Universe
- self.add_universe(self.universe.qc_500)
diff --git a/fincept-qt/scripts/strategies/ConstituentsUniverseRegressionAlgorithm.py b/fincept-qt/scripts/strategies/ConstituentsUniverseRegressionAlgorithm.py
deleted file mode 100644
index 47b995357..000000000
--- a/fincept-qt/scripts/strategies/ConstituentsUniverseRegressionAlgorithm.py
+++ /dev/null
@@ -1,83 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-DE244AD5
-# Category: Universe Selection
-# Description: Test algorithm using a 'ConstituentsUniverse' with test data
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Test algorithm using a 'ConstituentsUniverse' with test data
-### </summary>
-class ConstituentsUniverseRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2013, 10, 7) #Set Start Date
- self.set_end_date(2013, 10, 11) #Set End Date
- self.set_cash(100000) #Set Strategy Cash
-
- self._appl = Symbol.create("AAPL", SecurityType.EQUITY, Market.USA)
- self._spy = Symbol.create("SPY", SecurityType.EQUITY, Market.USA)
- self._qqq = Symbol.create("QQQ", SecurityType.EQUITY, Market.USA)
- self._fb = Symbol.create("FB", SecurityType.EQUITY, Market.USA)
- self._step = 0
-
- self.universe_settings.resolution = Resolution.DAILY
-
- custom_universe_symbol = Symbol(SecurityIdentifier.generate_constituent_identifier(
- "constituents-universe-qctest",
- SecurityType.EQUITY,
- Market.USA),
- "constituents-universe-qctest")
-
- self.add_universe(ConstituentsUniverse(custom_universe_symbol, self.universe_settings))
-
- def on_data(self, data):
- self._step = self._step + 1
- if self._step == 1:
- if not data.contains_key(self._qqq) or not data.contains_key(self._appl):
- raise ValueError("Unexpected symbols found, step: " + str(self._step))
- if data.count != 2:
- raise ValueError("Unexpected data count, step: " + str(self._step))
- # AAPL will be deselected by the ConstituentsUniverse
- # but it shouldn't be removed since we hold it
- self.set_holdings(self._appl, 0.5)
- elif self._step == 2:
- if not data.contains_key(self._appl):
- raise ValueError("Unexpected symbols found, step: " + str(self._step))
- if data.count != 1:
- raise ValueError("Unexpected data count, step: " + str(self._step))
- # AAPL should now be released
- # note: takes one extra loop because the order is executed on market open
- self.liquidate()
- elif self._step == 3:
- if not data.contains_key(self._fb) or not data.contains_key(self._spy) or not data.contains_key(self._appl):
- raise ValueError("Unexpected symbols found, step: " + str(self._step))
- if data.count != 3:
- raise ValueError("Unexpected data count, step: " + str(self._step))
- elif self._step == 4:
- if not data.contains_key(self._fb) or not data.contains_key(self._spy):
- raise ValueError("Unexpected symbols found, step: " + str(self._step))
- if data.count != 2:
- raise ValueError("Unexpected data count, step: " + str(self._step))
-
- def on_end_of_algorithm(self):
- # First selection is on the midnight of the 8th, start getting data from the 8th to the 11th
- if self._step != 4:
- raise ValueError("Unexpected step count: " + str(self._step))
-
- def OnSecuritiesChanged(self, changes):
- for added in changes.added_securities:
- self.log(f"{self.Time} AddedSecurities " + str(added))
-
- for removed in changes.removed_securities:
- self.log(f"{self.Time} RemovedSecurities " + str(removed) + str(self._step))
- # we are currently notifying the removal of AAPl twice,
- # when deselected and when finally removed (since it stayed pending)
- if removed.symbol == self._appl and self._step != 1 and self._step != 2 or removed.symbol == self._qqq and self._step != 1:
- raise ValueError("Unexpected removal step count: " + str(self._step))
diff --git a/fincept-qt/scripts/strategies/ContinuousFutureModelsConsistencyRegressionAlgorithm.py b/fincept-qt/scripts/strategies/ContinuousFutureModelsConsistencyRegressionAlgorithm.py
deleted file mode 100644
index 1ec73f989..000000000
--- a/fincept-qt/scripts/strategies/ContinuousFutureModelsConsistencyRegressionAlgorithm.py
+++ /dev/null
@@ -1,31 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-E27B6A38
-# Category: Futures
-# Description: Regression algorithm asserting that when setting custom models for canonical future, a one-time warning is sent infor...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-from OptionModelsConsistencyRegressionAlgorithm import OptionModelsConsistencyRegressionAlgorithm
-
-### <summary>
-### Regression algorithm asserting that when setting custom models for canonical future, a one-time warning is sent
-### informing the user that the contracts models are different (not the custom ones).
-### </summary>
-class ContinuousFutureModelsConsistencyRegressionAlgorithm(OptionModelsConsistencyRegressionAlgorithm):
-
- def initialize_algorithm(self) -> Security:
- self.set_start_date(2013, 7, 1)
- self.set_end_date(2014, 1, 1)
-
- continuous_contract = self.add_future(Futures.Indices.SP_500_E_MINI,
- data_normalization_mode=DataNormalizationMode.BACKWARDS_PANAMA_CANAL,
- data_mapping_mode=DataMappingMode.OPEN_INTEREST,
- contract_depth_offset=1)
-
- return continuous_contract
diff --git a/fincept-qt/scripts/strategies/ContinuousFutureRegressionAlgorithm.py b/fincept-qt/scripts/strategies/ContinuousFutureRegressionAlgorithm.py
deleted file mode 100644
index b3f60e434..000000000
--- a/fincept-qt/scripts/strategies/ContinuousFutureRegressionAlgorithm.py
+++ /dev/null
@@ -1,88 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-C573FB46
-# Category: Futures
-# Description: Continuous Futures Regression algorithm. Asserting and showcasing the behavior of adding a continuous future
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Continuous Futures Regression algorithm. Asserting and showcasing the behavior of adding a continuous future
-### </summary>
-class ContinuousFutureRegressionAlgorithm(QCAlgorithm):
- '''Basic template algorithm simply initializes the date range and cash'''
-
- def initialize(self):
- '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
-
- self.set_start_date(2013, 7, 1)
- self.set_end_date(2014, 1, 1)
-
- self._previous_mapped_contract_symbols = []
- self._last_date_log = -1
- self._continuous_contract = self.add_future(Futures.Indices.SP_500_E_MINI,
- data_normalization_mode = DataNormalizationMode.BACKWARDS_RATIO,
- data_mapping_mode = DataMappingMode.LAST_TRADING_DAY,
- contract_depth_offset= 0)
- self._current_mapped_symbol = self._continuous_contract.symbol
-
- def on_data(self, data):
- '''on_data event is the primary entry point for your algorithm. Each new data point will be pumped in here.
-
- Arguments:
- data: Slice object keyed by symbol containing the stock data
- '''
- currently_mapped_security = self.securities[self._continuous_contract.mapped]
- if len(data.keys()) != 1:
- raise ValueError(f"We are getting data for more than one symbols! {','.join(data.keys())}")
-
- for changed_event in data.symbol_changed_events.values():
- if changed_event.symbol == self._continuous_contract.symbol:
- self._previous_mapped_contract_symbols.append(self.symbol(changed_event.old_symbol))
- self.log(f"SymbolChanged event: {changed_event}")
-
- if self._current_mapped_symbol == self._continuous_contract.mapped:
- raise ValueError(f"Continuous contract current symbol did not change! {self._continuous_contract.mapped}")
-
- if self._last_date_log != self.time.month and currently_mapped_security.has_data:
- self._last_date_log = self.time.month
-
- self.log(f"{self.time}- {currently_mapped_security.get_last_data()}")
- if self.portfolio.invested:
- self.liquidate()
- else:
- # This works because we set this contract as tradable, even if it's a canonical security
- self.buy(currently_mapped_security.symbol, 1)
-
- if self.time.month == 1 and self.time.year == 2013:
- response = self.history( [ self._continuous_contract.symbol ], 60 * 24 * 90)
- if response.empty:
- raise ValueError("Unexpected empty history response")
-
- self._current_mapped_symbol = self._continuous_contract.mapped
-
- def on_order_event(self, order_event):
- if order_event.status == OrderStatus.FILLED:
- self.debug("Purchased Stock: {0}".format(order_event.symbol))
-
- def on_securities_changed(self, changes):
- self.debug(f"{self.time}-{changes}")
-
- def on_end_of_algorithm(self):
- expected_mapping_counts = 2
- if len(self._previous_mapped_contract_symbols) != expected_mapping_counts:
- raise ValueError(f"Unexpected symbol changed events: {len(self._previous_mapped_contract_symbols)}, was expecting {expected_mapping_counts}")
-
- delisted_securities = [
- [security for security in self.securities.total if security.symbol == symbol][0]
- for symbol in self._previous_mapped_contract_symbols
- ]
- marked_delisted_securities = [security for security in delisted_securities if security.is_delisted and not security.is_tradable]
- if len(marked_delisted_securities) != len(delisted_securities):
- raise ValueError(f"Not all delisted contracts are properly marked as delisted and non-tradable: "
- f"only {len(marked_delisted_securities)} are marked, was expecting {len(delisted_securities)}")
diff --git a/fincept-qt/scripts/strategies/ConvertToFrameworkAlgorithm.py b/fincept-qt/scripts/strategies/ConvertToFrameworkAlgorithm.py
deleted file mode 100644
index e377fedc4..000000000
--- a/fincept-qt/scripts/strategies/ConvertToFrameworkAlgorithm.py
+++ /dev/null
@@ -1,90 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-E9C47E95
-# Category: General Strategy
-# Description: Demonstration algorithm showing how to easily convert an old algorithm into the framework. ### 1. When making orders...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Demonstration algorithm showing how to easily convert an old algorithm into the framework.
-###
-### 1. When making orders, also create insights for the correct direction (up/down/flat), can also set insight prediction period/magnitude/direction
-### 2. Emit insights before placing any trades
-### 3. Profit :)
-### </summary>
-### <meta name="tag" content="indicators" />
-### <meta name="tag" content="indicator classes" />
-### <meta name="tag" content="plotting indicators" />
-class ConvertToFrameworkAlgorithm(QCAlgorithm):
- '''Demonstration algorithm showing how to easily convert an old algorithm into the framework.'''
-
- fast_ema_period = 12
- slow_ema_period = 26
-
- def initialize(self):
- '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
-
- self.set_start_date(2004, 1, 1)
- self.set_end_date(2015, 1, 1)
-
- self._symbol = self.add_security(SecurityType.EQUITY, 'SPY', Resolution.DAILY).symbol
-
- # define our daily macd(12,26) with a 9 day signal
- self._macd = self.macd(self._symbol, self.fast_ema_period, self.slow_ema_period, 9, MovingAverageType.EXPONENTIAL, Resolution.DAILY)
-
-
- def on_data(self, data):
- '''on_data event is the primary entry point for your algorithm. Each new data point will be pumped in here.
- Args:
- data: Slice object with your stock data'''
- # wait for our indicator to be ready
- if not self._macd.is_ready or not data.contains_key(self._symbol) or data[self._symbol] is None: return
-
- holding = self.portfolio[self._symbol]
-
- signal_delta_percent = float(self._macd.current.value - self._macd.signal.current.value) / float(self._macd.fast.current.value)
- tolerance = 0.0025
-
- # if our macd is greater than our signal, then let's go long
- if holding.quantity <= 0 and signal_delta_percent > tolerance:
- # 1. Call emit_insights with insights created in correct direction, here we're going long
- # The emit_insights method can accept multiple insights separated by commas
- self.emit_insights(
- # Creates an insight for our symbol, predicting that it will move up within the fast ema period number of days
- Insight.price(self._symbol, timedelta(self.fast_ema_period), InsightDirection.UP)
- )
-
- # longterm says buy as well
- self.set_holdings(self._symbol, 1)
-
- # if our macd is less than our signal, then let's go short
- elif holding.quantity >= 0 and signal_delta_percent < -tolerance:
- # 1. Call emit_insights with insights created in correct direction, here we're going short
- # The emit_insights method can accept multiple insights separated by commas
- self.emit_insights(
- # Creates an insight for our symbol, predicting that it will move down within the fast ema period number of days
- Insight.price(self._symbol, timedelta(self.fast_ema_period), InsightDirection.DOWN)
- )
-
- self.set_holdings(self._symbol, -1)
-
- # if we wanted to liquidate our positions
- ## 1. Call emit_insights with insights create in the correct direction -- Flat
-
- #self.emit_insights(
- # Creates an insight for our symbol, predicting that it will move down or up within the fast ema period number of days, depending on our current position
- # Insight.price(self._symbol, timedelta(self.fast_ema_period), InsightDirection.FLAT)
- #)
-
- # self.liquidate()
-
- # plot both lines
- self.plot("MACD", self._macd, self._macd.signal)
- self.plot(self._symbol.value, self._macd.fast, self._macd.slow)
- self.plot(self._symbol.value, "Open", data[self._symbol].open)
diff --git a/fincept-qt/scripts/strategies/CorrectConsolidatedBarTypeForTickTypesAlgorithm.py b/fincept-qt/scripts/strategies/CorrectConsolidatedBarTypeForTickTypesAlgorithm.py
deleted file mode 100644
index 5f37b7254..000000000
--- a/fincept-qt/scripts/strategies/CorrectConsolidatedBarTypeForTickTypesAlgorithm.py
+++ /dev/null
@@ -1,51 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-C0F56022
-# Category: Data Consolidation
-# Description: Algorithm asserting that consolidated bars are of type `QuoteBar` when `QCAlgorithm.consolidate()` is called with `ti...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Algorithm asserting that consolidated bars are of type `QuoteBar` when `QCAlgorithm.consolidate()` is called with `tick_type=TickType.QUOTE`
-### </summary>
-class CorrectConsolidatedBarTypeForTickTypesAlgorithm(QCAlgorithm):
- def initialize(self):
- self.set_start_date(2013, 10, 7)
- self.set_end_date(2013, 10, 7)
-
- symbol = self.add_equity("SPY", Resolution.TICK).symbol
-
- self.consolidate(symbol, timedelta(minutes=1), TickType.QUOTE, self.quote_tick_consolidation_handler)
- self.consolidate(symbol, timedelta(minutes=1), TickType.TRADE, self.trade_tick_consolidation_handler)
-
- self.quote_tick_consolidation_handler_called = False
- self.trade_tick_consolidation_handler_called = False
-
- def on_data(self, slice: Slice) -> None:
- if self.time.hour > 9:
- self.quit("Early quit to save time")
-
- def on_end_of_algorithm(self):
- if not self.quote_tick_consolidation_handler_called:
- raise Exception("quote_tick_consolidation_handler was not called")
-
- if not self.trade_tick_consolidation_handler_called:
- raise Exception("trade_tick_consolidation_handler was not called")
-
- def quote_tick_consolidation_handler(self, consolidated_bar: QuoteBar) -> None:
- if type(consolidated_bar) != QuoteBar:
- raise Exception(f"Expected the consolidated bar to be of type {QuoteBar} but was {type(consolidated_bar)}")
-
- self.quote_tick_consolidation_handler_called = True
-
- def trade_tick_consolidation_handler(self, consolidated_bar: TradeBar) -> None:
- if type(consolidated_bar) != TradeBar:
- raise Exception(f"Expected the consolidated bar to be of type {TradeBar} but was {type(consolidated_bar)}")
-
- self.trade_tick_consolidation_handler_called = True
diff --git a/fincept-qt/scripts/strategies/CoveredAndProtectiveCallStrategiesAlgorithm.py b/fincept-qt/scripts/strategies/CoveredAndProtectiveCallStrategiesAlgorithm.py
deleted file mode 100644
index b8c4e1ae2..000000000
--- a/fincept-qt/scripts/strategies/CoveredAndProtectiveCallStrategiesAlgorithm.py
+++ /dev/null
@@ -1,52 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-0AD9A342
-# Category: General Strategy
-# Description: Protective position management strategy inspired by covered call
-# mechanics. Buys SPY and uses trailing stop logic to protect profits. Enters
-# on EMA uptrend, exits with 3% trailing stop loss.
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-class CoveredAndProtectiveCallStrategiesAlgorithm(QCAlgorithm):
- """Trend-following with trailing stop loss (protective strategy)."""
-
- def initialize(self):
- self.set_start_date(2023, 1, 1)
- self.set_end_date(2024, 1, 1)
- self.set_cash(100000)
-
- self.symbol = "SPY"
- self.add_equity(self.symbol, Resolution.DAILY)
-
- self._ema = self.ema(self.symbol, 20, Resolution.DAILY)
- self._highest_since_entry = 0.0
-
- def on_data(self, data):
- if not self._ema.is_ready:
- return
- if self.symbol not in data:
- return
-
- price = data[self.symbol].close
-
- if not self.portfolio.invested:
- # Enter when price above EMA (uptrend)
- if price > self._ema.current.value:
- self.set_holdings(self.symbol, 1)
- self._highest_since_entry = price
- else:
- # Track highest price since entry
- if price > self._highest_since_entry:
- self._highest_since_entry = price
-
- # Trailing stop: exit if price drops 3% from peak
- drawdown = (self._highest_since_entry - price) / self._highest_since_entry
- if drawdown > 0.03:
- self.liquidate()
- self._highest_since_entry = 0.0
diff --git a/fincept-qt/scripts/strategies/CoveredAndProtectivePutStrategiesAlgorithm.py b/fincept-qt/scripts/strategies/CoveredAndProtectivePutStrategiesAlgorithm.py
deleted file mode 100644
index a29eb5447..000000000
--- a/fincept-qt/scripts/strategies/CoveredAndProtectivePutStrategiesAlgorithm.py
+++ /dev/null
@@ -1,58 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-485EB46A
-# Category: General Strategy
-# Description: This algorithm demonstrate how to use OptionStrategies helper class to batch send orders for common strategies. In th...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-from OptionStrategyFactoryMethodsBaseAlgorithm import *
-
-### <summary>
-### This algorithm demonstrate how to use OptionStrategies helper class to batch send orders for common strategies.
-### In this case, the algorithm tests the Covered and Protective Put strategies.
-### </summary>
-class CoveredAndProtectivePutStrategiesAlgorithm(OptionStrategyFactoryMethodsBaseAlgorithm):
-
- def expected_orders_count(self) -> int:
- return 4
-
- def trade_strategy(self, chain: OptionChain, option_symbol: Symbol):
- contracts = sorted(sorted(chain, key = lambda x: abs(chain.underlying.price - x.strike)),
- key = lambda x: x.expiry, reverse=True)
-
- if len(contracts) == 0: return
- contract = contracts[0]
- if contract != None:
- self._covered_put = OptionStrategies.covered_put(option_symbol, contract.strike, contract.expiry)
- self._protective_put = OptionStrategies.protective_put(option_symbol, contract.strike, contract.expiry)
- self.buy(self._covered_put, 2)
-
-
- def assert_strategy_position_group(self, position_group: IPositionGroup, option_symbol: Symbol):
- positions = list(position_group.positions)
- if len(positions) != 2:
- raise Exception(f"Expected position group to have 2 positions. Actual: {len(positions)}")
-
- option_position = [position for position in positions if position.symbol.security_type == SecurityType.OPTION][0]
- if option_position.symbol.id.option_right != OptionRight.PUT:
- raise Exception(f"Expected option position to be a put. Actual: {option_position.symbol.id.option_right}")
-
- underlying_position = [position for position in positions if position.symbol.security_type == SecurityType.EQUITY][0]
- expected_option_position_quantity = -2
- expected_underlying_position_quantity = -2 * self.securities[option_symbol].symbol_properties.contract_multiplier
-
- if option_position.quantity != expected_option_position_quantity:
- raise Exception(f"Expected option position quantity to be {expected_option_position_quantity}. Actual: {option_position.quantity}")
-
- if underlying_position.quantity != expected_underlying_position_quantity:
- raise Exception(f"Expected underlying position quantity to be {expected_underlying_position_quantity}. Actual: {underlying_position.quantity}")
-
- def liquidate_strategy(self):
- # We should be able to close the position using the inverse strategy (a protective put)
- self.buy(self._protective_put, 2)
diff --git a/fincept-qt/scripts/strategies/CrunchDAOSignalExportDemonstrationAlgorithm.py b/fincept-qt/scripts/strategies/CrunchDAOSignalExportDemonstrationAlgorithm.py
deleted file mode 100644
index 2c2d48b05..000000000
--- a/fincept-qt/scripts/strategies/CrunchDAOSignalExportDemonstrationAlgorithm.py
+++ /dev/null
@@ -1,109 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-B5A1B412
-# Category: General Strategy
-# Description: This algorithm sends portfolio targets to CrunchDAO API once a week
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### This algorithm sends portfolio targets to CrunchDAO API once a week.
-### </summary>
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="using quantconnect" />
-### <meta name="tag" content="securities and portfolio" />
-class CrunchDAOSignalExportDemonstrationAlgorithm(QCAlgorithm):
-
- crunch_universe = []
-
- def initialize(self):
- self.set_start_date(2023, 5, 22)
- self.set_end_date(2023, 5, 26)
- self.set_cash(1_000_000)
-
- # Connect to CrunchDAO
- api_key = "" # Your CrunchDAO API key
- model = "" # The Id of your CrunchDAO model
- submission_name = "" # A name for the submission to distinguish it from your other submissions
- comment = "" # A comment for the submission
- self.signal_export.add_signal_export_providers(CrunchDAOSignalExport(api_key, model, submission_name, comment))
-
- self.set_security_initializer(BrokerageModelSecurityInitializer(self.brokerage_model, FuncSecuritySeeder(self.get_last_known_prices)))
-
- # Add a custom data universe to read the CrunchDAO skeleton
- self.add_universe(CrunchDaoSkeleton, "CrunchDaoSkeleton", Resolution.DAILY, self.select_symbols)
-
- # Create a Scheduled Event to submit signals every monday before the market opens
- self.week = -1
- self.schedule.on(
- self.date_rules.every([DayOfWeek.MONDAY, DayOfWeek.TUESDAY, DayOfWeek.WEDNESDAY, DayOfWeek.THURSDAY, DayOfWeek.FRIDAY]),
- self.time_rules.at(13, 15, TimeZones.UTC),
- self.submit_signals)
-
- self.settings.minimum_order_margin_portfolio_percentage = 0
-
- self.set_warm_up(timedelta(45))
-
- def select_symbols(self, data: List[CrunchDaoSkeleton]) -> List[Symbol]:
- return [x.symbol for x in data]
-
- def on_securities_changed(self, changes):
- for security in changes.removed_securities:
- if security in self.crunch_universe:
- self.crunch_universe.remove(security)
- self.crunch_universe.extend(changes.added_securities)
-
- def submit_signals(self):
- if self.is_warming_up:
- return
-
- # Submit signals once per week
- week_num = self.time.isocalendar()[1]
- if self.week == week_num:
- return
- self.week = week_num
-
- symbols = [security.symbol for security in self.crunch_universe if security.price > 0]
-
- # Get historical price data
- # close_prices = self.history(symbols, 22, Resolution.DAILY).close.unstack(0)
-
- # Create portfolio targets
- weight_by_symbol = {symbol: 1/len(symbols) for symbol in symbols} # Add your logic here
- targets = [PortfolioTarget(symbol, weight) for symbol, weight in weight_by_symbol.items()]
-
- # (Optional) Place trades
- self.set_holdings(targets)
-
- # Send signals to CrunchDAO
- success = self.signal_export.set_target_portfolio(targets)
- if not success:
- self.debug(f"Couldn't send targets at {self.time}")
-
-
-class CrunchDaoSkeleton(PythonData):
-
- def get_source(self, config, date, is_live):
- return SubscriptionDataSource("https://tournament.crunchdao.com/data/skeleton.csv", SubscriptionTransportMedium.REMOTE_FILE)
-
- def reader(self, config, line, date, is_live):
- if not line[0].isdigit(): return None
- skeleton = CrunchDaoSkeleton()
- skeleton.symbol = config.symbol
-
- try:
- csv = line.split(',')
- skeleton.end_time = (datetime.strptime(csv[0], "%Y-%m-%d")).date()
- skeleton.symbol = Symbol(SecurityIdentifier.generate_equity(csv[1], Market.USA, mapping_resolve_date=skeleton.time), csv[1])
- skeleton["Ticker"] = csv[1]
-
- except ValueError:
- # Do nothing
- return None
-
- return skeleton
diff --git a/fincept-qt/scripts/strategies/CustomBenchmarkAlgorithm.py b/fincept-qt/scripts/strategies/CustomBenchmarkAlgorithm.py
deleted file mode 100644
index 2224c6db9..000000000
--- a/fincept-qt/scripts/strategies/CustomBenchmarkAlgorithm.py
+++ /dev/null
@@ -1,44 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-390AE467
-# Category: Benchmark
-# Description: Shows how to set a custom benchmark for you algorithms
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Shows how to set a custom benchmark for you algorithms
-### </summary>
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="benchmarks" />
-class CustomBenchmarkAlgorithm(QCAlgorithm):
-
- def initialize(self):
- '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
-
- self.set_start_date(2013,10,7) #Set Start Date
- self.set_end_date(2013,10,11) #Set End Date
- self.set_cash(100000) #Set Strategy Cash
- # Fincept Terminal Strategy Engine - Symbol Configuration
- self.add_equity("SPY", Resolution.SECOND)
-
- # Disabling the benchmark / setting to a fixed value
- # self.set_benchmark(lambda x: 0)
-
- # Set the benchmark to AAPL US Equity
- self.set_benchmark(Symbol.create("AAPL", SecurityType.EQUITY, Market.USA))
-
- def on_data(self, data):
- '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.'''
- if not self.portfolio.invested:
- self.set_holdings("SPY", 1)
- self.debug("Purchased Stock")
-
- tuple_result = SymbolCache.try_get_symbol("AAPL", None)
- if tuple_result[0]:
- raise Exception("Benchmark Symbol is not expected to be added to the Symbol cache")
diff --git a/fincept-qt/scripts/strategies/CustomBenchmarkRegressionAlgorithm.py b/fincept-qt/scripts/strategies/CustomBenchmarkRegressionAlgorithm.py
deleted file mode 100644
index d0f8b5b8c..000000000
--- a/fincept-qt/scripts/strategies/CustomBenchmarkRegressionAlgorithm.py
+++ /dev/null
@@ -1,43 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-F72D9CA4
-# Category: Regression Test
-# Description: Regression algorithm to test we can specify a custom benchmark model, and override some of its methods
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-from CustomBrokerageModelRegressionAlgorithm import CustomBrokerageModel
-
-### <summary>
-### Regression algorithm to test we can specify a custom benchmark model, and override some of its methods
-### </summary>
-class CustomBenchmarkRegressionAlgorithm(QCAlgorithm):
- def initialize(self):
- self.set_start_date(2013,10,7)
- self.set_end_date(2013,10,11)
- self.set_brokerage_model(CustomBrokerageModelWithCustomBenchmark())
- self.add_equity("SPY", Resolution.DAILY)
- self.update_request_submitted = False
-
- def on_data(self, slice):
- benchmark = self.benchmark.evaluate(self.time)
- if (self.time.day % 2 == 0) and (benchmark != 1):
- raise Exception(f"Benchmark should be 1, but was {benchmark}")
-
- if (self.time.day % 2 == 1) and (benchmark != 2):
- raise Exception(f"Benchmark should be 2, but was {benchmark}")
-
-class CustomBenchmark:
- def evaluate(self, time):
- if time.day % 2 == 0:
- return 1
- else:
- return 2
-
-class CustomBrokerageModelWithCustomBenchmark(CustomBrokerageModel):
- def get_benchmark(self, securities):
- return CustomBenchmark()
diff --git a/fincept-qt/scripts/strategies/CustomBrokerageModelRegressionAlgorithm.py b/fincept-qt/scripts/strategies/CustomBrokerageModelRegressionAlgorithm.py
deleted file mode 100644
index 6a99cbf04..000000000
--- a/fincept-qt/scripts/strategies/CustomBrokerageModelRegressionAlgorithm.py
+++ /dev/null
@@ -1,64 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-BDF6639E
-# Category: Regression Test
-# Description: Regression algorithm to test we can specify a custom brokerage model, and override some of its methods
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Regression algorithm to test we can specify a custom brokerage model, and override some of its methods
-### </summary>
-class CustomBrokerageModelRegressionAlgorithm(QCAlgorithm):
- def initialize(self):
- self.set_start_date(2013,10,7)
- self.set_end_date(2013,10,11)
- self.set_brokerage_model(CustomBrokerageModel())
- self.add_equity("SPY", Resolution.DAILY)
- self.add_equity("AIG", Resolution.DAILY)
- self.update_request_submitted = False
-
- if self.brokerage_model.default_markets[SecurityType.EQUITY] != Market.USA:
- raise Exception(f"The default market for Equity should be {Market.USA}")
- if self.brokerage_model.default_markets[SecurityType.CRYPTO] != Market.BINANCE:
- raise Exception(f"The default market for Crypto should be {Market.BINANCE}")
-
- def on_data(self, slice):
- if not self.portfolio.invested:
- self.market_order("SPY", 100.0)
- self.aig_ticket = self.market_order("AIG", 100.0)
-
- def on_order_event(self, order_event):
- spy_ticket = self.transactions.get_order_ticket(order_event.order_id)
- if self.update_request_submitted == False:
- update_order_fields = UpdateOrderFields()
- update_order_fields.quantity = spy_ticket.quantity + 10
- spy_ticket.update(update_order_fields)
- self.spy_ticket = spy_ticket
- self.update_request_submitted = True
-
- def on_end_of_algorithm(self):
- submit_expected_message = "BrokerageModel declared unable to submit order: [2] Information - Code: - Symbol AIG can not be submitted"
- if self.aig_ticket.submit_request.response.error_message != submit_expected_message:
- raise Exception(f"Order with ID: {self.aig_ticket.order_id} should not have submitted symbol AIG")
- update_expected_message = "OrderID: 1 Information - Code: - This order can not be updated"
- if self.spy_ticket.update_requests[0].response.error_message != update_expected_message:
- raise Exception(f"Order with ID: {self.spy_ticket.order_id} should have been updated")
-
-class CustomBrokerageModel(DefaultBrokerageModel):
- default_markets = { SecurityType.EQUITY: Market.USA, SecurityType.CRYPTO : Market.BINANCE }
-
- def can_submit_order(self, security: SecurityType, order: Order, message: BrokerageMessageEvent):
- if security.symbol.value == "AIG":
- message = BrokerageMessageEvent(BrokerageMessageType.INFORMATION, "", "Symbol AIG can not be submitted")
- return False, message
- return True, None
-
- def can_update_order(self, security: SecurityType, order: Order, request: UpdateOrderRequest, message: BrokerageMessageEvent):
- message = BrokerageMessageEvent(BrokerageMessageType.INFORMATION, "", "This order can not be updated")
- return False, message
diff --git a/fincept-qt/scripts/strategies/CustomBrokerageSideOrderHandlingRegressionAlgorithm.py b/fincept-qt/scripts/strategies/CustomBrokerageSideOrderHandlingRegressionAlgorithm.py
deleted file mode 100644
index 545cec97d..000000000
--- a/fincept-qt/scripts/strategies/CustomBrokerageSideOrderHandlingRegressionAlgorithm.py
+++ /dev/null
@@ -1,59 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-D2A1A24A
-# Category: Regression Test
-# Description: Algorithm demonstrating the usage of custom brokerage message handler and the new brokerage-side order handling/filte...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Algorithm demonstrating the usage of custom brokerage message handler and the new brokerage-side order handling/filtering.
-### This test is supposed to be ran by the CustomBrokerageMessageHandlerTests unit test fixture.
-###
-### All orders are sent from the brokerage, none of them will be placed by the algorithm.
-### </summary>
-class CustomBrokerageSideOrderHandlingRegressionAlgorithm(QCAlgorithm):
- '''Algorithm demonstrating the usage of custom brokerage message handler and the new brokerage-side order handling/filtering.
- This test is supposed to be ran by the CustomBrokerageMessageHandlerTests unit test fixture.
-
- All orders are sent from the brokerage, none of them will be placed by the algorithm.'''
-
- def initialize(self):
- self.set_start_date(2013, 10, 7)
- self.set_end_date(2013, 10, 11)
- self.set_cash(100000)
-
- self.set_brokerage_message_handler(CustomBrokerageMessageHandler(self))
-
- self._spy = Symbol.create("SPY", SecurityType.EQUITY, Market.USA)
-
- def on_end_of_algorithm(self):
- # The security should have been added
- if not self.securities.contains_key(self._spy):
- raise Exception("Expected security to have been added")
-
- if self.transactions.orders_count == 0:
- raise Exception("Expected orders to be added from brokerage side")
-
- if len(list(self.portfolio.positions.groups)) != 1:
- raise Exception("Expected only one position")
-
-class CustomBrokerageMessageHandler(DefaultBrokerageMessageHandler):
- def __init__(self, algorithm):
- self._algorithm = algorithm
-
- def handle_message(self, message):
- self._algorithm.debug(f"{self._algorithm.time} Event: {message.message}")
-
- def handle_order(self, event_args):
- order = event_args.order
- if order.tag is None or not order.tag.isdigit():
- raise Exception("Expected all new brokerage-side orders to have a valid tag")
-
- # We will only process orders with even tags
- return int(order.tag) % 2 == 0
diff --git a/fincept-qt/scripts/strategies/CustomBrokerageSideOrderHandlingRegressionPartialAlgorithm.py b/fincept-qt/scripts/strategies/CustomBrokerageSideOrderHandlingRegressionPartialAlgorithm.py
deleted file mode 100644
index 8cfa072c9..000000000
--- a/fincept-qt/scripts/strategies/CustomBrokerageSideOrderHandlingRegressionPartialAlgorithm.py
+++ /dev/null
@@ -1,57 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-335819E6
-# Category: Regression Test
-# Description: Algorithm demonstrating the usage of custom brokerage message handler and the new brokerage-side order handling/filte...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Algorithm demonstrating the usage of custom brokerage message handler and the new brokerage-side order handling/filtering.
-### This test is supposed to be ran by the CustomBrokerageMessageHandlerTests unit test fixture.
-###
-### All orders are sent from the brokerage, none of them will be placed by the algorithm.
-### </summary>
-class CustomBrokerageSideOrderHandlingRegressionPartialAlgorithm(QCAlgorithm):
- '''Algorithm demonstrating the usage of custom brokerage message handler and the new brokerage-side order handling/filtering.
- This test is supposed to be ran by the CustomBrokerageMessageHandlerTests unit test fixture.
-
- All orders are sent from the brokerage, none of them will be placed by the algorithm.'''
-
- def initialize(self):
- self.set_start_date(2013, 10, 7)
- self.set_end_date(2013, 10, 11)
- self.set_cash(100000)
-
- self.set_brokerage_message_handler(CustomBrokerageMessageHandler(self))
-
- self._spy = Symbol.create("SPY", SecurityType.EQUITY, Market.USA)
-
- def on_end_of_algorithm(self):
- # The security should have been added
- if not self.securities.contains_key(self._spy):
- raise Exception("Expected security to have been added")
-
- if self.transactions.orders_count == 0:
- raise Exception("Expected orders to be added from brokerage side")
-
- if len(list(self.portfolio.positions.groups)) != 1:
- raise Exception("Expected only one position")
-
-class CustomBrokerageMessageHandler(DefaultBrokerageMessageHandler):
- def __init__(self, algorithm):
- super().__init__(algorithm)
- self._algorithm = algorithm
-
- def handle_order(self, event_args):
- order = event_args.order
- if order.tag is None or not order.tag.isdigit():
- raise Exception("Expected all new brokerage-side orders to have a valid tag")
-
- # We will only process orders with even tags
- return int(order.tag) % 2 == 0
diff --git a/fincept-qt/scripts/strategies/CustomBuyingPowerModelAlgorithm.py b/fincept-qt/scripts/strategies/CustomBuyingPowerModelAlgorithm.py
deleted file mode 100644
index 357eba971..000000000
--- a/fincept-qt/scripts/strategies/CustomBuyingPowerModelAlgorithm.py
+++ /dev/null
@@ -1,63 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-DC4DC088
-# Category: General Strategy
-# Description: Demonstration of using custom buying power model in backtesting. QuantConnect allows you to model all orders as deepl...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Demonstration of using custom buying power model in backtesting.
-### QuantConnect allows you to model all orders as deeply and accurately as you need.
-### </summary>
-### <meta name="tag" content="trading and orders" />
-### <meta name="tag" content="transaction fees and slippage" />
-### <meta name="tag" content="custom buying power models" />
-class CustomBuyingPowerModelAlgorithm(QCAlgorithm):
- '''Demonstration of using custom buying power model in backtesting.
- QuantConnect allows you to model all orders as deeply and accurately as you need.'''
-
- def initialize(self):
- self.set_start_date(2013,10,1) # Set Start Date
- self.set_end_date(2013,10,31) # Set End Date
- security = self.add_equity("SPY", Resolution.HOUR)
- self.spy = security.symbol
-
- # set the buying power model
- security.set_buying_power_model(CustomBuyingPowerModel())
-
- def on_data(self, slice):
- if self.portfolio.invested:
- return
-
- quantity = self.calculate_order_quantity(self.spy, 1)
- if quantity % 100 != 0:
- raise Exception(f'CustomBuyingPowerModel only allow quantity that is multiple of 100 and {quantity} was found')
-
- # We normally get insufficient buying power model, but the
- # CustomBuyingPowerModel always says that there is sufficient buying power for the orders
- self.market_order(self.spy, quantity * 10)
-
-
-class CustomBuyingPowerModel(BuyingPowerModel):
- def get_maximum_order_quantity_for_target_buying_power(self, parameters):
- quantity = super().get_maximum_order_quantity_for_target_buying_power(parameters).quantity
- quantity = np.floor(quantity / 100) * 100
- return GetMaximumOrderQuantityResult(quantity)
-
- def has_sufficient_buying_power_for_order(self, parameters):
- return HasSufficientBuyingPowerForOrderResult(True)
-
- # Let's always return 0 as the maintenance margin so we avoid margin call orders
- def get_maintenance_margin(self, parameters):
- return MaintenanceMargin(0)
-
- # Override this as well because the base implementation calls GetMaintenanceMargin (overridden)
- # because in C# it wouldn't resolve the overridden Python method
- def get_reserved_buying_power_for_position(self, parameters):
- return parameters.result_in_account_currency(0)
diff --git a/fincept-qt/scripts/strategies/CustomChartingAlgorithm.py b/fincept-qt/scripts/strategies/CustomChartingAlgorithm.py
deleted file mode 100644
index 598a67a71..000000000
--- a/fincept-qt/scripts/strategies/CustomChartingAlgorithm.py
+++ /dev/null
@@ -1,86 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-DAAB71C9
-# Category: General Strategy
-# Description: Algorithm demonstrating custom charting support in QuantConnect. The entire charting system of quantconnect is adapta...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Algorithm demonstrating custom charting support in QuantConnect.
-### The entire charting system of quantconnect is adaptable. You can adjust it to draw whatever you'd like.
-### Charts can be stacked, or overlayed on each other. Series can be candles, lines or scatter plots.
-### Even the default behaviours of QuantConnect can be overridden.
-### </summary>
-### <meta name="tag" content="charting" />
-### <meta name="tag" content="adding charts" />
-### <meta name="tag" content="series types" />
-### <meta name="tag" content="plotting indicators" />
-class CustomChartingAlgorithm(QCAlgorithm):
- def initialize(self):
- self.set_start_date(2016,1,1)
- self.set_end_date(2017,1,1)
- self.set_cash(100000)
-
- spy = self.add_equity("SPY", Resolution.DAILY).symbol
-
- # In your initialize method:
- # Chart - Master Container for the Chart:
- stock_plot = Chart("Trade Plot")
- # On the Trade Plotter Chart we want 3 series: trades and price:
- stock_plot.add_series(Series("Buy", SeriesType.SCATTER, 0))
- stock_plot.add_series(Series("Sell", SeriesType.SCATTER, 0))
- stock_plot.add_series(Series("Price", SeriesType.LINE, 0))
- self.add_chart(stock_plot)
-
- # On the Average Cross Chart we want 2 series, slow MA and fast MA
- avg_cross = Chart("Average Cross")
- avg_cross.add_series(Series("FastMA", SeriesType.LINE, 0))
- avg_cross.add_series(Series("SlowMA", SeriesType.LINE, 0))
- self.add_chart(avg_cross)
-
- # There's support for candlestick charts built-in:
- weekly_spy_plot = Chart("Weekly SPY")
- spy_candlesticks = CandlestickSeries("SPY")
- weekly_spy_plot.add_series(spy_candlesticks)
- self.add_chart(weekly_spy_plot)
-
- self.consolidate(spy, Calendar.WEEKLY, lambda bar: self.plot("Weekly SPY", "SPY", bar))
-
- self.fast_ma = 0
- self.slow_ma = 0
- self.last_price = 0
- self.resample = datetime.min
- self.resample_period = (self.end_date - self.start_date) / 2000
-
- def on_data(self, slice):
- if slice["SPY"] is None: return
-
- self.last_price = slice["SPY"].close
- if self.fast_ma == 0: self.fast_ma = self.last_price
- if self.slow_ma == 0: self.slow_ma = self.last_price
- self.fast_ma = (0.01 * self.last_price) + (0.99 * self.fast_ma)
- self.slow_ma = (0.001 * self.last_price) + (0.999 * self.slow_ma)
-
-
- if self.time > self.resample:
- self.resample = self.time + self.resample_period
- self.plot("Average Cross", "FastMA", self.fast_ma)
- self.plot("Average Cross", "SlowMA", self.slow_ma)
-
- # On the 5th days when not invested buy:
- if not self.portfolio.invested and self.time.day % 13 == 0:
- self.order("SPY", (int)(self.portfolio.margin_remaining / self.last_price))
- self.plot("Trade Plot", "Buy", self.last_price)
- elif self.time.day % 21 == 0 and self.portfolio.invested:
- self.plot("Trade Plot", "Sell", self.last_price)
- self.liquidate()
-
- def on_end_of_day(self, symbol):
- #Log the end of day prices:
- self.plot("Trade Plot", "Price", self.last_price)
diff --git a/fincept-qt/scripts/strategies/CustomConsolidatorRegressionAlgorithm.py b/fincept-qt/scripts/strategies/CustomConsolidatorRegressionAlgorithm.py
deleted file mode 100644
index 804ccf124..000000000
--- a/fincept-qt/scripts/strategies/CustomConsolidatorRegressionAlgorithm.py
+++ /dev/null
@@ -1,166 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-5FE7DA42
-# Category: Data Consolidation
-# Description: Custom Consolidator Regression Algorithm shows some examples of how to build custom
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-class CustomConsolidatorRegressionAlgorithm(QCAlgorithm):
- '''Custom Consolidator Regression Algorithm shows some examples of how to build custom
- consolidators in Python.'''
-
- def initialize(self):
- self.set_start_date(2013,10,4)
- self.set_end_date(2013,10,11)
- self.set_cash(100000)
- self.add_equity("SPY", Resolution.MINUTE)
-
- #Create 5 day QuoteBarConsolidator; set consolidated function; add to subscription manager
- five_day_consolidator = QuoteBarConsolidator(timedelta(days=5))
- five_day_consolidator.data_consolidated += self.on_quote_bar_data_consolidated
- self.subscription_manager.add_consolidator("SPY", five_day_consolidator)
-
- #Create a 3:10PM custom quote bar consolidator
- timed_consolidator = DailyTimeQuoteBarConsolidator(time(hour=15, minute=10))
- timed_consolidator.data_consolidated += self.on_quote_bar_data_consolidated
- self.subscription_manager.add_consolidator("SPY", timed_consolidator)
-
- #Create our entirely custom 2 day quote bar consolidator
- self.custom_consolidator = CustomQuoteBarConsolidator(timedelta(days=2))
- self.custom_consolidator.data_consolidated += (self.on_quote_bar_data_consolidated)
- self.subscription_manager.add_consolidator("SPY", self.custom_consolidator)
-
- #Create an indicator and register a consolidator to it
- self.moving_average = SimpleMovingAverage(5)
- self.custom_consolidator2 = CustomQuoteBarConsolidator(timedelta(hours=1))
- self.register_indicator("SPY", self.moving_average, self.custom_consolidator2)
-
-
- def on_quote_bar_data_consolidated(self, sender, bar):
- '''Function assigned to be triggered by consolidators.
- Designed to post debug messages to show how the examples work, including
- which consolidator is posting, as well as its values.
-
- If using an inherited class and not overwriting OnDataConsolidated
- we expect to see the super C# class as the sender type.
-
- Using sender.period only works when all consolidators have a Period value.
- '''
-
- consolidator_info = str(type(sender)) + str(sender.period)
-
- self.debug("Bar Type: " + consolidator_info)
- self.debug("Bar Range: " + bar.time.ctime() + " - " + bar.end_time.ctime())
- self.debug("Bar value: " + str(bar.close))
-
- def on_data(self, slice):
- test = slice.get_values()
-
- if self.custom_consolidator.consolidated and slice.contains_key("SPY"):
- data = slice['SPY']
-
- if self.moving_average.is_ready:
- if data.value > self.moving_average.current.price:
- self.set_holdings("SPY", .5)
- else :
- self.set_holdings("SPY", 0)
-
-
-
-class DailyTimeQuoteBarConsolidator(QuoteBarConsolidator):
- '''A custom QuoteBar consolidator that inherits from C# class QuoteBarConsolidator.
-
- This class shows an example of building on top of an existing consolidator class, it is important
- to note that this class can leverage the functions of QuoteBarConsolidator but its private fields
- (_period, _workingbar, etc.) are separate from this Python. For that reason if we want Scan() to work
- we must overwrite the function with our desired Scan function and trigger OnDataConsolidated().
-
- For this particular example we implemented the scan method to trigger a consolidated bar
- at close_time everyday'''
-
- def __init__(self, close_time):
- self.close_time = close_time
- self.working_bar = None
-
- def update(self, data):
- '''Updates this consolidator with the specified data'''
-
- #If we don't have bar yet, create one
- if self.working_bar is None:
- self.working_bar = QuoteBar(data.time,data.symbol,data.bid,data.last_bid_size,
- data.ask,data.last_ask_size)
-
- #Update bar using QuoteBarConsolidator's AggregateBar()
- self.aggregate_bar(self.working_bar, data)
-
-
- def scan(self, time):
- '''Scans this consolidator to see if it should emit a bar due yet'''
-
- if self.working_bar is None:
- return
-
- #If its our desired bar end time take the steps to
- if time.hour == self.close_time.hour and time.minute == self.close_time.minute:
-
- #Set end time
- self.working_bar.end_time = time
-
- #Emit event using QuoteBarConsolidator's OnDataConsolidated()
- self.on_data_consolidated(self.working_bar)
-
- #Reset the working bar to None
- self.working_bar = None
-
-class CustomQuoteBarConsolidator(PythonConsolidator):
- '''A custom quote bar consolidator that inherits from PythonConsolidator and implements
- the IDataConsolidator interface, it must implement all of IDataConsolidator. Reference
- PythonConsolidator.cs and DataConsolidatorPythonWrapper.PY for more information.
-
- This class shows how to implement a consolidator from scratch in Python, this gives us more
- freedom to determine the behavior of the consolidator but can't leverage any of the built in
- functions of an inherited class.
-
- For this example we implemented a Quotebar from scratch'''
-
- def __init__(self, period):
-
- #IDataConsolidator required vars for all consolidators
- self.consolidated = None #Most recently consolidated piece of data.
- self.working_data = None #Data being currently consolidated
- self.input_type = QuoteBar #The type consumed by this consolidator
- self.output_type = QuoteBar #The type produced by this consolidator
-
- #Consolidator Variables
- self.period = period
-
- def update(self, data):
- '''Updates this consolidator with the specified data'''
-
- #If we don't have bar yet, create one
- if self.working_data is None:
- self.working_data = QuoteBar(data.time,data.symbol,data.bid,data.last_bid_size,
- data.ask,data.last_ask_size,self.period)
-
- #Update bar using QuoteBar's update()
- self.working_data.update(data.value, data.bid.close, data.ask.close, 0,
- data.last_bid_size, data.last_ask_size)
-
- def scan(self, time):
- '''Scans this consolidator to see if it should emit a bar due to time passing'''
-
- if self.period is not None and self.working_data is not None:
- if time - self.working_data.time >= self.period:
-
- #Trigger the event handler with a copy of self and the data
- self.on_data_consolidated(self, self.working_data)
-
- #Set the most recent consolidated piece of data and then clear the working_data
- self.consolidated = self.working_data
- self.working_data = None
diff --git a/fincept-qt/scripts/strategies/CustomDataBenchmarkRegressionAlgorithm.py b/fincept-qt/scripts/strategies/CustomDataBenchmarkRegressionAlgorithm.py
deleted file mode 100644
index 903aeaaba..000000000
--- a/fincept-qt/scripts/strategies/CustomDataBenchmarkRegressionAlgorithm.py
+++ /dev/null
@@ -1,53 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-23C6E607
-# Category: Regression Test
-# Description: Regression algorithm to demonstrate the use of SetBenchmark() with custom data
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Regression algorithm to demonstrate the use of SetBenchmark() with custom data
-### </summary>
-class CustomDataBenchmarkRegressionAlgorithm(QCAlgorithm):
- def initialize(self):
- self.set_start_date(2017, 8, 18) # Set Start Date
- self.set_end_date(2017, 8, 21) # Set End Date
- self.set_cash(100000) # Set Strategy Cash
-
- self.add_equity("SPY", Resolution.HOUR)
- # Load benchmark data
- self.custom_symbol = self.add_data(ExampleCustomData, "ExampleCustomData", Resolution.HOUR).symbol
- self.set_benchmark(self.custom_symbol)
-
- def on_data(self, data):
- if not self.portfolio.invested:
- self.set_holdings("SPY", 1)
-
- def on_end_of_algorithm(self):
- security_benchmark = self.benchmark
- if security_benchmark.security.price == 0:
- raise Exception("Security benchmark price was not expected to be zero")
-
-class ExampleCustomData(PythonData):
-
- def get_source(self, config, date, is_live):
- source = "https://www.dl.dropboxusercontent.com/s/d83xvd7mm9fzpk0/path_to_my_csv_data.csv?dl=0"
- return SubscriptionDataSource(source, SubscriptionTransportMedium.REMOTE_FILE)
-
- def reader(self, config, line, date, is_live):
- data = line.split(',')
- obj_data = ExampleCustomData()
- obj_data.symbol = config.symbol
- obj_data.time = datetime.strptime(data[0], '%Y-%m-%d %H:%M:%S') + timedelta(hours=20)
- obj_data.value = float(data[4])
- obj_data["Open"] = float(data[1])
- obj_data["High"] = float(data[2])
- obj_data["Low"] = float(data[3])
- obj_data["Close"] = float(data[4])
- return obj_data
diff --git a/fincept-qt/scripts/strategies/CustomDataBitcoinAlgorithm.py b/fincept-qt/scripts/strategies/CustomDataBitcoinAlgorithm.py
deleted file mode 100644
index 86384b0f4..000000000
--- a/fincept-qt/scripts/strategies/CustomDataBitcoinAlgorithm.py
+++ /dev/null
@@ -1,54 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-0D7003A5
-# Category: Custom Data
-# Description: Dual-momentum strategy inspired by Bitcoin/crypto trading. Uses
-# EMA 12/26 crossover combined with volume confirmation. Buys on bullish
-# crossover with above-average volume, exits on bearish crossover.
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-class CustomDataBitcoinAlgorithm(QCAlgorithm):
- """EMA crossover with volume confirmation (inspired by crypto strategies)."""
-
- def initialize(self):
- self.set_start_date(2023, 1, 1)
- self.set_end_date(2024, 1, 1)
- self.set_cash(100000)
-
- self.symbol = "SPY"
- self.add_equity(self.symbol, Resolution.DAILY)
-
- self._fast_ema = self.ema(self.symbol, 12, Resolution.DAILY)
- self._slow_ema = self.ema(self.symbol, 26, Resolution.DAILY)
- self._vol_sma = self.sma(self.symbol, 20, Resolution.DAILY)
-
- self._prev_fast = 0
- self._prev_slow = 0
-
- def on_data(self, data):
- if not self._fast_ema.is_ready or not self._slow_ema.is_ready:
- return
- if self.symbol not in data:
- return
-
- fast = self._fast_ema.current.value
- slow = self._slow_ema.current.value
- price = data[self.symbol].close
-
- # Detect crossover
- bullish_cross = self._prev_fast <= self._prev_slow and fast > slow
- bearish_cross = self._prev_fast >= self._prev_slow and fast < slow
-
- self._prev_fast = fast
- self._prev_slow = slow
-
- if not self.portfolio.invested and bullish_cross:
- self.set_holdings(self.symbol, 1)
- elif self.portfolio.invested and bearish_cross:
- self.liquidate()
diff --git a/fincept-qt/scripts/strategies/CustomDataIconicTypesAddDataRegressionAlgorithm.py b/fincept-qt/scripts/strategies/CustomDataIconicTypesAddDataRegressionAlgorithm.py
deleted file mode 100644
index 2d17462e5..000000000
--- a/fincept-qt/scripts/strategies/CustomDataIconicTypesAddDataRegressionAlgorithm.py
+++ /dev/null
@@ -1,65 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-52D9893F
-# Category: Regression Test
-# Description: Regression algorithm checks that adding data via AddData works as expected
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-from QuantConnect.Data.Custom.IconicTypes import *
-
-### <summary>
-### Regression algorithm checks that adding data via AddData
-### works as expected
-### </summary>
-class CustomDataIconicTypesAddDataRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2013, 10, 7)
- self.set_end_date(2013, 10, 11)
- self.set_cash(100000)
-
- twx_equity = self.add_equity("TWX", Resolution.DAILY).symbol
- custom_twx_symbol = self.add_data(LinkedData, twx_equity, Resolution.DAILY).symbol
-
- self.googl_equity = self.add_equity("GOOGL", Resolution.DAILY).symbol
- custom_googl_symbol = self.add_data(LinkedData, "GOOGL", Resolution.DAILY).symbol
-
- unlinked_data_symbol = self.add_data(UnlinkedData, "GOOGL", Resolution.DAILY).symbol
- unlinked_data_symbol_underlying_equity = Symbol.create("MSFT", SecurityType.EQUITY, Market.USA)
- unlinked_data_symbol_underlying = self.add_data(UnlinkedData, unlinked_data_symbol_underlying_equity, Resolution.DAILY).symbol
-
- option_symbol = self.add_option("TWX", Resolution.MINUTE).symbol
- custom_option_symbol = self.add_data(LinkedData, option_symbol, Resolution.DAILY).symbol
-
- if custom_twx_symbol.underlying != twx_equity:
- raise Exception(f"Underlying symbol for {custom_twx_symbol} is not equal to TWX equity. Expected {twx_equity} got {custom_twx_symbol.underlying}")
- if custom_googl_symbol.underlying != self.googl_equity:
- raise Exception(f"Underlying symbol for {custom_googl_symbol} is not equal to GOOGL equity. Expected {self.googl_equity} got {custom_googl_symbol.underlying}")
- if unlinked_data_symbol.has_underlying:
- raise Exception(f"Unlinked data type (no underlying) has underlying when it shouldn't. Found {unlinked_data_symbol.underlying}")
- if not unlinked_data_symbol_underlying.has_underlying:
- raise Exception("Unlinked data type (with underlying) has no underlying Symbol even though we added with Symbol")
- if unlinked_data_symbol_underlying.underlying != unlinked_data_symbol_underlying_equity:
- raise Exception(f"Unlinked data type underlying does not equal equity Symbol added. Expected {unlinked_data_symbol_underlying_equity} got {unlinked_data_symbol_underlying.underlying}")
- if custom_option_symbol.underlying != option_symbol:
- raise Exception(f"Option symbol not equal to custom underlying symbol. Expected {option_symbol} got {custom_option_symbol.underlying}")
-
- try:
- custom_data_no_cache = self.add_data(LinkedData, "AAPL", Resolution.DAILY)
- raise Exception("AAPL was found in the SymbolCache, though it should be missing")
- except InvalidOperationException as e:
- return
-
- def on_data(self, data):
- '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
-
- Arguments:
- data: Slice object keyed by symbol containing the stock data
- '''
- if not self.portfolio.invested and len(self.transactions.get_open_orders()) == 0:
- self.set_holdings(self.googl_equity, 0.5)
diff --git a/fincept-qt/scripts/strategies/CustomDataIndicatorExtensionsAlgorithm.py b/fincept-qt/scripts/strategies/CustomDataIndicatorExtensionsAlgorithm.py
deleted file mode 100644
index f7aa6c5f4..000000000
--- a/fincept-qt/scripts/strategies/CustomDataIndicatorExtensionsAlgorithm.py
+++ /dev/null
@@ -1,50 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-0021591C
-# Category: Indicators
-# Description: Ratio-based pair trading using SMA indicator extensions. Buys IBM
-# when SPY/IBM price ratio > 1, liquidates when ratio < 1. Demonstrates
-# indicator comparison for relative-value strategies.
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-class CustomDataIndicatorExtensionsAlgorithm(QCAlgorithm):
- """Ratio-based pair trading: buys IBM when SPY/IBM ratio > 1, exits when < 1."""
-
- def initialize(self):
- self.set_start_date(2014, 1, 1)
- self.set_end_date(2018, 1, 1)
- self.set_cash(25000)
-
- self.ibm = 'IBM'
- self.spy = 'SPY'
-
- self.add_equity(self.ibm, Resolution.DAILY)
- self.add_equity(self.spy, Resolution.DAILY)
-
- # 1-period SMA = identity (tracks closing price)
- self.ibm_sma = self.sma(self.ibm, 1, Resolution.DAILY)
- self.spy_sma = self.sma(self.spy, 1, Resolution.DAILY)
-
- def on_data(self, data):
- # Wait for indicators to be ready
- if not (self.ibm_sma.is_ready and self.spy_sma.is_ready):
- return
-
- ibm_val = self.ibm_sma.current.value
- spy_val = self.spy_sma.current.value
-
- if ibm_val == 0:
- return
-
- ratio = spy_val / ibm_val
-
- if not self.portfolio.invested and ratio > 1:
- self.market_order(self.ibm, 100)
- elif self.portfolio.invested and ratio < 1:
- self.liquidate()
diff --git a/fincept-qt/scripts/strategies/CustomDataLinkedIconicTypeAddDataCoarseSelectionRegressionAlgorithm.py b/fincept-qt/scripts/strategies/CustomDataLinkedIconicTypeAddDataCoarseSelectionRegressionAlgorithm.py
deleted file mode 100644
index 7eb9b0d20..000000000
--- a/fincept-qt/scripts/strategies/CustomDataLinkedIconicTypeAddDataCoarseSelectionRegressionAlgorithm.py
+++ /dev/null
@@ -1,50 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-3EE829AC
-# Category: Regression Test
-# Description: Custom Data Linked Iconic Type Add Data Coarse Selection Regression Algorithm
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-from QuantConnect.Data.Custom.IconicTypes import *
-
-class CustomDataLinkedIconicTypeAddDataCoarseSelectionRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2014, 3, 24)
- self.set_end_date(2014, 4, 7)
- self.set_cash(100000)
-
- self.universe_settings.resolution = Resolution.DAILY
-
- self.add_universe_selection(CoarseFundamentalUniverseSelectionModel(self.coarse_selector))
-
- def coarse_selector(self, coarse):
- symbols = [
- Symbol.create("AAPL", SecurityType.EQUITY, Market.USA),
- Symbol.create("BAC", SecurityType.EQUITY, Market.USA),
- Symbol.create("FB", SecurityType.EQUITY, Market.USA),
- Symbol.create("GOOGL", SecurityType.EQUITY, Market.USA),
- Symbol.create("GOOG", SecurityType.EQUITY, Market.USA),
- Symbol.create("IBM", SecurityType.EQUITY, Market.USA),
- ]
-
- self.custom_symbols = []
-
- for symbol in symbols:
- self.custom_symbols.append(self.add_data(LinkedData, symbol, Resolution.DAILY).symbol)
-
- return symbols
-
- def on_data(self, data):
- if not self.portfolio.invested and len(self.transactions.get_open_orders()) == 0:
- aapl = Symbol.create("AAPL", SecurityType.EQUITY, Market.USA)
- self.set_holdings(aapl, 0.5)
-
- for custom_symbol in self.custom_symbols:
- if not self.active_securities.contains_key(custom_symbol.underlying):
- raise Exception(f"Custom data undelrying ({custom_symbol.underlying}) Symbol was not found in active securities")
diff --git a/fincept-qt/scripts/strategies/CustomDataLinkedIconicTypeAddDataOnSecuritiesChangedRegressionAlgorithm.py b/fincept-qt/scripts/strategies/CustomDataLinkedIconicTypeAddDataOnSecuritiesChangedRegressionAlgorithm.py
deleted file mode 100644
index ff31c1aef..000000000
--- a/fincept-qt/scripts/strategies/CustomDataLinkedIconicTypeAddDataOnSecuritiesChangedRegressionAlgorithm.py
+++ /dev/null
@@ -1,53 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-BAD0C3B3
-# Category: Regression Test
-# Description: Custom Data Linked Iconic Type Add Data On Securities Changed Regression Algorithm
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-from QuantConnect.Data.Custom.IconicTypes import *
-
-class CustomDataLinkedIconicTypeAddDataOnSecuritiesChangedRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2014, 3, 24)
- self.set_end_date(2014, 4, 7)
- self.set_cash(100000)
-
- self.universe_settings.resolution = Resolution.DAILY
-
- self.add_universe_selection(CoarseFundamentalUniverseSelectionModel(self.coarse_selector))
-
- def coarse_selector(self, coarse):
- return [
- Symbol.create("AAPL", SecurityType.EQUITY, Market.USA),
- Symbol.create("BAC", SecurityType.EQUITY, Market.USA),
- Symbol.create("FB", SecurityType.EQUITY, Market.USA),
- Symbol.create("GOOGL", SecurityType.EQUITY, Market.USA),
- Symbol.create("GOOG", SecurityType.EQUITY, Market.USA),
- Symbol.create("IBM", SecurityType.EQUITY, Market.USA),
- ]
-
- def on_data(self, data):
- if not self.portfolio.invested and len(self.transactions.get_open_orders()) == 0:
- aapl = Symbol.create("AAPL", SecurityType.EQUITY, Market.USA)
- self.set_holdings(aapl, 0.5)
-
- for custom_symbol in self.custom_symbols:
- if not self.active_securities.contains_key(custom_symbol.underlying):
- raise Exception(f"Custom data undelrying ({custom_symbol.underlying}) Symbol was not found in active securities")
-
- def on_securities_changed(self, changes):
- iterated = False
-
- for added in changes.added_securities:
- if not iterated:
- self.custom_symbols = []
- iterated = True
-
- self.custom_symbols.append(self.add_data(LinkedData, added.symbol, Resolution.DAILY).symbol)
diff --git a/fincept-qt/scripts/strategies/CustomDataMultiFileObjectStoreRegressionAlgorithm.py b/fincept-qt/scripts/strategies/CustomDataMultiFileObjectStoreRegressionAlgorithm.py
deleted file mode 100644
index f46523a43..000000000
--- a/fincept-qt/scripts/strategies/CustomDataMultiFileObjectStoreRegressionAlgorithm.py
+++ /dev/null
@@ -1,103 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-EA427FD2
-# Category: Regression Test
-# Description: Regression algorithm demonstrating the use of custom data sourced from multiple "files" in the object store
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-from datetime import datetime
-
-### <summary>
-### Regression algorithm demonstrating the use of custom data sourced from multiple "files" in the object store
-### </summary>
-class CustomDataMultiFileObjectStoreRegressionAlgorithm(QCAlgorithm):
- custom_data = "2017-08-18 01:00:00,5749.5,5852.95,5749.5,5842.2,214402430,8753.33\n2017-08-18 02:00:00,5834.1,5904.35,5822.2,5898.85,144794030,5405.72\n2017-08-18 03:00:00,5885.5,5898.8,5852.3,5857.55,145721790,5163.09\n2017-08-18 04:00:00,5811.95,5815,5760.4,5770.9,160523863,5219.24\n2017-08-18 05:00:00,5794.75,5848.2,5786.05,5836.95,151929179,5429.87\n2017-08-18 06:00:00,5889.95,5900.45,5858.45,5867.9,123586417,4303.93\n2017-08-18 07:00:00,5833.15,5833.85,5775.55,5811.55,127624733,4823.52\n2017-08-18 08:00:00,5834.6,5864.95,5834.6,5859,110427867,4661.55\n2017-08-18 09:00:00,5869.9,5879.35,5802.85,5816.7,117516350,4820.53\n2017-08-18 10:00:00,5894.5,5948.85,5887.95,5935.1,120195681,4882.29\n2017-08-18 11:00:00,6000.5,6019,5951.15,6009,127707078,6591.27\n2017-08-18 12:00:00,5991.2,6038.2,5980.95,6030.8,116275729,4641.97\n2017-08-18 13:00:00,5930.8,5966.05,5910.95,5955.25,151162819,5915.8\n2017-08-18 14:00:00,5972.25,5989.8,5926.75,5973.3,191516153,8349.59\n2017-08-18 15:00:00,5984.7,6051.1,5974.55,6038.05,171728134,7774.83\n2017-08-18 16:00:00,5894.5,5948.85,5887.95,5935.1,120195681,4882.29\n2017-08-18 17:00:00,6000.5,6019,5951.15,6009,127707078,6591.27\n2017-08-18 18:00:00,5991.2,6038.2,5980.95,6030.8,116275729,4641.97\n2017-08-18 19:00:00,5894.5,5948.85,5887.95,5935.1,120195681,4882.29\n2017-08-18 20:00:00,5895,5956.55,5869.5,5921.4,114174694,4961.54\n2017-08-18 21:00:00,5900.05,5972.7,5871.3,5881,118346364,4888.65\n2017-08-18 22:00:00,5907.9,5931.65,5857.4,5878,100130739,4304.75\n2017-08-18 23:00:00,5848.75,5868.05,5780.35,5788.8,180902123,6695.57\n2017-08-19 01:00:00,5771.75,5792.9,5738.6,5760.2,140394424,5894.04\n2017-08-19 02:00:00,5709.35,5729.85,5683.1,5699.1,142041404,5462.45\n2017-08-19 03:00:00,5748.95,5819.4,5739.4,5808.4,124410018,5121.33\n2017-08-19 04:00:00,5820.4,5854.9,5770.25,5850.05,107160887,4560.84\n2017-08-19 05:00:00,5841.9,5863.4,5804.3,5813.6,117541145,4591.91\n2017-08-19 06:00:00,5805.75,5828.4,5777.9,5822.25,115539008,4643.17\n2017-08-19 07:00:00,5754.15,5755,5645.65,5655.9,198400131,7148\n2017-08-19 08:00:00,5639.9,5686.15,5616.85,5667.65,182410583,6697.18\n2017-08-19 09:00:00,5638.05,5640,5566.25,5590.25,193488581,6308.88\n2017-08-19 10:00:00,5606.95,5666.25,5570.25,5609.1,196571543,6792.49\n2017-08-19 11:00:00,5627.95,5635.25,5579.35,5588.7,160095940,5939.3\n2017-08-19 12:00:00,5647.95,5699.35,5630.95,5682.35,239029425,9184.29\n2017-08-19 13:00:00,5749.5,5852.95,5749.5,5842.2,214402430,8753.33\n2017-08-19 14:00:00,5834.1,5904.35,5822.2,5898.85,144794030,5405.72\n2017-08-19 15:00:00,5885.5,5898.8,5852.3,5857.55,145721790,5163.09\n2017-08-19 16:00:00,5811.95,5815,5760.4,5770.9,160523863,5219.24\n2017-08-19 17:00:00,5794.75,5848.2,5786.05,5836.95,151929179,5429.87\n2017-08-19 18:00:00,5889.95,5900.45,5858.45,5867.9,123586417,4303.93\n2017-08-19 19:00:00,5833.15,5833.85,5775.55,5811.55,127624733,4823.52\n2017-08-19 20:00:00,5834.6,5864.95,5834.6,5859,110427867,4661.55\n2017-08-19 21:00:00,5869.9,5879.35,5802.85,5816.7,117516350,4820.53\n2017-08-19 22:00:00,5894.5,5948.85,5887.95,5935.1,120195681,4882.29\n2017-08-19 23:00:00,6000.5,6019,5951.15,6009,127707078,6591.27\n2017-08-21 01:00:00,5749.5,5852.95,5749.5,5842.2,214402430,8753.33\n2017-08-21 02:00:00,5834.1,5904.35,5822.2,5898.85,144794030,5405.72\n2017-08-21 03:00:00,5885.5,5898.8,5852.3,5857.55,145721790,5163.09\n2017-08-21 04:00:00,5811.95,5815,5760.4,5770.9,160523863,5219.24\n2017-08-21 05:00:00,5794.75,5848.2,5786.05,5836.95,151929179,5429.87\n2017-08-21 06:00:00,5889.95,5900.45,5858.45,5867.9,123586417,4303.93\n2017-08-21 07:00:00,5833.15,5833.85,5775.55,5811.55,127624733,4823.52\n2017-08-21 08:00:00,5834.6,5864.95,5834.6,5859,110427867,4661.55\n2017-08-21 09:00:00,5869.9,5879.35,5802.85,5816.7,117516350,4820.53\n2017-08-21 10:00:00,5894.5,5948.85,5887.95,5935.1,120195681,4882.29\n2017-08-21 11:00:00,6000.5,6019,5951.15,6009,127707078,6591.27\n2017-08-21 12:00:00,5991.2,6038.2,5980.95,6030.8,116275729,4641.97\n2017-08-21 13:00:00,5930.8,5966.05,5910.95,5955.25,151162819,5915.8\n2017-08-21 14:00:00,5972.25,5989.8,5926.75,5973.3,191516153,8349.59\n2017-08-21 15:00:00,5984.7,6051.1,5974.55,6038.05,171728134,7774.83\n2017-08-21 16:00:00,5894.5,5948.85,5887.95,5935.1,120195681,4882.29\n2017-08-21 17:00:00,6000.5,6019,5951.15,6009,127707078,6591.27\n2017-08-21 18:00:00,5991.2,6038.2,5980.95,6030.8,116275729,4641.97\n2017-08-21 19:00:00,5894.5,5948.85,5887.95,5935.1,120195681,4882.29\n2017-08-21 20:00:00,5895,5956.55,5869.5,5921.4,114174694,4961.54\n2017-08-21 21:00:00,5900.05,5972.7,5871.3,5881,118346364,4888.65\n2017-08-21 22:00:00,5907.9,5931.65,5857.4,5878,100130739,4304.75\n2017-08-21 23:00:00,5848.75,5868.05,5780.35,5788.8,180902123,6695.57"
-
- def initialize(self):
- self.set_start_date(2017, 8, 18)
- self.set_end_date(2017, 8, 21)
- self.set_cash(100000)
-
- self.set_benchmark(lambda x: 0)
-
- self.custom_symbol = self.add_data(ExampleCustomData, "ExampleCustomData", Resolution.HOUR).symbol
-
- # Saving data here for demonstration and regression testing purposes.
- # In real scenarios, data has to be saved to the object store before the algorithm starts.
- # Note: The data is stored in separate files for each date.
- data = {}
- for line in self.custom_data.split('\n'):
- csv = line.split(',')
- time = datetime.strptime(csv[0], '%Y-%m-%d %H:%M:%S').date()
- if time not in data:
- data[time] = line
- else:
- data[time] += '\n' + line
-
- for date, date_data in data.items():
- self.object_store.save(self.get_custom_data_key(date), date_data)
-
- self.received_data = []
-
- def on_data(self, slice: Slice):
- if slice.contains_key(self.custom_symbol):
- custom_data = slice.get(ExampleCustomData, self.custom_symbol)
- if custom_data.price == 0:
- raise Exception("Custom data price was not expected to be zero")
-
- self.received_data.append(custom_data)
-
- def on_end_of_algorithm(self):
- if not self.received_data:
- raise Exception("Custom data was not fetched")
-
- custom_security = self.securities[self.custom_symbol]
- if custom_security is None or custom_security.price == 0:
- Exception("Expected the custom security to be added to the algorithm securities and to have a price that is not zero")
-
- # Make sure history requests work as expected
- history = self.history(ExampleCustomData, self.custom_symbol, self.start_date, self.end_date, Resolution.HOUR)
-
- if history.shape[0] != len(self.received_data):
- raise Exception("History request returned more or less data than expected")
-
- for i in range(len(self.received_data)):
- received_data = self.received_data[i]
- if (history.index[i][0] != received_data.symbol or
- history.index[i][1] != received_data.time or
- history[["value"]].values[i][0] != received_data.value or
- history[["open"]].values[i][0] != received_data.open or
- history[["high"]].values[i][0] != received_data.high or
- history[["low"]].values[i][0] != received_data.low or
- history[["close"]].values[i][0] != received_data.close):
- raise Exception("History request returned different data than expected")
-
- @staticmethod
- def get_custom_data_key(date: datetime.date) -> str:
- return f"CustomData/ExampleCustomData{date.strftime('%Y%m%d')}"
-
-class ExampleCustomData(PythonData):
- CustomDataKey = ""
-
- def get_source(self, config, date, is_live):
- return SubscriptionDataSource(CustomDataMultiFileObjectStoreRegressionAlgorithm.get_custom_data_key(date.date()),
- SubscriptionTransportMedium.OBJECT_STORE,
- FileFormat.CSV)
-
- def reader(self, config, line, date, is_live):
- data = line.split(',')
- obj_data = ExampleCustomData()
- obj_data.symbol = config.symbol
- obj_data.time = datetime.strptime(data[0], '%Y-%m-%d %H:%M:%S')
- obj_data.value = float(data[4])
- obj_data["Open"] = float(data[1])
- obj_data["High"] = float(data[2])
- obj_data["Low"] = float(data[3])
- obj_data["Close"] = float(data[4])
- return obj_data
diff --git a/fincept-qt/scripts/strategies/CustomDataNIFTYAlgorithm.py b/fincept-qt/scripts/strategies/CustomDataNIFTYAlgorithm.py
deleted file mode 100644
index 5d57dd2ee..000000000
--- a/fincept-qt/scripts/strategies/CustomDataNIFTYAlgorithm.py
+++ /dev/null
@@ -1,141 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-8C140F85
-# Category: Custom Data
-# Description: This demonstration imports indian NSE index "NIFTY" as a tradable security in addition to the USDINR currency pair. W...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### This demonstration imports indian NSE index "NIFTY" as a tradable security in addition to the USDINR currency pair. We move into the
-### NSE market when the economy is performing well.
-### </summary>
-### <meta name="tag" content="strategy example" />
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="custom data" />
-class CustomDataNIFTYAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2008, 1, 8)
- self.set_end_date(2014, 7, 25)
- self.set_cash(100000)
-
- # Define the symbol and "type" of our generic data:
- rupee = self.add_data(DollarRupee, "USDINR", Resolution.DAILY).symbol
- nifty = self.add_data(Nifty, "NIFTY", Resolution.DAILY).symbol
-
- self.settings.automatic_indicator_warm_up = True
- rupee_sma = self.sma(rupee, 20)
- nifty_sma = self.sma(rupee, 20)
- self.log(f"SMA - Is ready? USDINR: {rupee_sma.is_ready} NIFTY: {nifty_sma.is_ready}")
-
- self.minimum_correlation_history = 50
- self.today = CorrelationPair()
- self.prices = []
-
-
- def on_data(self, data):
- if data.contains_key("USDINR"):
- self.today = CorrelationPair(self.time)
- self.today.currency_price = data["USDINR"].close
-
- if not data.contains_key("NIFTY"): return
-
- self.today.nifty_price = data["NIFTY"].close
-
- if self.today.date() == data["NIFTY"].time.date():
- self.prices.append(self.today)
- if len(self.prices) > self.minimum_correlation_history:
- self.prices.pop(0)
-
- # Strategy
- if self.time.weekday() != 2: return
-
- cur_qnty = self.portfolio["NIFTY"].quantity
- quantity = int(self.portfolio.margin_remaining * 0.9 / data["NIFTY"].close)
- hi_nifty = max(price.nifty_price for price in self.prices)
- lo_nifty = min(price.nifty_price for price in self.prices)
-
- if data["NIFTY"].open >= hi_nifty:
- code = self.order("NIFTY", quantity - cur_qnty)
- self.debug("LONG {0} Time: {1} Quantity: {2} Portfolio: {3} Nifty: {4} Buying Power: {5}".format(code, self.time, quantity, self.portfolio["NIFTY"].quantity, data["NIFTY"].close, self.portfolio.total_portfolio_value))
- elif data["NIFTY"].open <= lo_nifty:
- code = self.order("NIFTY", -quantity - cur_qnty)
- self.debug("SHORT {0} Time: {1} Quantity: {2} Portfolio: {3} Nifty: {4} Buying Power: {5}".format(code, self.time, quantity, self.portfolio["NIFTY"].quantity, data["NIFTY"].close, self.portfolio.total_portfolio_value))
-
-
-class Nifty(PythonData):
- '''NIFTY Custom Data Class'''
- def get_source(self, config, date, is_live_mode):
- return SubscriptionDataSource("https://www.dropbox.com/s/rsmg44jr6wexn2h/CNXNIFTY.csv?dl=1", SubscriptionTransportMedium.REMOTE_FILE)
-
-
- def reader(self, config, line, date, is_live_mode):
- if not (line.strip() and line[0].isdigit()): return None
-
- # New Nifty object
- index = Nifty()
- index.symbol = config.symbol
-
- try:
- # Example File Format:
- # Date, Open High Low Close Volume Turnover
- # 2011-09-13 7792.9 7799.9 7722.65 7748.7 116534670 6107.78
- data = line.split(',')
- index.time = datetime.strptime(data[0], "%Y-%m-%d")
- index.end_time = index.time + timedelta(days=1)
- index.value = data[4]
- index["Open"] = float(data[1])
- index["High"] = float(data[2])
- index["Low"] = float(data[3])
- index["Close"] = float(data[4])
-
-
- except ValueError:
- # Do nothing
- return None
-
- return index
-
-
-class DollarRupee(PythonData):
- '''Dollar Rupe is a custom data type we create for this algorithm'''
- def get_source(self, config, date, is_live_mode):
- return SubscriptionDataSource("https://www.dropbox.com/s/m6ecmkg9aijwzy2/USDINR.csv?dl=1", SubscriptionTransportMedium.REMOTE_FILE)
-
- def reader(self, config, line, date, is_live_mode):
- if not (line.strip() and line[0].isdigit()): return None
-
- # New USDINR object
- currency = DollarRupee()
- currency.symbol = config.symbol
-
- try:
- data = line.split(',')
- currency.time = datetime.strptime(data[0], "%Y-%m-%d")
- currency.end_time = currency.time + timedelta(days=1)
- currency.value = data[1]
- currency["Close"] = float(data[1])
-
- except ValueError:
- # Do nothing
- return None
-
- return currency
-
-
-class CorrelationPair:
- '''Correlation Pair is a helper class to combine two data points which we'll use to perform the correlation.'''
- def __init__(self, *args):
- self.nifty_price = 0 # Nifty price for this correlation pair
- self.currency_price = 0 # Currency price for this correlation pair
- self._date = datetime.min # Date of the correlation pair
- if len(args) > 0: self._date = args[0]
-
- def date(self):
- return self._date.date()
diff --git a/fincept-qt/scripts/strategies/CustomDataObjectStoreRegressionAlgorithm.py b/fincept-qt/scripts/strategies/CustomDataObjectStoreRegressionAlgorithm.py
deleted file mode 100644
index b01e0f68f..000000000
--- a/fincept-qt/scripts/strategies/CustomDataObjectStoreRegressionAlgorithm.py
+++ /dev/null
@@ -1,92 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-675A0EC6
-# Category: Regression Test
-# Description: Regression algorithm demonstrating the use of custom data sourced from the object store
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Regression algorithm demonstrating the use of custom data sourced from the object store
-### </summary>
-class CustomDataObjectStoreRegressionAlgorithm(QCAlgorithm):
- custom_data = "2017-08-18 01:00:00,5749.5,5852.95,5749.5,5842.2,214402430,8753.33\n2017-08-18 02:00:00,5834.1,5904.35,5822.2,5898.85,144794030,5405.72\n2017-08-18 03:00:00,5885.5,5898.8,5852.3,5857.55,145721790,5163.09\n2017-08-18 04:00:00,5811.95,5815,5760.4,5770.9,160523863,5219.24\n2017-08-18 05:00:00,5794.75,5848.2,5786.05,5836.95,151929179,5429.87\n2017-08-18 06:00:00,5889.95,5900.45,5858.45,5867.9,123586417,4303.93\n2017-08-18 07:00:00,5833.15,5833.85,5775.55,5811.55,127624733,4823.52\n2017-08-18 08:00:00,5834.6,5864.95,5834.6,5859,110427867,4661.55\n2017-08-18 09:00:00,5869.9,5879.35,5802.85,5816.7,117516350,4820.53\n2017-08-18 10:00:00,5894.5,5948.85,5887.95,5935.1,120195681,4882.29\n2017-08-18 11:00:00,6000.5,6019,5951.15,6009,127707078,6591.27\n2017-08-18 12:00:00,5991.2,6038.2,5980.95,6030.8,116275729,4641.97\n2017-08-18 13:00:00,5930.8,5966.05,5910.95,5955.25,151162819,5915.8\n2017-08-18 14:00:00,5972.25,5989.8,5926.75,5973.3,191516153,8349.59\n2017-08-18 15:00:00,5984.7,6051.1,5974.55,6038.05,171728134,7774.83\n2017-08-18 16:00:00,5894.5,5948.85,5887.95,5935.1,120195681,4882.29\n2017-08-18 17:00:00,6000.5,6019,5951.15,6009,127707078,6591.27\n2017-08-18 18:00:00,5991.2,6038.2,5980.95,6030.8,116275729,4641.97\n2017-08-18 19:00:00,5894.5,5948.85,5887.95,5935.1,120195681,4882.29\n2017-08-18 20:00:00,5895,5956.55,5869.5,5921.4,114174694,4961.54\n2017-08-18 21:00:00,5900.05,5972.7,5871.3,5881,118346364,4888.65\n2017-08-18 22:00:00,5907.9,5931.65,5857.4,5878,100130739,4304.75\n2017-08-18 23:00:00,5848.75,5868.05,5780.35,5788.8,180902123,6695.57\n2017-08-19 01:00:00,5771.75,5792.9,5738.6,5760.2,140394424,5894.04\n2017-08-19 02:00:00,5709.35,5729.85,5683.1,5699.1,142041404,5462.45\n2017-08-19 03:00:00,5748.95,5819.4,5739.4,5808.4,124410018,5121.33\n2017-08-19 04:00:00,5820.4,5854.9,5770.25,5850.05,107160887,4560.84\n2017-08-19 05:00:00,5841.9,5863.4,5804.3,5813.6,117541145,4591.91\n2017-08-19 06:00:00,5805.75,5828.4,5777.9,5822.25,115539008,4643.17\n2017-08-19 07:00:00,5754.15,5755,5645.65,5655.9,198400131,7148\n2017-08-19 08:00:00,5639.9,5686.15,5616.85,5667.65,182410583,6697.18\n2017-08-19 09:00:00,5638.05,5640,5566.25,5590.25,193488581,6308.88\n2017-08-19 10:00:00,5606.95,5666.25,5570.25,5609.1,196571543,6792.49\n2017-08-19 11:00:00,5627.95,5635.25,5579.35,5588.7,160095940,5939.3\n2017-08-19 12:00:00,5647.95,5699.35,5630.95,5682.35,239029425,9184.29\n2017-08-19 13:00:00,5749.5,5852.95,5749.5,5842.2,214402430,8753.33\n2017-08-19 14:00:00,5834.1,5904.35,5822.2,5898.85,144794030,5405.72\n2017-08-19 15:00:00,5885.5,5898.8,5852.3,5857.55,145721790,5163.09\n2017-08-19 16:00:00,5811.95,5815,5760.4,5770.9,160523863,5219.24\n2017-08-19 17:00:00,5794.75,5848.2,5786.05,5836.95,151929179,5429.87\n2017-08-19 18:00:00,5889.95,5900.45,5858.45,5867.9,123586417,4303.93\n2017-08-19 19:00:00,5833.15,5833.85,5775.55,5811.55,127624733,4823.52\n2017-08-19 20:00:00,5834.6,5864.95,5834.6,5859,110427867,4661.55\n2017-08-19 21:00:00,5869.9,5879.35,5802.85,5816.7,117516350,4820.53\n2017-08-19 22:00:00,5894.5,5948.85,5887.95,5935.1,120195681,4882.29\n2017-08-19 23:00:00,6000.5,6019,5951.15,6009,127707078,6591.27\n2017-08-21 01:00:00,5749.5,5852.95,5749.5,5842.2,214402430,8753.33\n2017-08-21 02:00:00,5834.1,5904.35,5822.2,5898.85,144794030,5405.72\n2017-08-21 03:00:00,5885.5,5898.8,5852.3,5857.55,145721790,5163.09\n2017-08-21 04:00:00,5811.95,5815,5760.4,5770.9,160523863,5219.24\n2017-08-21 05:00:00,5794.75,5848.2,5786.05,5836.95,151929179,5429.87\n2017-08-21 06:00:00,5889.95,5900.45,5858.45,5867.9,123586417,4303.93\n2017-08-21 07:00:00,5833.15,5833.85,5775.55,5811.55,127624733,4823.52\n2017-08-21 08:00:00,5834.6,5864.95,5834.6,5859,110427867,4661.55\n2017-08-21 09:00:00,5869.9,5879.35,5802.85,5816.7,117516350,4820.53\n2017-08-21 10:00:00,5894.5,5948.85,5887.95,5935.1,120195681,4882.29\n2017-08-21 11:00:00,6000.5,6019,5951.15,6009,127707078,6591.27\n2017-08-21 12:00:00,5991.2,6038.2,5980.95,6030.8,116275729,4641.97\n2017-08-21 13:00:00,5930.8,5966.05,5910.95,5955.25,151162819,5915.8\n2017-08-21 14:00:00,5972.25,5989.8,5926.75,5973.3,191516153,8349.59\n2017-08-21 15:00:00,5984.7,6051.1,5974.55,6038.05,171728134,7774.83\n2017-08-21 16:00:00,5894.5,5948.85,5887.95,5935.1,120195681,4882.29\n2017-08-21 17:00:00,6000.5,6019,5951.15,6009,127707078,6591.27\n2017-08-21 18:00:00,5991.2,6038.2,5980.95,6030.8,116275729,4641.97\n2017-08-21 19:00:00,5894.5,5948.85,5887.95,5935.1,120195681,4882.29\n2017-08-21 20:00:00,5895,5956.55,5869.5,5921.4,114174694,4961.54\n2017-08-21 21:00:00,5900.05,5972.7,5871.3,5881,118346364,4888.65\n2017-08-21 22:00:00,5907.9,5931.65,5857.4,5878,100130739,4304.75\n2017-08-21 23:00:00,5848.75,5868.05,5780.35,5788.8,180902123,6695.57"
-
- def initialize(self):
- self.set_start_date(2017, 8, 18)
- self.set_end_date(2017, 8, 21)
- self.set_cash(100000)
-
- self.set_benchmark(lambda x: 0)
-
- ExampleCustomData.custom_data_key = self.get_custom_data_key()
-
- self.custom_symbol = self.add_data(ExampleCustomData, "ExampleCustomData", Resolution.HOUR).symbol
-
- # Saving data here for demonstration and regression testing purposes.
- # In real scenarios, data has to be saved to the object store before the algorithm starts.
- self.save_data_to_object_store()
-
- self.received_data = []
-
- def on_data(self, slice: Slice):
- if slice.contains_key(self.custom_symbol):
- custom_data = slice.get(ExampleCustomData, self.custom_symbol)
- if custom_data.price == 0:
- raise Exception("Custom data price was not expected to be zero")
-
- self.received_data.append(custom_data)
-
- def on_end_of_algorithm(self):
- if not self.received_data:
- raise Exception("Custom data was not fetched")
-
- custom_security = self.securities[self.custom_symbol]
- if custom_security is None or custom_security.price == 0:
- Exception("Expected the custom security to be added to the algorithm securities and to have a price that is not zero")
-
- # Make sure history requests work as expected
- history = self.history(ExampleCustomData, self.custom_symbol, self.start_date, self.end_date, Resolution.HOUR)
-
- if history.shape[0] != len(self.received_data):
- raise Exception("History request returned more or less data than expected")
-
- for i in range(len(self.received_data)):
- received_data = self.received_data[i]
- if (history.index[i][0] != received_data.symbol or
- history.index[i][1] != received_data.time or
- history[["value"]].values[i][0] != received_data.value or
- history[["open"]].values[i][0] != received_data.open or
- history[["high"]].values[i][0] != received_data.high or
- history[["low"]].values[i][0] != received_data.low or
- history[["close"]].values[i][0] != received_data.close):
- raise Exception("History request returned different data than expected")
-
- def get_custom_data_key(self):
- return "CustomData/ExampleCustomData"
-
- def save_data_to_object_store(self):
- self.object_store.save(self.get_custom_data_key(), self.custom_data)
-
-class ExampleCustomData(PythonData):
- custom_data_key = ""
-
- def get_source(self, config, date, is_live):
- return SubscriptionDataSource(self.custom_data_key, SubscriptionTransportMedium.OBJECT_STORE, FileFormat.CSV)
-
- def reader(self, config, line, date, is_live):
- data = line.split(',')
- obj_data = ExampleCustomData()
- obj_data.symbol = config.symbol
- obj_data.time = datetime.strptime(data[0], '%Y-%m-%d %H:%M:%S')
- obj_data.value = float(data[4])
- obj_data["Open"] = float(data[1])
- obj_data["High"] = float(data[2])
- obj_data["Low"] = float(data[3])
- obj_data["Close"] = float(data[4])
- return obj_data
diff --git a/fincept-qt/scripts/strategies/CustomDataPropertiesRegressionAlgorithm.py b/fincept-qt/scripts/strategies/CustomDataPropertiesRegressionAlgorithm.py
deleted file mode 100644
index fe19c77d6..000000000
--- a/fincept-qt/scripts/strategies/CustomDataPropertiesRegressionAlgorithm.py
+++ /dev/null
@@ -1,126 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-9147ECE5
-# Category: Regression Test
-# Description: Regression test to demonstrate setting custom Symbol Properties and Market Hours for a custom data import
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Regression test to demonstrate setting custom Symbol Properties and Market Hours for a custom data import
-### </summary>
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="importing data" />
-### <meta name="tag" content="custom data" />
-### <meta name="tag" content="crypto" />
-### <meta name="tag" content="regression test" />
-class CustomDataPropertiesRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2020, 1, 5) # Set Start Date
- self.set_end_date(2020, 1, 10) # Set End Date
- self.set_cash(100000) # Set Strategy Cash
-
- # Define our custom data properties and exchange hours
- self.ticker = 'BTC'
- properties = SymbolProperties("Bitcoin", "USD", 1, 0.01, 0.01, self.ticker)
- exchange_hours = SecurityExchangeHours.always_open(TimeZones.NEW_YORK)
-
- # Add the custom data to our algorithm with our custom properties and exchange hours
- self.bitcoin = self.add_data(Bitcoin, self.ticker, properties, exchange_hours, leverage=1, fill_forward=False)
-
- # Verify our symbol properties were changed and loaded into this security
- if self.bitcoin.symbol_properties != properties :
- raise Exception("Failed to set and retrieve custom SymbolProperties for BTC")
-
- # Verify our exchange hours were changed and loaded into this security
- if self.bitcoin.exchange.hours != exchange_hours :
- raise Exception("Failed to set and retrieve custom ExchangeHours for BTC")
-
- # For regression purposes on AddData overloads, this call is simply to ensure Lean can accept this
- # with default params and is not routed to a breaking function.
- self.add_data(Bitcoin, "BTCUSD")
-
-
- def on_data(self, data):
- if not self.portfolio.invested:
- if data['BTC'].close != 0 :
- self.order('BTC', self.portfolio.margin_remaining/abs(data['BTC'].close + 1))
-
- def on_end_of_algorithm(self):
- #Reset our Symbol property value, for testing purposes.
- self.symbol_properties_database.set_entry(Market.USA, self.market_hours_database.get_database_symbol_key(self.bitcoin.symbol), SecurityType.BASE,
- SymbolProperties.get_default("USD"))
-
-
-
-class Bitcoin(PythonData):
- '''Custom Data Type: Bitcoin data from Quandl - http://www.quandl.com/help/api-for-bitcoin-data'''
-
- def get_source(self, config, date, is_live_mode):
- if is_live_mode:
- return SubscriptionDataSource("https://www.bitstamp.net/api/ticker/", SubscriptionTransportMedium.REST)
-
- #return "http://my-ftp-server.com/futures-data-" + date.to_string("Ymd") + ".zip"
- # OR simply return a fixed small data file. Large files will slow down your backtest
- subscription = SubscriptionDataSource("https://www.quantconnect.com/api/v2/proxy/nasdaq/api/v3/datatables/QDL/BITFINEX.csv?code=BTCUSD&api_key=WyAazVXnq7ATy_fefTqm")
- subscription.Sort = True
- return subscription
-
-
- def reader(self, config, line, date, is_live_mode):
- coin = Bitcoin()
- coin.symbol = config.symbol
-
- if is_live_mode:
- # Example Line Format:
- # {"high": "441.00", "last": "421.86", "timestamp": "1411606877", "bid": "421.96", "vwap": "428.58", "volume": "14120.40683975", "low": "418.83", "ask": "421.99"}
- try:
- live_btc = json.loads(line)
-
- # If value is zero, return None
- value = live_btc["last"]
- if value == 0: return None
-
- coin.time = datetime.now()
- coin.value = value
- coin["Open"] = float(live_btc["open"])
- coin["High"] = float(live_btc["high"])
- coin["Low"] = float(live_btc["low"])
- coin["Close"] = float(live_btc["last"])
- coin["Ask"] = float(live_btc["ask"])
- coin["Bid"] = float(live_btc["bid"])
- coin["VolumeBTC"] = float(live_btc["volume"])
- coin["WeightedPrice"] = float(live_btc["vwap"])
- return coin
- except ValueError:
- # Do nothing, possible error in json decoding
- return None
-
- # Example Line Format:
- #code date high low mid last bid ask volume
- #BTCUSD 2024-10-08 63248.0 61940.0 62246.5 62245.0 62246.0 62247.0 5.929230648356
- if not (line.strip() and line[7].isdigit()): return None
-
- try:
- data = line.split(',')
- coin.time = datetime.strptime(data[1], "%Y-%m-%d")
- coin.end_time = coin.time + timedelta(days=1)
- coin.value = float(data[5])
- coin["High"] = float(data[2])
- coin["Low"] = float(data[3])
- coin["Mid"] = float(data[4])
- coin["Close"] = float(data[5])
- coin["Bid"] = float(data[6])
- coin["Ask"] = float(data[7])
- coin["VolumeBTC"] = float(data[8])
- return coin
-
- except ValueError:
- # Do nothing, possible error in json decoding
- return None
diff --git a/fincept-qt/scripts/strategies/CustomDataRegressionAlgorithm.py b/fincept-qt/scripts/strategies/CustomDataRegressionAlgorithm.py
deleted file mode 100644
index 374430a9f..000000000
--- a/fincept-qt/scripts/strategies/CustomDataRegressionAlgorithm.py
+++ /dev/null
@@ -1,118 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-67CFD0CD
-# Category: Regression Test
-# Description: Regression test to demonstrate importing and trading on custom data
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Regression test to demonstrate importing and trading on custom data.
-### </summary>
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="importing data" />
-### <meta name="tag" content="custom data" />
-### <meta name="tag" content="crypto" />
-### <meta name="tag" content="regression test" />
-class CustomDataRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self):
-
- self.set_start_date(2020,1,5) # Set Start Date
- self.set_end_date(2020,1,10) # Set End Date
- self.set_cash(100000) # Set Strategy Cash
-
- resolution = Resolution.SECOND if self.live_mode else Resolution.DAILY
- self.add_data(Bitcoin, "BTC", resolution)
-
- seeder = FuncSecuritySeeder(self.get_last_known_prices)
- self.set_security_initializer(lambda x: seeder.seed_security(x))
- self._warmed_up_checked = False
-
- def on_data(self, data):
- if not self.portfolio.invested:
- if data['BTC'].close != 0 :
- self.order('BTC', self.portfolio.margin_remaining/abs(data['BTC'].close + 1))
-
- def on_securities_changed(self, changes):
- changes.filter_custom_securities = False
- for added_security in changes.added_securities:
- if added_security.symbol.value == "BTC":
- self._warmed_up_checked = True
- if not added_security.has_data:
- raise ValueError(f"Security {added_security.symbol} was not warmed up!")
-
- def on_end_of_algorithm(self):
- if not self._warmed_up_checked:
- raise ValueError("Security was not warmed up!")
-
-class Bitcoin(PythonData):
- '''Custom Data Type: Bitcoin data from Quandl - https://data.nasdaq.com/databases/BCHAIN'''
-
- def get_source(self, config, date, is_live_mode):
- if is_live_mode:
- return SubscriptionDataSource("https://www.bitstamp.net/api/ticker/", SubscriptionTransportMedium.REST)
-
- #return "http://my-ftp-server.com/futures-data-" + date.to_string("Ymd") + ".zip"
- # OR simply return a fixed small data file. Large files will slow down your backtest
- subscription = SubscriptionDataSource("https://www.quantconnect.com/api/v2/proxy/nasdaq/api/v3/datatables/QDL/BITFINEX.csv?code=BTCUSD&api_key=WyAazVXnq7ATy_fefTqm")
- subscription.Sort = True
- return subscription
-
-
- def reader(self, config, line, date, is_live_mode):
- coin = Bitcoin()
- coin.symbol = config.symbol
-
- if is_live_mode:
- # Example Line Format:
- # {"high": "441.00", "last": "421.86", "timestamp": "1411606877", "bid": "421.96", "vwap": "428.58", "volume": "14120.40683975", "low": "418.83", "ask": "421.99"}
- try:
- live_btc = json.loads(line)
-
- # If value is zero, return None
- value = live_btc["last"]
- if value == 0: return None
-
- coin.time = datetime.now()
- coin.value = value
- coin["Open"] = float(live_btc["open"])
- coin["High"] = float(live_btc["high"])
- coin["Low"] = float(live_btc["low"])
- coin["Close"] = float(live_btc["last"])
- coin["Ask"] = float(live_btc["ask"])
- coin["Bid"] = float(live_btc["bid"])
- coin["VolumeBTC"] = float(live_btc["volume"])
- coin["WeightedPrice"] = float(live_btc["vwap"])
- return coin
- except ValueError:
- # Do nothing, possible error in json decoding
- return None
-
- # Example Line Format:
- # code date high low mid last bid ask volume
- # BTCUSD 2024-10-08 63248.0 61940.0 62246.5 62245.0 62246.0 62247.0 477.91102114
- if not (line.strip() and line[7].isdigit()): return None
-
- try:
- data = line.split(',')
- coin.time = datetime.strptime(data[1], "%Y-%m-%d")
- coin.end_time = coin.time + timedelta(days=1)
- coin.value = float(data[5])
- coin["High"] = float(data[2])
- coin["Low"] = float(data[3])
- coin["Mid"] = float(data[4])
- coin["Close"] = float(data[5])
- coin["Bid"] = float(data[6])
- coin["Ask"] = float(data[7])
- coin["VolumeBTC"] = float(data[8])
- return coin
-
- except ValueError:
- # Do nothing, possible error in json decoding
- return None
diff --git a/fincept-qt/scripts/strategies/CustomDataTypeHistoryAlgorithm.py b/fincept-qt/scripts/strategies/CustomDataTypeHistoryAlgorithm.py
deleted file mode 100644
index a8d3e3055..000000000
--- a/fincept-qt/scripts/strategies/CustomDataTypeHistoryAlgorithm.py
+++ /dev/null
@@ -1,51 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-1A4DBA47
-# Category: Custom Data
-# Description: Gap and momentum strategy inspired by custom data patterns.
-# Buys when today's open is above yesterday's close (gap up) with positive
-# 10-day momentum. Sells when gap down occurs or momentum turns negative.
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-class CustomDataTypeHistoryAlgorithm(QCAlgorithm):
- """Gap-up momentum strategy."""
-
- def initialize(self):
- self.set_start_date(2023, 1, 1)
- self.set_end_date(2024, 1, 1)
- self.set_cash(100000)
-
- self.symbol = "SPY"
- self.add_equity(self.symbol, Resolution.DAILY)
-
- self._momp = self.momp(self.symbol, 10, Resolution.DAILY)
- self._prev_close = 0
-
- def on_data(self, data):
- if not self._momp.is_ready:
- return
- if self.symbol not in data:
- return
-
- bar = data[self.symbol]
- mom_val = self._momp.current.value
-
- if self._prev_close > 0:
- gap_pct = (bar.open - self._prev_close) / self._prev_close * 100
-
- if not self.portfolio.invested:
- # Gap up + positive momentum
- if gap_pct > 0.1 and mom_val > 0:
- self.set_holdings(self.symbol, 1)
- else:
- # Gap down or negative momentum
- if gap_pct < -0.3 or mom_val < -1:
- self.liquidate()
-
- self._prev_close = bar.close
diff --git a/fincept-qt/scripts/strategies/CustomDataUniverseAlgorithm.py b/fincept-qt/scripts/strategies/CustomDataUniverseAlgorithm.py
deleted file mode 100644
index 42f8bc36b..000000000
--- a/fincept-qt/scripts/strategies/CustomDataUniverseAlgorithm.py
+++ /dev/null
@@ -1,110 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-A032E1EE
-# Category: Universe Selection
-# Description: This algorithm shows how to grab symbols from an external api each day and load data using the universe selection fea...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### This algorithm shows how to grab symbols from an external api each day
-### and load data using the universe selection feature. In this example we
-### define a custom data type for the NYSE top gainers and then short the
-### top 2 gainers each day
-### </summary>
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="universes" />
-### <meta name="tag" content="custom universes" />
-class CustomDataUniverseAlgorithm(QCAlgorithm):
-
- def initialize(self):
-
- # Data ADDED via universe selection is added with Daily resolution.
- self.universe_settings.resolution = Resolution.DAILY
-
- self.set_start_date(2015,1,5)
- self.set_end_date(2015,7,1)
- self.set_cash(100000)
-
- self.add_equity("SPY", Resolution.DAILY)
- self.set_benchmark("SPY")
-
- # add a custom universe data source (defaults to usa-equity)
- self.add_universe(NyseTopGainers, "universe-nyse-top-gainers", Resolution.DAILY, self.nyse_top_gainers)
-
- def nyse_top_gainers(self, data):
- return [ x.symbol for x in data if x["TopGainersRank"] <= 2 ]
-
-
- def on_data(self, slice):
- pass
-
- def on_securities_changed(self, changes):
- self._changes = changes
-
- for security in changes.removed_securities:
- # liquidate securities that have been removed
- if security.invested:
- self.liquidate(security.symbol)
- self.log("Exit {0} at {1}".format(security.symbol, security.close))
-
- for security in changes.added_securities:
- # enter short positions on new securities
- if not security.invested and security.close != 0:
- qty = self.calculate_order_quantity(security.symbol, -0.25)
- self.market_on_open_order(security.symbol, qty)
- self.log("Enter {0} at {1}".format(security.symbol, security.close))
-
-
-class NyseTopGainers(PythonData):
- def __init__(self):
- self.count = 0
- self.last_date = datetime.min
-
- def get_source(self, config, date, is_live_mode):
- url = "http://www.wsj.com/mdc/public/page/2_3021-gainnyse-gainer.html" if is_live_mode else \
- "https://www.dropbox.com/s/vrn3p38qberw3df/nyse-gainers.csv?dl=1"
-
- return SubscriptionDataSource(url, SubscriptionTransportMedium.REMOTE_FILE)
-
- def reader(self, config, line, date, is_live_mode):
-
- if not is_live_mode:
- # backtest gets data from csv file in dropbox
- if not (line.strip() and line[0].isdigit()): return None
- csv = line.split(',')
- nyse = NyseTopGainers()
- nyse.time = datetime.strptime(csv[0], "%Y%m%d")
- nyse.end_time = nyse.time + timedelta(1)
- nyse.symbol = Symbol.create(csv[1], SecurityType.EQUITY, Market.USA)
- nyse["TopGainersRank"] = int(csv[2])
- return nyse
-
- if self.last_date != date:
- # reset our counter for the new day
- self.last_date = date
- self.count = 0
-
- # parse the html into a symbol
- if not line.startswith('<a href=\"/public/quotes/main.html?symbol='):
- # we're only looking for lines that contain the symbols
- return None
-
- last_close_paren = line.rfind(')')
- last_open_paren = line.rfind('(')
- if last_open_paren == -1 or last_close_paren == -1:
- return None
-
- symbol_string = line[last_open_paren + 1:last_close_paren]
- nyse = NyseTopGainers()
- nyse.time = date
- nyse.end_time = nyse.time + timedelta(1)
- nyse.symbol = Symbol.create(symbol_string, SecurityType.EQUITY, Market.USA)
- nyse["TopGainersRank"] = self.count
- self.count = self.count + 1
- return nyse
diff --git a/fincept-qt/scripts/strategies/CustomDataUniverseRegressionAlgorithm.py b/fincept-qt/scripts/strategies/CustomDataUniverseRegressionAlgorithm.py
deleted file mode 100644
index 075475bdf..000000000
--- a/fincept-qt/scripts/strategies/CustomDataUniverseRegressionAlgorithm.py
+++ /dev/null
@@ -1,100 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-FC1DA597
-# Category: Universe Selection
-# Description: Custom data universe selection regression algorithm asserting it's behavior. See GH issue #6396
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Custom data universe selection regression algorithm asserting it's behavior. See GH issue #6396
-### </summary>
-class CustomDataUniverseRegressionAlgorithm(QCAlgorithm):
- def initialize(self):
- '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
- self.set_start_date(2014, 3, 24)
- self.set_end_date(2014, 3, 31)
-
- self.current_underlying_symbols = set()
- self.universe_settings.resolution = Resolution.DAILY;
- self.add_universe(CoarseFundamental, "custom-data-universe", self.selection)
-
- self._selection_time = [datetime(2014, 3, 24), datetime(2014, 3, 25), datetime(2014, 3, 26),
- datetime(2014, 3, 27), datetime(2014, 3, 28), datetime(2014, 3, 29)]
-
- def selection(self, coarse):
- self.debug(f"Universe selection called: {self.time} Count: {len(coarse)}")
-
- expected_time = self._selection_time.pop(0)
- if expected_time != self.time:
- raise ValueError(f"Unexpected selection time {self.time} expected {expected_time}")
-
- # sort descending by daily dollar volume
- sorted_by_dollar_volume = sorted(coarse, key=lambda x: x.dollar_volume, reverse=True)
-
- # return the symbol objects of the top entries from our sorted collection
- underlying_symbols = [ x.symbol for x in sorted_by_dollar_volume[:10] ]
- custom_symbols = []
- for symbol in underlying_symbols:
- custom_symbols.append(Symbol.create_base(MyPyCustomData, symbol))
- return underlying_symbols + custom_symbols
-
- def on_data(self, data):
- '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
-
- Arguments:
- data: Slice object keyed by symbol containing the stock data
- '''
- if not self.portfolio.invested:
- custom_data = data.get(MyPyCustomData)
- if len(custom_data) > 0:
- for symbol in sorted(self.current_underlying_symbols, key=lambda x: x.id.symbol):
- if not self.securities[symbol].has_data:
- continue;
- self.set_holdings(symbol, 1 / len(self.current_underlying_symbols))
-
- if len([x for x in custom_data.keys() if x.underlying == symbol]) == 0:
- raise ValueError(f"Custom data was not found for symbol {symbol}")
-
- def on_end_of_algorithm(self):
- if len(self._selection_time) != 0:
- raise ValueError(f"Unexpected selection times, missing {len(self._selection_time)}")
-
- def OnSecuritiesChanged(self, changes):
- for security in changes.AddedSecurities:
- if security.symbol.security_type == SecurityType.Base:
- continue
- self.current_underlying_symbols.add(security.Symbol)
-
- for security in changes.RemovedSecurities:
- if security.symbol.security_type == SecurityType.Base:
- continue
- self.current_underlying_symbols.remove(security.Symbol)
-
-class MyPyCustomData(PythonData):
-
- def get_source(self, config, date, is_live_mode):
- source = f"{Globals.DataFolder}/equity/usa/daily/{LeanData.generate_zip_file_name(config.symbol, date, config.resolution, config.tick_type)}"
- return SubscriptionDataSource(source)
-
- def reader(self, config, line, date, is_live_mode):
- csv = line.split(',')
- _scaleFactor = 1 / 10000
-
- custom = MyPyCustomData()
- custom.symbol = config.symbol
- custom.time = datetime.strptime(csv[0], '%Y%m%d %H:%M')
- custom.open = float(csv[1]) * _scaleFactor
- custom.high = float(csv[2]) * _scaleFactor
- custom.low = float(csv[3]) * _scaleFactor
- custom.close = float(csv[4]) * _scaleFactor
- custom.value = float(csv[4]) * _scaleFactor
- custom.period = Time.ONE_DAY
- custom.end_time = custom.time + custom.period
-
- return custom
diff --git a/fincept-qt/scripts/strategies/CustomDataUniverseScheduledRegressionAlgorithm.py b/fincept-qt/scripts/strategies/CustomDataUniverseScheduledRegressionAlgorithm.py
deleted file mode 100644
index 41e49d60d..000000000
--- a/fincept-qt/scripts/strategies/CustomDataUniverseScheduledRegressionAlgorithm.py
+++ /dev/null
@@ -1,91 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-72626C25
-# Category: Universe Selection
-# Description: Custom data universe selection regression algorithm asserting it's behavior. Similar to CustomDataUniverseRegressionA...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Custom data universe selection regression algorithm asserting it's behavior. Similar to CustomDataUniverseRegressionAlgorithm but with a custom schedule
-### </summary>
-class CustomDataUniverseScheduledRegressionAlgorithm(QCAlgorithm):
- def initialize(self):
- '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
- self.set_start_date(2014, 3, 24)
- self.set_end_date(2014, 3, 31)
-
- self.current_underlying_symbols = []
- self._selection_time = [datetime(2014, 3, 25), datetime(2014, 3, 27), datetime(2014, 3, 29)]
- self.universe_settings.resolution = Resolution.DAILY;
- self.universe_settings.schedule.on(self.date_rules.on(self._selection_time))
- self.add_universe(CoarseFundamental, "custom-data-universe", self.universe_settings, self.selection)
-
- # This use case is also valid/same because it will use the algorithm settings by default
- # self.add_universe(CoarseFundamental, "custom-data-universe", self.selection)
-
- def selection(self, coarse):
- self.debug(f"Universe selection called: {self.time} Count: {len(coarse)}")
-
- expected_time = self._selection_time.pop(0)
- if expected_time != self.time:
- raise ValueError(f"Unexpected selection time {self.time} expected {expected_time}")
-
- # sort descending by daily dollar volume
- sorted_by_dollar_volume = sorted(coarse, key=lambda x: x.dollar_volume, reverse=True)
-
- # return the symbol objects of the top entries from our sorted collection
- underlying_symbols = [ x.symbol for x in sorted_by_dollar_volume[:10] ]
- custom_symbols = []
- for symbol in underlying_symbols:
- custom_symbols.append(Symbol.create_base(MyPyCustomData, symbol))
- return underlying_symbols + custom_symbols
-
- def on_data(self, data):
- '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
-
- Arguments:
- data: Slice object keyed by symbol containing the stock data
- '''
- if not self.portfolio.invested:
- custom_data = data.get(MyPyCustomData)
- if len(custom_data) > 0:
- for symbol in self.current_underlying_symbols:
- self.set_holdings(symbol, 1 / len(self.current_underlying_symbols))
-
- if len([x for x in custom_data.keys() if x.underlying == symbol]) == 0:
- raise ValueError(f"Custom data was not found for symbol {symbol}")
- # equity daily data arrives at 16 pm but custom data is set to arrive at midnight
- self.current_underlying_symbols = [symbol for symbol in data.keys() if symbol.security_type is SecurityType.EQUITY]
-
- def on_end_of_algorithm(self):
- if len(self._selection_time) != 0:
- raise ValueError(f"Unexpected selection times, missing {len(self._selection_time)}")
-
-class MyPyCustomData(PythonData):
-
- def get_source(self, config, date, is_live_mode):
- source = f"{Globals.DataFolder}/equity/usa/daily/{LeanData.generate_zip_file_name(config.symbol, date, config.resolution, config.tick_type)}"
- return SubscriptionDataSource(source)
-
- def reader(self, config, line, date, is_live_mode):
- csv = line.split(',')
- _scaleFactor = 1 / 10000
-
- custom = MyPyCustomData()
- custom.symbol = config.symbol
- custom.time = datetime.strptime(csv[0], '%Y%m%d %H:%M')
- custom.open = float(csv[1]) * _scaleFactor
- custom.high = float(csv[2]) * _scaleFactor
- custom.low = float(csv[3]) * _scaleFactor
- custom.close = float(csv[4]) * _scaleFactor
- custom.value = float(csv[4]) * _scaleFactor
- custom.period = Time.ONE_DAY
- custom.end_time = custom.time + custom.period
-
- return custom
diff --git a/fincept-qt/scripts/strategies/CustomDataUsingMapFileRegressionAlgorithm.py b/fincept-qt/scripts/strategies/CustomDataUsingMapFileRegressionAlgorithm.py
deleted file mode 100644
index bdd93be96..000000000
--- a/fincept-qt/scripts/strategies/CustomDataUsingMapFileRegressionAlgorithm.py
+++ /dev/null
@@ -1,92 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-BEF6D76E
-# Category: Regression Test
-# Description: Regression algorithm demonstrating use of map files with custom data
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Regression algorithm demonstrating use of map files with custom data
-### </summary>
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="custom data" />
-### <meta name="tag" content="regression test" />
-### <meta name="tag" content="rename event" />
-### <meta name="tag" content="map" />
-### <meta name="tag" content="mapping" />
-### <meta name="tag" content="map files" />
-class CustomDataUsingMapFileRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self):
- # Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
- self.set_start_date(2013, 6, 27)
- self.set_end_date(2013, 7, 2)
-
- self.initial_mapping = False
- self.execution_mapping = False
- self.foxa = Symbol.create("FOXA", SecurityType.EQUITY, Market.USA)
- self._symbol = self.add_data(CustomDataUsingMapping, self.foxa).symbol
-
- for config in self.subscription_manager.subscription_data_config_service.get_subscription_data_configs(self._symbol):
- if config.resolution != Resolution.MINUTE:
- raise ValueError("Expected resolution to be set to Minute")
-
- def on_data(self, slice):
- date = self.time.date()
- if slice.symbol_changed_events.contains_key(self._symbol):
- mapping_event = slice.symbol_changed_events[self._symbol]
- self.log("{0} - Ticker changed from: {1} to {2}".format(str(self.time), mapping_event.old_symbol, mapping_event.new_symbol))
-
- if date == datetime(2013, 6, 27).date():
- # we should Not receive the initial mapping event
- if mapping_event.new_symbol != "NWSA" or mapping_event.old_symbol != "FOXA":
- raise Exception("Unexpected mapping event mapping_event")
- self.initial_mapping = True
-
- if date == datetime(2013, 6, 29).date():
- if mapping_event.new_symbol != "FOXA" or mapping_event.old_symbol != "NWSA":
- raise Exception("Unexpected mapping event mapping_event")
- self.set_holdings(self._symbol, 1)
- self.execution_mapping = True
-
- def on_end_of_algorithm(self):
- if self.initial_mapping:
- raise Exception("The ticker generated the initial rename event")
- if not self.execution_mapping:
- raise Exception("The ticker did not rename throughout the course of its life even though it should have")
-
-class CustomDataUsingMapping(PythonData):
- '''Test example custom data showing how to enable the use of mapping.
- Implemented as a wrapper of existing NWSA->FOXA equity'''
-
- def get_source(self, config, date, is_live_mode):
- return TradeBar().get_source(SubscriptionDataConfig(config, CustomDataUsingMapping,
- # create a new symbol as equity so we find the existing data files
- Symbol.create(config.mapped_symbol, SecurityType.EQUITY, config.market)),
- date,
- is_live_mode)
-
- def reader(self, config, line, date, is_live_mode):
- return TradeBar.parse_equity(config, line, date)
-
- def requires_mapping(self):
- '''True indicates mapping should be done'''
- return True
-
- def is_sparse_data(self):
- '''Indicates that the data set is expected to be sparse'''
- return True
-
- def default_resolution(self):
- '''Gets the default resolution for this data and security type'''
- return Resolution.MINUTE
-
- def supported_resolutions(self):
- '''Gets the supported resolution for this data and security type'''
- return [ Resolution.MINUTE ]
diff --git a/fincept-qt/scripts/strategies/CustomDataZippedObjectStoreRegressionAlgorithm.py b/fincept-qt/scripts/strategies/CustomDataZippedObjectStoreRegressionAlgorithm.py
deleted file mode 100644
index b4e4ed858..000000000
--- a/fincept-qt/scripts/strategies/CustomDataZippedObjectStoreRegressionAlgorithm.py
+++ /dev/null
@@ -1,26 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-95644B6E
-# Category: Regression Test
-# Description: Regression algorithm demonstrating the use of zipped custom data sourced from the object store
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-from CustomDataObjectStoreRegressionAlgorithm import *
-
-### <summary>
-### Regression algorithm demonstrating the use of zipped custom data sourced from the object store
-### </summary>
-class CustomDataZippedObjectStoreRegressionAlgorithm(CustomDataObjectStoreRegressionAlgorithm):
-
- def get_custom_data_key(self):
- return "CustomData/ExampleCustomData.zip"
-
- def save_data_to_object_store(self):
- self.object_store.save_bytes(self.get_custom_data_key(), Compression.zip_bytes(bytes(self.custom_data, 'utf-8'), 'data'))
-
diff --git a/fincept-qt/scripts/strategies/CustomIndicatorAlgorithm.py b/fincept-qt/scripts/strategies/CustomIndicatorAlgorithm.py
deleted file mode 100644
index 645f105f5..000000000
--- a/fincept-qt/scripts/strategies/CustomIndicatorAlgorithm.py
+++ /dev/null
@@ -1,72 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-0B5CD58B
-# Category: Indicators
-# Description: Demonstrates how to create a custom indicator and register it for automatic updated
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-from collections import deque
-
-### <summary>
-### Demonstrates how to create a custom indicator and register it for automatic updated
-### </summary>
-### <meta name="tag" content="indicators" />
-### <meta name="tag" content="indicator classes" />
-### <meta name="tag" content="custom indicator" />
-class CustomIndicatorAlgorithm(QCAlgorithm):
- def initialize(self):
- self.set_start_date(2013,10,7)
- self.set_end_date(2013,10,11)
- self.add_equity("SPY", Resolution.SECOND)
-
- # Create a QuantConnect indicator and a python custom indicator for comparison
- self._sma = self.sma("SPY", 60, Resolution.MINUTE)
- self.custom = CustomSimpleMovingAverage('custom', 60)
-
- # The python custom class must inherit from PythonIndicator to enable Updated event handler
- self.custom.updated += self.custom_updated
-
- self.custom_window = RollingWindow[IndicatorDataPoint](5)
- self.register_indicator("SPY", self.custom, Resolution.MINUTE)
- self.plot_indicator('CSMA', self.custom)
-
- def custom_updated(self, sender, updated):
- self.custom_window.add(updated)
-
- def on_data(self, data):
- if not self.portfolio.invested:
- self.set_holdings("SPY", 1)
-
- if self.time.second == 0:
- self.log(f" sma -> IsReady: {self._sma.is_ready}. Value: {self._sma.current.value}")
- self.log(f"custom -> IsReady: {self.custom.is_ready}. Value: {self.custom.value}")
-
- # Regression test: test fails with an early quit
- diff = abs(self.custom.value - self._sma.current.value)
- if diff > 1e-10:
- self.quit(f"Quit: indicators difference is {diff}")
-
- def on_end_of_algorithm(self):
- for item in self.custom_window:
- self.log(f'{item}')
-
-# Python implementation of SimpleMovingAverage.
-# Represents the traditional simple moving average indicator (SMA).
-class CustomSimpleMovingAverage(PythonIndicator):
- def __init__(self, name, period):
- super().__init__()
- self.name = name
- self.value = 0
- self.queue = deque(maxlen=period)
-
- # Update method is mandatory
- def update(self, input):
- self.queue.appendleft(input.value)
- count = len(self.queue)
- self.value = np.sum(self.queue) / count
- return count == self.queue.maxlen
diff --git a/fincept-qt/scripts/strategies/CustomIndicatorWithExtensionAlgorithm.py b/fincept-qt/scripts/strategies/CustomIndicatorWithExtensionAlgorithm.py
deleted file mode 100644
index c2e14864e..000000000
--- a/fincept-qt/scripts/strategies/CustomIndicatorWithExtensionAlgorithm.py
+++ /dev/null
@@ -1,86 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-E42C0F2D
-# Category: Indicators
-# Description: Custom Indicator With Extension Algorithm
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-from collections import deque
-from math import isclose
-
-class CustomIndicatorWithExtensionAlgorithm(QCAlgorithm):
- def initialize(self):
- self.set_start_date(2013, 10, 9)
- self.set_end_date(2013, 10, 9)
-
- self.spy = self.add_equity("SPY", Resolution.MINUTE).symbol
-
- self.sma_values = []
- self.period = 10
-
- self.sma = self.sma(self.spy, self.period, Resolution.MINUTE)
- self.sma.updated += self.on_sma_updated
-
- self.custom_sma = CustomSimpleMovingAverage("My SMA", self.period)
- self.ext = IndicatorExtensions.of(self.custom_sma, self.sma)
- self.ext.updated += self.on_indicator_extension_updated
-
- self.sma_minus_custom = IndicatorExtensions.minus(self.sma, self.custom_sma)
- self.sma_minus_custom.updated += self.on_minus_updated
-
- self.sma_was_updated = False
- self.custom_sma_was_updated = False
- self.sma_minus_custom_was_updated = False
-
- def on_sma_updated(self, sender, updated):
- self.sma_was_updated = True
-
- if self.sma.is_ready:
- self.sma_values.append(self.sma.current.value)
-
- def on_indicator_extension_updated(self, sender, updated):
- self.custom_sma_was_updated = True
-
- sma_last_values = self.sma_values[-self.period:]
- expected = sum(sma_last_values) / len(sma_last_values)
-
- if not isclose(expected, self.custom_sma.value):
- raise Exception(f"Expected the custom SMA to calculate the moving average of the last {self.period} values of the SMA. "
- f"Current expected: {expected}. Actual {self.custom_sma.value}.")
-
- self.debug(f"{self.sma.current.value} :: {self.custom_sma.value} :: {updated}")
-
- def on_minus_updated(self, sender, updated):
- self.sma_minus_custom_was_updated = True
-
- expected = self.sma.current.value - self.custom_sma.value
-
- if not isclose(expected, self.sma_minus_custom.current.value):
- raise Exception(f"Expected the composite minus indicator to calculate the difference between the SMA and custom SMA indicators. "
- f"Expected: {expected}. Actual {self.sma_minus_custom.current.value}.")
-
- def on_end_of_algorithm(self):
- if not (self.sma_was_updated and self.custom_sma_was_updated and self.sma_minus_custom_was_updated):
- raise Exception("Expected all indicators to have been updated.")
-
-# Custom indicator
-class CustomSimpleMovingAverage(PythonIndicator):
- def __init__(self, name, period):
- self.name = name
- self.value = 0
- self.warm_up_period = period
- self.queue = deque(maxlen=period)
-
- def update(self, input: BaseData) -> bool:
- self.queue.appendleft(input.value)
- count = len(self.queue)
- self.value = sum(self.queue) / count
-
- return count == self.queue.maxlen
-
diff --git a/fincept-qt/scripts/strategies/CustomMarginInterestRateModelAlgorithm.py b/fincept-qt/scripts/strategies/CustomMarginInterestRateModelAlgorithm.py
deleted file mode 100644
index 6e6015c03..000000000
--- a/fincept-qt/scripts/strategies/CustomMarginInterestRateModelAlgorithm.py
+++ /dev/null
@@ -1,60 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-F06C15CD
-# Category: Margin
-# Description: Demonstration of using custom margin interest rate model in backtesting
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Demonstration of using custom margin interest rate model in backtesting.
-### </summary>
-class CustomMarginInterestRateModelAlgorithm(QCAlgorithm):
- def initialize(self):
- self.set_start_date(2013, 10, 1)
- self.set_end_date(2013, 10, 31)
-
- security = self.add_equity("SPY", Resolution.HOUR)
- self._spy = security.symbol
-
- # set the margin interest rate model
- self._margin_interest_rate_model = CustomMarginInterestRateModel()
- security.set_margin_interest_rate_model(self._margin_interest_rate_model)
-
- self._cash_after_order = 0
-
- def on_data(self, data: Slice):
- if not self.portfolio.invested:
- self.set_holdings(self._spy, 1)
-
- def on_order_event(self, order_event: OrderEvent):
- if order_event.status == OrderStatus.FILLED:
- self._cash_after_order = self.portfolio.cash
-
- def on_end_of_algorithm(self):
- if self._margin_interest_rate_model.call_count == 0:
- raise Exception("CustomMarginInterestRateModel was not called")
-
- expected_cash = self._cash_after_order * pow(1 + self._margin_interest_rate_model.interest_rate, self._margin_interest_rate_model.call_count)
-
- if abs(self.portfolio.cash - expected_cash) > 1e-10:
- raise Exception(f"Expected cash {expected_cash} but got {self.portfolio.cash}")
-
-
-class CustomMarginInterestRateModel:
- def __init__(self):
- self.interest_rate = 0.01
- self.call_count = 0
-
- def apply_margin_interest_rate(self, parameters: MarginInterestRateParameters):
- security = parameters.security
- position_value = security.holdings.get_quantity_value(security.holdings.quantity)
-
- if position_value.amount > 0:
- position_value.cash.add_amount(self.interest_rate * position_value.cash.amount)
- self.call_count += 1
diff --git a/fincept-qt/scripts/strategies/CustomModelsAlgorithm.py b/fincept-qt/scripts/strategies/CustomModelsAlgorithm.py
deleted file mode 100644
index 3c4c4aeb0..000000000
--- a/fincept-qt/scripts/strategies/CustomModelsAlgorithm.py
+++ /dev/null
@@ -1,179 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-C77A7B18
-# Category: General Strategy
-# Description: Demonstration of using custom fee, slippage, fill, and buying power models for modelling transactions in backtesting....
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-import random
-
-### <summary>
-### Demonstration of using custom fee, slippage, fill, and buying power models for modelling transactions in backtesting.
-### QuantConnect allows you to model all orders as deeply and accurately as you need.
-### </summary>
-### <meta name="tag" content="trading and orders" />
-### <meta name="tag" content="transaction fees and slippage" />
-### <meta name="tag" content="custom buying power models" />
-### <meta name="tag" content="custom transaction models" />
-### <meta name="tag" content="custom slippage models" />
-### <meta name="tag" content="custom fee models" />
-class CustomModelsAlgorithm(QCAlgorithm):
- '''Demonstration of using custom fee, slippage, fill, and buying power models for modelling transactions in backtesting.
- QuantConnect allows you to model all orders as deeply and accurately as you need.'''
-
- def initialize(self):
- self.set_start_date(2013,10,1) # Set Start Date
- self.set_end_date(2013,10,31) # Set End Date
- self.security = self.add_equity("SPY", Resolution.HOUR)
- self.spy = self.security.symbol
-
- # set our models
- self.security.set_fee_model(CustomFeeModel(self))
- self.security.set_fill_model(CustomFillModel(self))
- self.security.set_slippage_model(CustomSlippageModel(self))
- self.security.set_buying_power_model(CustomBuyingPowerModel(self))
-
- def on_data(self, data):
- open_orders = self.transactions.get_open_orders(self.spy)
- if len(open_orders) != 0: return
-
- if self.time.day > 10 and self.security.holdings.quantity <= 0:
- quantity = self.calculate_order_quantity(self.spy, .5)
- self.log(f"MarketOrder: {quantity}")
- self.market_order(self.spy, quantity, True) # async needed for partial fill market orders
-
- elif self.time.day > 20 and self.security.holdings.quantity >= 0:
- quantity = self.calculate_order_quantity(self.spy, -.5)
- self.log(f"MarketOrder: {quantity}")
- self.market_order(self.spy, quantity, True) # async needed for partial fill market orders
-
-# If we want to use methods from other models, you need to inherit from one of them
-class CustomFillModel(ImmediateFillModel):
- def __init__(self, algorithm):
- super().__init__()
- self.algorithm = algorithm
- self.absolute_remaining_by_order_id = {}
- self.random = Random(387510346)
-
- def market_fill(self, asset, order):
- absolute_remaining = order.absolute_quantity
-
- if order.id in self.absolute_remaining_by_order_id.keys():
- absolute_remaining = self.absolute_remaining_by_order_id[order.id]
-
- fill = super().market_fill(asset, order)
- absolute_fill_quantity = int(min(absolute_remaining, self.random.next(0, 2*int(order.absolute_quantity))))
- fill.fill_quantity = np.sign(order.quantity) * absolute_fill_quantity
-
- if absolute_remaining == absolute_fill_quantity:
- fill.status = OrderStatus.FILLED
- if self.absolute_remaining_by_order_id.get(order.id):
- self.absolute_remaining_by_order_id.pop(order.id)
- else:
- absolute_remaining = absolute_remaining - absolute_fill_quantity
- self.absolute_remaining_by_order_id[order.id] = absolute_remaining
- fill.status = OrderStatus.PARTIALLY_FILLED
- self.algorithm.log(f"CustomFillModel: {fill}")
- return fill
-
-class CustomFeeModel(FeeModel):
- def __init__(self, algorithm):
- super().__init__()
- self.algorithm = algorithm
-
- def get_order_fee(self, parameters):
- # custom fee math
- fee = max(1, parameters.security.price
- * parameters.order.absolute_quantity
- * 0.00001)
- self.algorithm.log(f"CustomFeeModel: {fee}")
- return OrderFee(CashAmount(fee, "USD"))
-
-class CustomSlippageModel:
- def __init__(self, algorithm):
- self.algorithm = algorithm
-
- def get_slippage_approximation(self, asset, order):
- # custom slippage math
- slippage = asset.price * 0.0001 * np.log10(2*float(order.absolute_quantity))
- self.algorithm.log(f"CustomSlippageModel: {slippage}")
- return slippage
-
-class CustomBuyingPowerModel(BuyingPowerModel):
- def __init__(self, algorithm):
- super().__init__()
- self.algorithm = algorithm
-
- def has_sufficient_buying_power_for_order(self, parameters):
- # custom behavior: this model will assume that there is always enough buying power
- has_sufficient_buying_power_for_order_result = HasSufficientBuyingPowerForOrderResult(True)
- self.algorithm.log(f"CustomBuyingPowerModel: {has_sufficient_buying_power_for_order_result.is_sufficient}")
- return has_sufficient_buying_power_for_order_result
-
-# The simple fill model shows how to implement a simpler version of
-# the most popular order fills: Market, Stop Market and Limit
-class SimpleCustomFillModel(FillModel):
- def __init__(self):
- super().__init__()
-
- def _create_order_event(self, asset, order):
- utc_time = Extensions.convert_to_utc(asset.local_time, asset.exchange.time_zone)
- return OrderEvent(order, utc_time, OrderFee.ZERO)
-
- def _set_order_event_to_filled(self, fill, fill_price, fill_quantity):
- fill.status = OrderStatus.FILLED
- fill.fill_quantity = fill_quantity
- fill.fill_price = fill_price
- return fill
-
- def _get_trade_bar(self, asset, order_direction):
- trade_bar = asset.cache.get_data[TradeBar]()
- if trade_bar: return trade_bar
-
- # Tick-resolution data doesn't have TradeBar, use the asset price
- price = asset.price
- return TradeBar(asset.local_time, asset.symbol, price, price, price, price, 0)
-
- def market_fill(self, asset, order):
- fill = self._create_order_event(asset, order)
- if order.status == OrderStatus.CANCELED: return fill
-
- return self._set_order_event_to_filled(fill,
- asset.cache.ask_price \
- if order.direction == OrderDirection.BUY else asset.cache.bid_price,
- order.quantity)
-
- def stop_market_fill(self, asset, order):
- fill = self._create_order_event(asset, order)
- if order.status == OrderStatus.CANCELED: return fill
-
- stop_price = order.stop_price
- trade_bar = self._get_trade_bar(asset, order.direction)
-
- if order.direction == OrderDirection.SELL and trade_bar.low < stop_price:
- return self._set_order_event_to_filled(fill, stop_price, order.quantity)
-
- if order.direction == OrderDirection.BUY and trade_bar.high > stop_price:
- return self._set_order_event_to_filled(fill, stop_price, order.quantity)
-
- return fill
-
- def limit_fill(self, asset, order):
- fill = self._create_order_event(asset, order)
- if order.status == OrderStatus.CANCELED: return fill
-
- limit_price = order.limit_price
- trade_bar = self._get_trade_bar(asset, order.direction)
-
- if order.direction == OrderDirection.SELL and trade_bar.high > limit_price:
- return self._set_order_event_to_filled(fill, limit_price, order.quantity)
-
- if order.direction == OrderDirection.BUY and trade_bar.low < limit_price:
- return self._set_order_event_to_filled(fill, limit_price, order.quantity)
-
- return fill
diff --git a/fincept-qt/scripts/strategies/CustomModelsPEP8Algorithm.py b/fincept-qt/scripts/strategies/CustomModelsPEP8Algorithm.py
deleted file mode 100644
index 30e915f84..000000000
--- a/fincept-qt/scripts/strategies/CustomModelsPEP8Algorithm.py
+++ /dev/null
@@ -1,176 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-3555D255
-# Category: General Strategy
-# Description: Demonstration of using custom fee, slippage, fill, and buying power models for modeling transactions in backtesting. ...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-import random
-
-### <summary>
-### Demonstration of using custom fee, slippage, fill, and buying power models for modeling transactions in backtesting.
-### QuantConnect allows you to model all orders as deeply and accurately as you need.
-### This example illustrates how Lean exports its API to Python conforming to PEP8 style guide.
-### </summary>
-### <meta name="tag" content="trading and orders" />
-### <meta name="tag" content="transaction fees and slippage" />
-### <meta name="tag" content="custom buying power models" />
-### <meta name="tag" content="custom transaction models" />
-### <meta name="tag" content="custom slippage models" />
-### <meta name="tag" content="custom fee models" />
-class CustomModelsPEP8Algorithm(QCAlgorithm):
- '''Demonstration of using custom fee, slippage, fill, and buying power models for modeling transactions in backtesting.
- QuantConnect allows you to model all orders as deeply and accurately as you need.'''
-
- def initialize(self):
- self.set_start_date(2013,10,1) # Set Start Date
- self.set_end_date(2013,10,31) # Set End Date
- self.security = self.add_equity("SPY", Resolution.HOUR)
- self.spy = self.security.symbol
-
- # set our models
- self.security.set_fee_model(CustomFeeModelPEP8(self))
- self.security.set_fill_model(CustomFillModelPEP8(self))
- self.security.set_slippage_model(CustomSlippageModelPEP8(self))
- self.security.set_buying_power_model(CustomBuyingPowerModelPEP8(self))
-
- def on_data(self, data):
- open_orders = self.transactions.get_open_orders(self.spy)
- if len(open_orders) != 0: return
- if self.time.day > 10 and self.security.holdings.quantity <= 0:
- quantity = self.calculate_order_quantity(self.spy, .5)
- self.log(f"MarketOrder: {quantity}")
- self.market_order(self.spy, quantity, True) # async needed for partial fill market orders
- elif self.time.day > 20 and self.security.holdings.quantity >= 0:
- quantity = self.calculate_order_quantity(self.spy, -.5)
- self.log(f"MarketOrder: {quantity}")
- self.market_order(self.spy, quantity, True) # async needed for partial fill market orders
-
-class CustomFillModelPEP8(ImmediateFillModel):
- def __init__(self, algorithm):
- super().__init__()
- self.algorithm = algorithm
- self.absolute_remaining_by_order_id = {}
- self.random = Random(387510346)
-
- def market_fill(self, asset, order):
- absolute_remaining = order.absolute_quantity
-
- if order.id in self.absolute_remaining_by_order_id.keys():
- absolute_remaining = self.absolute_remaining_by_order_id[order.id]
-
- fill = super().market_fill(asset, order)
- absolute_fill_quantity = int(min(absolute_remaining, self.random.next(0, 2*int(order.absolute_quantity))))
- fill.fill_quantity = np.sign(order.quantity) * absolute_fill_quantity
-
- if absolute_remaining == absolute_fill_quantity:
- fill.status = OrderStatus.FILLED
- if self.absolute_remaining_by_order_id.get(order.id):
- self.absolute_remaining_by_order_id.pop(order.id)
- else:
- absolute_remaining = absolute_remaining - absolute_fill_quantity
- self.absolute_remaining_by_order_id[order.id] = absolute_remaining
- fill.status = OrderStatus.PARTIALLY_FILLED
- self.algorithm.log(f"CustomFillModel: {fill}")
- return fill
-
-class CustomFeeModelPEP8(FeeModel):
- def __init__(self, algorithm):
- super().__init__()
- self.algorithm = algorithm
-
- def get_order_fee(self, parameters):
- # custom fee math
- fee = max(1, parameters.security.price
- * parameters.order.absolute_quantity
- * 0.00001)
- self.algorithm.log(f"CustomFeeModel: {fee}")
- return OrderFee(CashAmount(fee, "USD"))
-
-class CustomSlippageModelPEP8:
- def __init__(self, algorithm):
- self.algorithm = algorithm
-
- def get_slippage_approximation(self, asset, order):
- # custom slippage math
- slippage = asset.price * 0.0001 * np.log10(2*float(order.absolute_quantity))
- self.algorithm.log(f"CustomSlippageModel: {slippage}")
- return slippage
-
-class CustomBuyingPowerModelPEP8(BuyingPowerModel):
- def __init__(self, algorithm):
- super().__init__()
- self.algorithm = algorithm
-
- def has_sufficient_buying_power_for_order(self, parameters):
- # custom behavior: this model will assume that there is always enough buying power
- has_sufficient_buying_power_for_order_result = HasSufficientBuyingPowerForOrderResult(True)
- self.algorithm.log(f"CustomBuyingPowerModel: {has_sufficient_buying_power_for_order_result.is_sufficient}")
- return has_sufficient_buying_power_for_order_result
-
-class SimpleCustomFillModelPEP8(FillModel):
- def __init__(self):
- super().__init()
-
- def _create_order_event(self, asset, order):
- utc_time = Extensions.convert_to_utc(asset.local_time, asset.exchange.time_zone)
- return OrderEvent(order, utc_time, OrderFee.ZERO)
-
- def _set_order_event_to_filled(self, fill, fill_price, fill_quantity):
- fill.status = OrderStatus.FILLED
- fill.fill_quantity = fill_quantity
- fill.fill_price = fill_price
- return fill
-
- def _get_trade_bar(self, asset, order_direction):
- trade_bar = asset.cache.get_data[TradeBar]()
- if trade_bar:
- return trade_bar
-
- price = asset.price
- return TradeBar(asset.local_time, asset.symbol, price, price, price, price, 0)
-
- def market_fill(self, asset, order):
- fill = self._create_order_event(asset, order)
- if order.status == OrderStatus.CANCELED:
- return fill
-
- fill_price = asset.cache.ask_price if order.direction == OrderDirection.BUY else asset.cache.bid_price
- return self._set_order_event_to_filled(fill, fill_price, order.quantity)
-
- def stop_market_fill(self, asset, order):
- fill = self._create_order_event(asset, order)
- if order.status == OrderStatus.CANCELED:
- return fill
-
- stop_price = order.stop_price
- trade_bar = self._get_trade_bar(asset, order.direction)
-
- if order.direction == OrderDirection.SELL and trade_bar.low < stop_price:
- return self._set_order_event_to_filled(fill, stop_price, order.quantity)
-
- if order.direction == OrderDirection.BUY and trade_bar.high > stop_price:
- return self._set_order_event_to_filled(fill, stop_price, order.quantity)
-
- return fill
-
- def limit_fill(self, asset, order):
- fill = self._create_order_event(asset, order)
- if order.status == OrderStatus.CANCELED:
- return fill
-
- limit_price = order.limit_price
- trade_bar = self._get_trade_bar(asset, order.direction)
-
- if order.direction == OrderDirection.SELL and trade_bar.high > limit_price:
- return self._set_order_event_to_filled(fill, limit_price, order.quantity)
-
- if order.direction == OrderDirection.BUY and trade_bar.low < limit_price:
- return self._set_order_event_to_filled(fill, limit_price, order.quantity)
-
- return fill
diff --git a/fincept-qt/scripts/strategies/CustomOptionAssignmentRegressionAlgorithm.py b/fincept-qt/scripts/strategies/CustomOptionAssignmentRegressionAlgorithm.py
deleted file mode 100644
index 356b41de4..000000000
--- a/fincept-qt/scripts/strategies/CustomOptionAssignmentRegressionAlgorithm.py
+++ /dev/null
@@ -1,38 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-8C620280
-# Category: Options
-# Description: Regression algorithm asserting we can specify a custom option assignment
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-from QuantConnect.Algorithm.CSharp import *
-
-### <summary>
-### Regression algorithm asserting we can specify a custom option assignment
-### </summary>
-class CustomOptionAssignmentRegressionAlgorithm(OptionAssignmentRegressionAlgorithm):
- def initialize(self):
- self.set_security_initializer(self.custom_security_initializer)
- super().initialize()
-
- def custom_security_initializer(self, security):
- if Extensions.is_option(security.symbol.security_type):
- # we have to be 10% in the money to get assigned
- security.set_option_assignment_model(PyCustomOptionAssignmentModel(0.1))
-
- def on_data(self, data):
- super().on_data(data)
-
-class PyCustomOptionAssignmentModel(DefaultOptionAssignmentModel):
- def __init__(self, required_in_the_money_percent):
- super().__init__(required_in_the_money_percent)
-
- def get_assignment(self, parameters):
- result = super().get_assignment(parameters)
- result.tag = "Custom Option Assignment"
- return result
diff --git a/fincept-qt/scripts/strategies/CustomOptionExerciseModelRegressionAlgorithm.py b/fincept-qt/scripts/strategies/CustomOptionExerciseModelRegressionAlgorithm.py
deleted file mode 100644
index 90d7887e3..000000000
--- a/fincept-qt/scripts/strategies/CustomOptionExerciseModelRegressionAlgorithm.py
+++ /dev/null
@@ -1,44 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-A7E25D46
-# Category: Options
-# Description: Regression algorithm asserting we can specify a custom option exercise model
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-from QuantConnect.Algorithm.CSharp import *
-
-### <summary>
-### Regression algorithm asserting we can specify a custom option exercise model
-### </summary>
-class CustomOptionExerciseModelRegressionAlgorithm(OptionAssignmentRegressionAlgorithm):
- def initialize(self):
- self.set_security_initializer(self.custom_security_initializer)
- super().initialize()
-
- def custom_security_initializer(self, security):
- if Extensions.is_option(security.symbol.security_type):
- security.set_option_exercise_model(CustomExerciseModel())
-
- def on_data(self, data):
- super().on_data(data)
-
-class CustomExerciseModel(DefaultExerciseModel):
- def option_exercise(self, option: Option, order: OptionExerciseOrder):
- order_event = OrderEvent(
- order.id,
- option.symbol,
- Extensions.convert_to_utc(option.local_time, option.exchange.time_zone),
- OrderStatus.FILLED,
- Extensions.get_order_direction(order.quantity),
- 0.0,
- order.quantity,
- OrderFee.ZERO,
- "Tag"
- )
- order_event.is_assignment = False
- return [ order_event ]
diff --git a/fincept-qt/scripts/strategies/CustomPartialFillModelAlgorithm.py b/fincept-qt/scripts/strategies/CustomPartialFillModelAlgorithm.py
deleted file mode 100644
index 173a35747..000000000
--- a/fincept-qt/scripts/strategies/CustomPartialFillModelAlgorithm.py
+++ /dev/null
@@ -1,70 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-3E3DC670
-# Category: General Strategy
-# Description: Basic template algorithm that implements a fill model with partial fills
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Basic template algorithm that implements a fill model with partial fills
-### <meta name="tag" content="trading and orders" />
-### </summary>
-class CustomPartialFillModelAlgorithm(QCAlgorithm):
- '''Basic template algorithm that implements a fill model with partial fills'''
-
- def initialize(self):
- self.set_start_date(2019, 1, 1)
- self.set_end_date(2019, 3, 1)
-
- equity = self.add_equity("SPY", Resolution.HOUR)
- self.spy = equity.symbol
- self.holdings = equity.holdings
-
- # Set the fill model
- equity.set_fill_model(CustomPartialFillModel(self))
-
-
- def on_data(self, data):
- open_orders = self.transactions.get_open_orders(self.spy)
- if len(open_orders) != 0: return
-
- if self.time.day > 10 and self.holdings.quantity <= 0:
- self.market_order(self.spy, 105, True)
-
- elif self.time.day > 20 and self.holdings.quantity >= 0:
- self.market_order(self.spy, -100, True)
-
-
-class CustomPartialFillModel(FillModel):
- '''Implements a custom fill model that inherit from FillModel. Override the MarketFill method to simulate partially fill orders'''
-
- def __init__(self, algorithm):
- self.algorithm = algorithm
- self.absolute_remaining_by_order_id = {}
-
- def market_fill(self, asset, order):
- absolute_remaining = self.absolute_remaining_by_order_id.get(order.id, order. AbsoluteQuantity)
-
- # Create the object
- fill = super().market_fill(asset, order)
-
- # Set the fill amount
- fill.fill_quantity = np.sign(order.quantity) * 10
-
- if (min(abs(fill.fill_quantity), absolute_remaining) == absolute_remaining):
- fill.fill_quantity = np.sign(order.quantity) * absolute_remaining
- fill.status = OrderStatus.FILLED
- self.absolute_remaining_by_order_id.pop(order.id, None)
- else:
- fill.status = OrderStatus.PARTIALLY_FILLED
- self.absolute_remaining_by_order_id[order.id] = absolute_remaining - abs(fill.fill_quantity)
- price = fill.fill_price
- # self.algorithm.debug(f"{self.algorithm.time} - Partial Fill - Remaining {self.absolute_remaining_by_order_id[order.id]} Price - {price}")
-
- return fill
diff --git a/fincept-qt/scripts/strategies/CustomPortfolioOptimizerRegressionAlgorithm.py b/fincept-qt/scripts/strategies/CustomPortfolioOptimizerRegressionAlgorithm.py
deleted file mode 100644
index abf932f19..000000000
--- a/fincept-qt/scripts/strategies/CustomPortfolioOptimizerRegressionAlgorithm.py
+++ /dev/null
@@ -1,29 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-9C9C9891
-# Category: Portfolio Management
-# Description: Regression algorithm asserting we can specify a custom portfolio optimizer with a MeanVarianceOptimizationPortfolioCo...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-from MeanVarianceOptimizationFrameworkAlgorithm import MeanVarianceOptimizationFrameworkAlgorithm
-
-### <summary>
-### Regression algorithm asserting we can specify a custom portfolio
-### optimizer with a MeanVarianceOptimizationPortfolioConstructionModel
-### </summary>
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="using quantconnect" />
-### <meta name="tag" content="trading and orders" />
-class CustomPortfolioOptimizerRegressionAlgorithm(MeanVarianceOptimizationFrameworkAlgorithm):
- def initialize(self):
- super().initialize()
- self.set_portfolio_construction(MeanVarianceOptimizationPortfolioConstructionModel(timedelta(days=1), PortfolioBias.LONG_SHORT, 1, 63, Resolution.DAILY, 0.02, CustomPortfolioOptimizer()))
-
-class CustomPortfolioOptimizer:
- def optimize(self, historical_returns, expected_returns, covariance):
- return [0.5]*(np.array(historical_returns)).shape[1]
diff --git a/fincept-qt/scripts/strategies/CustomSecurityDataFilterRegressionAlgorithm.py b/fincept-qt/scripts/strategies/CustomSecurityDataFilterRegressionAlgorithm.py
deleted file mode 100644
index 369afe355..000000000
--- a/fincept-qt/scripts/strategies/CustomSecurityDataFilterRegressionAlgorithm.py
+++ /dev/null
@@ -1,42 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-2F0E8AB5
-# Category: Regression Test
-# Description: Regression algorithm asserting we can specify a custom security data filter
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Regression algorithm asserting we can specify a custom security data filter
-### </summary>
-class CustomSecurityDataFilterRegressionAlgorithm(QCAlgorithm):
- def initialize(self):
- self.set_cash(2500000)
- self.set_start_date(2013,10,7)
- self.set_end_date(2013,10,7)
-
- security = self.add_security(SecurityType.EQUITY, "SPY")
- security.set_data_filter(CustomDataFilter())
- self.data_points = 0
-
- def on_data(self, data):
- self.data_points += 1
- self.set_holdings("SPY", 0.2)
- if self.data_points > 5:
- raise Exception("There should not be more than 5 data points, but there were " + str(self.data_points))
-
-
-class CustomDataFilter(SecurityDataFilter):
- def filter(self, vehicle: Security, data: BaseData) -> bool:
- """
- Skip data after 9:35am
- """
- if data.time >= datetime(2013,10,7,9,35,0):
- return False
- else:
- return True
diff --git a/fincept-qt/scripts/strategies/CustomSecurityInitializerAlgorithm.py b/fincept-qt/scripts/strategies/CustomSecurityInitializerAlgorithm.py
deleted file mode 100644
index 7d85fca20..000000000
--- a/fincept-qt/scripts/strategies/CustomSecurityInitializerAlgorithm.py
+++ /dev/null
@@ -1,81 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-C15813B3
-# Category: General Strategy
-# Description: This algorithm shows how to set a custom security initializer. A security initializer is run immediately after a new ...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### This algorithm shows how to set a custom security initializer.
-### A security initializer is run immediately after a new security object
-### has been created and can be used to security models and other settings,
-### such as data normalization mode
-### </summary>
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="securities and portfolio" />
-### <meta name="tag" content="trading and orders" />
-class CustomSecurityInitializerAlgorithm(QCAlgorithm):
-
- def initialize(self):
-
- # set our initializer to our custom type
- self.set_brokerage_model(BrokerageName.INTERACTIVE_BROKERS_BROKERAGE)
-
- func_security_seeder = FuncSecuritySeeder(Func[Security, BaseData](self.custom_seed_function))
- self.set_security_initializer(CustomSecurityInitializer(self.brokerage_model, func_security_seeder, DataNormalizationMode.RAW))
-
- self.set_start_date(2013,10,1)
- self.set_end_date(2013,11,1)
-
- self.add_equity("SPY", Resolution.HOUR)
-
- def on_data(self, data):
- if not self.portfolio.invested:
- self.set_holdings("SPY", 1)
-
- def custom_seed_function(self, security):
-
- resolution = Resolution.HOUR
-
- df = self.history(security.symbol, 1, resolution)
- if df.empty:
- return None
-
- last_bar = df.unstack(level=0).iloc[-1]
- date_time = last_bar.name.to_pydatetime()
- open = last_bar.open.values[0]
- high = last_bar.high.values[0]
- low = last_bar.low.values[0]
- close = last_bar.close.values[0]
- volume = last_bar.volume.values[0]
- return TradeBar(date_time, security.symbol, open, high, low, close, volume, Extensions.to_time_span(resolution))
-
-
-class CustomSecurityInitializer(BrokerageModelSecurityInitializer):
- '''Our custom initializer that will set the data normalization mode.
- We sub-class the BrokerageModelSecurityInitializer so we can also
- take advantage of the default model/leverage setting behaviors'''
-
- def __init__(self, brokerage_model, security_seeder, data_normalization_mode):
- '''Initializes a new instance of the CustomSecurityInitializer class with the specified normalization mode
- brokerage_model -- The brokerage model used to get fill/fee/slippage/settlement models
- security_seeder -- The security seeder to be used
- data_normalization_mode -- The desired data normalization mode'''
- self.base = BrokerageModelSecurityInitializer(brokerage_model, security_seeder)
- self.data_normalization_mode = data_normalization_mode
-
- def initialize(self, security):
- '''Initializes the specified security by setting up the models
- security -- The security to be initialized
- seed_security -- True to seed the security, false otherwise'''
- # first call the default implementation
- self.base.initialize(security)
-
- # now apply our data normalization mode
- security.set_data_normalization_mode(self.data_normalization_mode)
diff --git a/fincept-qt/scripts/strategies/CustomSettlementModelRegressionAlgorithm.py b/fincept-qt/scripts/strategies/CustomSettlementModelRegressionAlgorithm.py
deleted file mode 100644
index b066fe745..000000000
--- a/fincept-qt/scripts/strategies/CustomSettlementModelRegressionAlgorithm.py
+++ /dev/null
@@ -1,57 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-3D3166AE
-# Category: Regression Test
-# Description: Regression algorithm to test we can specify a custom settlement model, and override some of its methods
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-from CustomBrokerageModelRegressionAlgorithm import CustomBrokerageModel
-
-### <summary>
-### Regression algorithm to test we can specify a custom settlement model, and override some of its methods
-### </summary>
-class CustomSettlementModelRegressionAlgorithm(QCAlgorithm):
- def initialize(self):
- self.set_start_date(2013,10,7)
- self.set_end_date(2013,10,11)
- self.set_cash(10000)
- self.spy = self.add_equity("SPY", Resolution.DAILY)
- self.set_settlement_model(self.spy)
-
- def set_settlement_model(self, security):
- self.set_brokerage_model(CustomBrokerageModelWithCustomSettlementModel())
-
- def on_data(self, slice):
- if self.portfolio.cash_book[Currencies.USD].amount == 10000:
- parameters = ApplyFundsSettlementModelParameters(self.portfolio, self.spy, self.time, CashAmount(101, Currencies.USD), None)
- self.spy.settlement_model.apply_funds(parameters)
-
- def on_end_of_algorithm(self):
- if self.portfolio.cash_book[Currencies.USD].amount != 10101:
- raise Exception(f"It was expected to have 10101 USD in Portfolio, but was {self.portfolio.cash_book[Currencies.USD].amount}")
- parameters = ScanSettlementModelParameters(self.portfolio, self.spy, datetime(2013, 10, 6))
- self.spy.settlement_model.scan(parameters)
- if self.portfolio.cash_book[Currencies.USD].amount != 10000:
- raise Exception(f"It was expected to have 10000 USD in Portfolio, but was {self.portfolio.cash_book[Currencies.USD].amount}")
-
-class CustomSettlementModel:
- def apply_funds(self, parameters):
- self.currency = parameters.cash_amount.currency
- self.amount = parameters.cash_amount.amount
- parameters.portfolio.cash_book[self.currency].add_amount(self.amount)
-
- def scan(self, parameters):
- if parameters.utc_time == datetime(2013, 10, 6):
- parameters.portfolio.cash_book[self.currency].add_amount(-self.amount)
-
- def get_unsettled_cash(self):
- return None
-
-class CustomBrokerageModelWithCustomSettlementModel(CustomBrokerageModel):
- def get_settlement_model(self, security):
- return CustomSettlementModel()
diff --git a/fincept-qt/scripts/strategies/CustomShortableProviderRegressionAlgorithm.py b/fincept-qt/scripts/strategies/CustomShortableProviderRegressionAlgorithm.py
deleted file mode 100644
index cd68eb5fb..000000000
--- a/fincept-qt/scripts/strategies/CustomShortableProviderRegressionAlgorithm.py
+++ /dev/null
@@ -1,56 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-324DD834
-# Category: Regression Test
-# Description: Regression algorithm asserting we can specify a custom Shortable Provider
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Regression algorithm asserting we can specify a custom Shortable Provider
-### </summary>
-class CustomShortableProviderRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_cash(10000000)
- self.set_start_date(2013,10,4)
- self.set_end_date(2013,10,6)
- self.spy = self.add_security(SecurityType.EQUITY, "SPY", Resolution.DAILY)
- self.spy.set_shortable_provider(CustomShortableProvider())
-
- def on_data(self, data):
- spy_shortable_quantity = self.spy.shortable_provider.shortable_quantity(self.spy.symbol, self.time)
- if spy_shortable_quantity > 1000:
- self.order_id = self.sell("SPY", int(spy_shortable_quantity))
-
- def on_end_of_algorithm(self):
- transactions = self.transactions.orders_count
- if transactions != 1:
- raise Exception("Algorithm should have just 1 order, but was " + str(transactions))
-
- order_quantity = self.transactions.get_order_by_id(self.order_id).quantity
- if order_quantity != -1001:
- raise Exception("Quantity of order " + str(_order_id) + " should be " + str(-1001)+", but was {order_quantity}")
-
- fee_rate = self.spy.shortable_provider.fee_rate(self.spy.symbol, self.time)
- if fee_rate != 0.0025:
- raise Exception(f"Fee rate should be 0.0025, but was {fee_rate}")
- rebate_rate = self.spy.shortable_provider.rebate_rate(self.spy.symbol, self.time)
- if rebate_rate != 0.0507:
- raise Exception(f"Rebate rate should be 0.0507, but was {rebate_rate}")
-
-class CustomShortableProvider(NullShortableProvider):
- def fee_rate(self, symbol: Symbol, local_time: DateTime):
- return 0.0025
- def rebate_rate(self, symbol: Symbol, local_time: DateTime):
- return 0.0507
- def shortable_quantity(self, symbol: Symbol, local_time: DateTime):
- if local_time < datetime(2013,10,4,16,0,0):
- return 10
- else:
- return 1001
diff --git a/fincept-qt/scripts/strategies/CustomUniverseSelectionModelRegressionAlgorithm.py b/fincept-qt/scripts/strategies/CustomUniverseSelectionModelRegressionAlgorithm.py
deleted file mode 100644
index 6e21ec23d..000000000
--- a/fincept-qt/scripts/strategies/CustomUniverseSelectionModelRegressionAlgorithm.py
+++ /dev/null
@@ -1,47 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-CB434E24
-# Category: Universe Selection
-# Description: Regression algorithm showing how to implement a custom universe selection model and asserting it's behavior
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-from Selection.FundamentalUniverseSelectionModel import FundamentalUniverseSelectionModel
-
-### <summary>
-### Regression algorithm showing how to implement a custom universe selection model and asserting it's behavior
-### </summary>
-class CustomUniverseSelectionModelRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2014,3,24)
- self.set_end_date(2014,4,7)
-
- self.universe_settings.resolution = Resolution.DAILY
- self.set_universe_selection(CustomUniverseSelectionModel())
-
- def on_data(self, data):
- '''on_data event is the primary entry point for your algorithm. Each new data point will be pumped in here.
-
- Arguments:
- data: Slice object keyed by symbol containing the stock data
- '''
- if not self.portfolio.invested:
- for kvp in self.active_securities:
- self.set_holdings(kvp.key, 0.1)
-
-class CustomUniverseSelectionModel(FundamentalUniverseSelectionModel):
-
- def __init__(self, universe_settings = None):
- super().__init__(universe_settings)
- self._selected = False
-
- def select(self, algorithm, fundamental):
- if not self._selected:
- self._selected = True
- return [ Symbol.create('AAPL', SecurityType.EQUITY, Market.USA) ]
- return Universe.UNCHANGED
diff --git a/fincept-qt/scripts/strategies/CustomVolatilityModelAlgorithm.py b/fincept-qt/scripts/strategies/CustomVolatilityModelAlgorithm.py
deleted file mode 100644
index 9a0b32618..000000000
--- a/fincept-qt/scripts/strategies/CustomVolatilityModelAlgorithm.py
+++ /dev/null
@@ -1,74 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-57E3FCCE
-# Category: General Strategy
-# Description: Example of custom volatility model
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Example of custom volatility model
-### </summary>
-### <meta name="tag" content="using quantconnect" />
-### <meta name="tag" content="indicators" />
-### <meta name="tag" content="reality modelling" />
-class CustomVolatilityModelAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2013,10,7) #Set Start Date
- self.set_end_date(2015,7,15) #Set End Date
- self.set_cash(100000) #Set Strategy Cash
- # Fincept Terminal Strategy Engine - Symbol Configuration
- self.equity = self.add_equity("SPY", Resolution.DAILY)
- self.equity.set_volatility_model(CustomVolatilityModel(10))
-
-
- def on_data(self, data):
- if not self.portfolio.invested and self.equity.volatility_model.volatility > 0:
- self.set_holdings("SPY", 1)
-
-
-# Python implementation of StandardDeviationOfReturnsVolatilityModel
-# Computes the annualized sample standard deviation of daily returns as the volatility of the security
-# https://github.com/QuantConnect/Lean/blob/master/Common/Securities/Volatility/StandardDeviationOfReturnsVolatilityModel.cs
-class CustomVolatilityModel():
- def __init__(self, periods):
- self.last_update = datetime.min
- self.last_price = 0
- self.needs_update = False
- self.period_span = timedelta(1)
- self.window = RollingWindow[float](periods)
-
- # Volatility is a mandatory attribute
- self.volatility = 0
-
- # Updates this model using the new price information in the specified security instance
- # Update is a mandatory method
- def update(self, security, data):
- time_since_last_update = data.end_time - self.last_update
- if time_since_last_update >= self.period_span and data.price > 0:
- if self.last_price > 0:
- self.window.add(float(data.price / self.last_price) - 1.0)
- self.needs_update = self.window.is_ready
- self.last_update = data.end_time
- self.last_price = data.price
-
- if self.window.count < 2:
- self.volatility = 0
- return
-
- if self.needs_update:
- self.needs_update = False
- std = np.std([ x for x in self.window ])
- self.volatility = std * np.sqrt(252.0)
-
- # Returns history requirements for the volatility model expressed in the form of history request
- # GetHistoryRequirements is a mandatory method
- def get_history_requirements(self, security, utc_time):
- # For simplicity's sake, we will not set a history requirement
- return None
diff --git a/fincept-qt/scripts/strategies/CustomWarmUpPeriodIndicatorAlgorithm.py b/fincept-qt/scripts/strategies/CustomWarmUpPeriodIndicatorAlgorithm.py
deleted file mode 100644
index 5643782a0..000000000
--- a/fincept-qt/scripts/strategies/CustomWarmUpPeriodIndicatorAlgorithm.py
+++ /dev/null
@@ -1,136 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-223472B2
-# Category: Indicators
-# Description: Regression test to check python indicator is keeping backwards compatibility with indicators that do not set WarmUpP...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-from collections import deque
-
-### <summary>
-### Regression test to check python indicator is keeping backwards compatibility
-### with indicators that do not set WarmUpPeriod or do not inherit from PythonIndicator class.
-### </summary>
-### <meta name="tag" content="indicators" />
-### <meta name="tag" content="indicator classes" />
-### <meta name="tag" content="custom indicator" />
-### <meta name="tag" content="regression test" />
-class CustomWarmUpPeriodIndicatorAlgorithm(QCAlgorithm):
- def initialize(self):
- self.set_start_date(2013,10,7)
- self.set_end_date(2013,10,11)
- self.add_equity("SPY", Resolution.SECOND)
-
- # Create three python indicators
- # - custom_not_warm_up does not define WarmUpPeriod parameter
- # - custom_warm_up defines WarmUpPeriod parameter
- # - custom_not_inherit defines WarmUpPeriod parameter but does not inherit from PythonIndicator class
- # - csharp_indicator defines WarmUpPeriod parameter and represents the traditional LEAN C# indicator
- self.custom_not_warm_up = CSMANotWarmUp('custom_not_warm_up', 60)
- self.custom_warm_up = CSMAWithWarmUp('custom_warm_up', 60)
- self.custom_not_inherit = CustomSMA('custom_not_inherit', 60)
- self.csharp_indicator = SimpleMovingAverage('csharp_indicator', 60)
-
- # Register the daily data of "SPY" to automatically update the indicators
- self.register_indicator("SPY", self.custom_warm_up, Resolution.MINUTE)
- self.register_indicator("SPY", self.custom_not_warm_up, Resolution.MINUTE)
- self.register_indicator("SPY", self.custom_not_inherit, Resolution.MINUTE)
- self.register_indicator("SPY", self.csharp_indicator, Resolution.MINUTE)
-
- # Warm up custom_warm_up indicator
- self.warm_up_indicator("SPY", self.custom_warm_up, Resolution.MINUTE)
-
- # Check custom_warm_up indicator has already been warmed up with the requested data
- assert(self.custom_warm_up.is_ready), "custom_warm_up indicator was expected to be ready"
- assert(self.custom_warm_up.samples == 60), "custom_warm_up indicator was expected to have processed 60 datapoints already"
-
- # Try to warm up custom_not_warm_up indicator. It's expected from LEAN to skip the warm up process
- # because this indicator doesn't define WarmUpPeriod parameter
- self.warm_up_indicator("SPY", self.custom_not_warm_up, Resolution.MINUTE)
-
- # Check custom_not_warm_up indicator is not ready and is using the default WarmUpPeriod value
- assert(not self.custom_not_warm_up.is_ready), "custom_not_warm_up indicator wasn't expected to be warmed up"
- assert(self.custom_not_warm_up.warm_up_period == 0), "custom_not_warm_up indicator WarmUpPeriod parameter was expected to be 0"
-
- # Warm up custom_not_inherit indicator. Though it does not inherit from PythonIndicator class,
- # it defines WarmUpPeriod parameter so it's expected to be warmed up from LEAN
- self.warm_up_indicator("SPY", self.custom_not_inherit, Resolution.MINUTE)
-
- # Check custom_not_inherit indicator has already been warmed up with the requested data
- assert(self.custom_not_inherit.is_ready), "custom_not_inherit indicator was expected to be ready"
- assert(self.custom_not_inherit.samples == 60), "custom_not_inherit indicator was expected to have processed 60 datapoints already"
-
- # Warm up csharp_indicator
- self.warm_up_indicator("SPY", self.csharp_indicator, Resolution.MINUTE)
-
- # Check csharp_indicator indicator has already been warmed up with the requested data
- assert(self.csharp_indicator.is_ready), "csharp_indicator indicator was expected to be ready"
- assert(self.csharp_indicator.samples == 60), "csharp_indicator indicator was expected to have processed 60 datapoints already"
-
- def on_data(self, data):
- if not self.portfolio.invested:
- self.set_holdings("SPY", 1)
-
- if self.time.second == 0:
- # Compute the difference between indicators values
- diff = abs(self.custom_not_warm_up.current.value - self.custom_warm_up.current.value)
- diff += abs(self.custom_not_inherit.value - self.custom_not_warm_up.current.value)
- diff += abs(self.custom_not_inherit.value - self.custom_warm_up.current.value)
- diff += abs(self.csharp_indicator.current.value - self.custom_warm_up.current.value)
- diff += abs(self.csharp_indicator.current.value - self.custom_not_warm_up.current.value)
- diff += abs(self.csharp_indicator.current.value - self.custom_not_inherit.value)
-
- # Check custom_not_warm_up indicator is ready when the number of samples is bigger than its WarmUpPeriod parameter
- assert(self.custom_not_warm_up.is_ready == (self.custom_not_warm_up.samples >= 60)), "custom_not_warm_up indicator was expected to be ready when the number of samples were bigger that its WarmUpPeriod parameter"
-
- # Check their values are the same. We only need to check if custom_not_warm_up indicator is ready because the other ones has already been asserted to be ready
- assert(diff <= 1e-10 or (not self.custom_not_warm_up.is_ready)), f"The values of the indicators are not the same. Indicators difference is {diff}"
-
-# Python implementation of SimpleMovingAverage.
-# Represents the traditional simple moving average indicator (SMA) without Warm Up Period parameter defined
-class CSMANotWarmUp(PythonIndicator):
- def __init__(self, name, period):
- super().__init__()
- self.name = name
- self.value = 0
- self.queue = deque(maxlen=period)
-
- # Update method is mandatory
- def update(self, input):
- self.queue.appendleft(input.value)
- count = len(self.queue)
- self.value = np.sum(self.queue) / count
- return count == self.queue.maxlen
-
-# Python implementation of SimpleMovingAverage.
-# Represents the traditional simple moving average indicator (SMA) With Warm Up Period parameter defined
-class CSMAWithWarmUp(CSMANotWarmUp):
- def __init__(self, name, period):
- super().__init__(name, period)
- self.warm_up_period = period
-
-# Custom python implementation of SimpleMovingAverage.
-# Represents the traditional simple moving average indicator (SMA)
-class CustomSMA():
- def __init__(self, name, period):
- self.name = name
- self.value = 0
- self.queue = deque(maxlen=period)
- self.warm_up_period = period
- self.is_ready = False
- self.samples = 0
-
- # Update method is mandatory
- def update(self, input):
- self.samples += 1
- self.queue.appendleft(input.value)
- count = len(self.queue)
- self.value = np.sum(self.queue) / count
- if count == self.queue.maxlen:
- self.is_ready = True
- return self.is_ready
diff --git a/fincept-qt/scripts/strategies/DailyAlgorithm.py b/fincept-qt/scripts/strategies/DailyAlgorithm.py
deleted file mode 100644
index 544ff007d..000000000
--- a/fincept-qt/scripts/strategies/DailyAlgorithm.py
+++ /dev/null
@@ -1,55 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-DCA92403
-# Category: General Strategy
-# Description: Uses daily data and a simple moving average cross to place trades and an ema for stop placement
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Uses daily data and a simple moving average cross to place trades and an ema for stop placement
-### </summary>
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="indicators" />
-### <meta name="tag" content="trading and orders" />
-class DailyAlgorithm(QCAlgorithm):
-
- def initialize(self):
- '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
-
- self.set_start_date(2013,1,1) #Set Start Date
- self.set_end_date(2014,1,1) #Set End Date
- self.set_cash(100000) #Set Strategy Cash
- # Fincept Terminal Strategy Engine - Symbol Configuration
- self.add_equity("SPY", Resolution.DAILY)
- self.add_equity("IBM", Resolution.HOUR).set_leverage(1.0)
- self.macd = self.macd("SPY", 12, 26, 9, MovingAverageType.WILDERS, Resolution.DAILY, Field.CLOSE)
- self.ema = self.ema("IBM", 15 * 6, Resolution.HOUR, Field.SEVEN_BAR)
- self.last_action = None
-
-
- def on_data(self, data):
- '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
-
- Arguments:
- data: Slice object keyed by symbol containing the stock data
- '''
- if not self.macd.is_ready: return
- if not data.contains_key("IBM"): return
- if data["IBM"] is None:
- self.log("Price Missing Time: %s"%str(self.time))
- return
- if self.last_action is not None and self.last_action.date() == self.time.date(): return
-
- self.last_action = self.time
- quantity = self.portfolio["SPY"].quantity
-
- if quantity <= 0 and self.macd.current.value > self.macd.signal.current.value and data["IBM"].price > self.ema.current.value:
- self.set_holdings("IBM", 0.25)
- elif quantity >= 0 and self.macd.current.value < self.macd.signal.current.value and data["IBM"].price < self.ema.current.value:
- self.set_holdings("IBM", -0.25)
diff --git a/fincept-qt/scripts/strategies/DataConsolidationAlgorithm.py b/fincept-qt/scripts/strategies/DataConsolidationAlgorithm.py
deleted file mode 100644
index 446efa0fe..000000000
--- a/fincept-qt/scripts/strategies/DataConsolidationAlgorithm.py
+++ /dev/null
@@ -1,178 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-5DD0A982
-# Category: Data Consolidation
-# Description: Example algorithm giving an introduction into using IDataConsolidators. This is an advanced QC concept and requires a...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Example algorithm giving an introduction into using IDataConsolidators.
-### This is an advanced QC concept and requires a certain level of comfort using C# and its event system.
-###
-### What is an IDataConsolidator?
-### IDataConsolidator is a plugin point that can be used to transform your data more easily.
-### In this example we show one of the simplest consolidators, the TradeBarConsolidator.
-### This type is capable of taking a timespan to indicate how long each bar should be, or an
-### integer to indicate how many bars should be aggregated into one.
-###
-### When a new 'consolidated' piece of data is produced by the IDataConsolidator, an event is fired
-### with the argument of the new data.
-### </summary>
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="consolidating data" />
-class DataConsolidationAlgorithm(QCAlgorithm):
-
- def initialize(self):
- '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
-
- self.set_start_date(DateTime(2013, 10, 7, 9, 30, 0)) #Set Start Date
- self.set_end_date(self.start_date + timedelta(60)) #Set End Date
- # Fincept Terminal Strategy Engine - Symbol Configuration
- self.add_equity("SPY")
- self.add_forex("EURUSD", Resolution.HOUR)
-
- # define our 30 minute trade bar consolidator. we can
- # access the 30 minute bar from the DataConsolidated events
- thirty_minute_consolidator = TradeBarConsolidator(timedelta(minutes=30))
-
- # attach our event handler. the event handler is a function that will
- # be called each time we produce a new consolidated piece of data.
- thirty_minute_consolidator.data_consolidated += self.thirty_minute_bar_handler
-
- # this call adds our 30 minute consolidator to
- # the manager to receive updates from the engine
- self.subscription_manager.add_consolidator("SPY", thirty_minute_consolidator)
-
- # here we'll define a slightly more complex consolidator. what we're trying to produce is
- # a 3 day bar. Now we could just use a single TradeBarConsolidator like above and pass in
- # TimeSpan.from_days(3), but in reality that's not what we want. For time spans of longer than
- # a day we'll get incorrect results around weekends and such. What we really want are tradeable
- # days. So we'll create a daily consolidator, and then wrap it with a 3 count consolidator.
-
- # first define a one day trade bar -- this produces a consolidated piece of data after a day has passed
- one_day_consolidator = TradeBarConsolidator(timedelta(1))
-
- # next define our 3 count trade bar -- this produces a consolidated piece of data after it sees 3 pieces of data
- three_count_consolidator = TradeBarConsolidator(3)
-
- # here we combine them to make a new, 3 day trade bar. The SequentialConsolidator allows composition of
- # consolidators. It takes the consolidated output of one consolidator (in this case, the one_day_consolidator)
- # and pipes it through to the three_count_consolidator. His output will be a 3 day bar.
- three_one_day_bar = SequentialConsolidator(one_day_consolidator, three_count_consolidator)
-
- # attach our handler
- three_one_day_bar.data_consolidated += self.three_day_bar_consolidated_handler
-
- # this call adds our 3 day to the manager to receive updates from the engine
- self.subscription_manager.add_consolidator("SPY", three_one_day_bar)
-
- # Custom monthly consolidator
- custom_monthly_consolidator = TradeBarConsolidator(self.custom_monthly)
- custom_monthly_consolidator.data_consolidated += self.custom_monthly_handler
- self.subscription_manager.add_consolidator("SPY", custom_monthly_consolidator)
-
- # API convenience method for easily receiving consolidated data
- self.consolidate("SPY", timedelta(minutes=45), self.forty_five_minute_bar_handler)
- self.consolidate("SPY", Resolution.HOUR, self.hour_bar_handler)
- self.consolidate("EURUSD", Resolution.DAILY, self.daily_eur_usd_bar_handler)
-
- # API convenience method for easily receiving weekly-consolidated data
- self.consolidate("SPY", Calendar.WEEKLY, self.calendar_trade_bar_handler)
- self.consolidate("EURUSD", Calendar.WEEKLY, self.calendar_quote_bar_handler)
-
- # API convenience method for easily receiving monthly-consolidated data
- self.consolidate("SPY", Calendar.MONTHLY, self.calendar_trade_bar_handler)
- self.consolidate("EURUSD", Calendar.MONTHLY, self.calendar_quote_bar_handler)
-
- # API convenience method for easily receiving quarterly-consolidated data
- self.consolidate("SPY", Calendar.QUARTERLY, self.calendar_trade_bar_handler)
- self.consolidate("EURUSD", Calendar.QUARTERLY, self.calendar_quote_bar_handler)
-
- # API convenience method for easily receiving yearly-consolidated data
- self.consolidate("SPY", Calendar.YEARLY, self.calendar_trade_bar_handler)
- self.consolidate("EURUSD", Calendar.YEARLY, self.calendar_quote_bar_handler)
-
- # some securities may have trade and quote data available, so we can choose it based on TickType:
- #self.consolidate("BTCUSD", Resolution.HOUR, TickType.TRADE, self.hour_bar_handler) # to get TradeBar
- #self.consolidate("BTCUSD", Resolution.HOUR, TickType.QUOTE, self.hour_bar_handler) # to get QuoteBar (default)
-
- self.consolidated_hour = False
- self.consolidated45_minute = False
- self.__last = None
-
- def on_data(self, data):
- '''We need to declare this method'''
- pass
-
-
- def on_end_of_day(self):
- # close up shop each day and reset our 'last' value so we start tomorrow fresh
- self.liquidate("SPY")
- self.__last = None
-
- def thirty_minute_bar_handler(self, sender, consolidated):
- '''This is our event handler for our 30 minute trade bar defined above in Initialize(). So each time the
- consolidator produces a new 30 minute bar, this function will be called automatically. The 'sender' parameter
- will be the instance of the IDataConsolidator that invoked the event, but you'll almost never need that!'''
-
- if self.__last is not None and consolidated.close > self.__last.close:
- self.log(f"{consolidated.time} >> SPY >> LONG >> 100 >> {self.portfolio['SPY'].quantity}")
- self.order("SPY", 100)
-
- elif self.__last is not None and consolidated.close < self.__last.close:
- self.log(f"{consolidated.time} >> SPY >> SHORT >> 100 >> {self.portfolio['SPY'].quantity}")
- self.order("SPY", -100)
-
- self.__last = consolidated
-
-
- def three_day_bar_consolidated_handler(self, sender, consolidated):
- ''' This is our event handler for our 3 day trade bar defined above in Initialize(). So each time the
- consolidator produces a new 3 day bar, this function will be called automatically. The 'sender' parameter
- will be the instance of the IDataConsolidator that invoked the event, but you'll almost never need that!'''
- self.log(f"{consolidated.time} >> Plotting!")
- self.plot(consolidated.symbol.value, "3HourBar", consolidated.close)
-
- def forty_five_minute_bar_handler(self, consolidated):
- ''' This is our event handler for our 45 minute consolidated defined using the Consolidate method'''
- self.consolidated45_minute = True
- self.log(f"{consolidated.end_time} >> FortyFiveMinuteBarHandler >> {consolidated.close}")
-
- def hour_bar_handler(self, consolidated):
- '''This is our event handler for our one hour consolidated defined using the Consolidate method'''
- self.consolidated_hour = True
- self.log(f"{consolidated.end_time} >> FortyFiveMinuteBarHandler >> {consolidated.close}")
-
- def daily_eur_usd_bar_handler(self, consolidated):
- '''This is our event handler for our daily consolidated defined using the Consolidate method'''
- self.log(f"{consolidated.end_time} EURUSD Daily consolidated.")
-
- def calendar_trade_bar_handler(self, trade_bar):
- self.log(f'{self.time} :: {trade_bar.time} {trade_bar.close}')
-
- def calendar_quote_bar_handler(self, quote_bar):
- self.log(f'{self.time} :: {quote_bar.time} {quote_bar.close}')
-
- def custom_monthly(self, dt):
- '''Custom Monthly Func'''
- start = dt.replace(day=1).date()
- end = dt.replace(day=28) + timedelta(4)
- end = (end - timedelta(end.day-1)).date()
- return CalendarInfo(start, end - start)
-
- def custom_monthly_handler(self, sender, consolidated):
- '''This is our event handler Custom Monthly function'''
- self.log(f"{consolidated.time} >> CustomMonthlyHandler >> {consolidated.close}")
-
- def on_end_of_algorithm(self):
- if not self.consolidated_hour:
- raise Exception("Expected hourly consolidator to be fired.")
-
- if not self.consolidated45_minute:
- raise Exception("Expected 45-minute consolidator to be fired.")
diff --git a/fincept-qt/scripts/strategies/DelistingEventsAlgorithm.py b/fincept-qt/scripts/strategies/DelistingEventsAlgorithm.py
deleted file mode 100644
index 437336071..000000000
--- a/fincept-qt/scripts/strategies/DelistingEventsAlgorithm.py
+++ /dev/null
@@ -1,77 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-2D323EF8
-# Category: Corporate Actions
-# Description: Demonstration of using the Delisting event in your algorithm. Assets are delisted on their last day of trading, or wh...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Demonstration of using the Delisting event in your algorithm. Assets are delisted on their last day of trading, or when their contract expires.
-### This data is not included in the open source project.
-### </summary>
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="data event handlers" />
-### <meta name="tag" content="delisting event" />
-class DelistingEventsAlgorithm(QCAlgorithm):
-
- def initialize(self):
- '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
-
- self.set_start_date(2007, 5, 15) #Set Start Date
- self.set_end_date(2007, 5, 25) #Set End Date
- self.set_cash(100000) #Set Strategy Cash
- # Fincept Terminal Strategy Engine - Symbol Configuration
- self.add_equity("AAA.1", Resolution.DAILY)
- self.add_equity("SPY", Resolution.DAILY)
-
-
- def on_data(self, data):
- '''on_data event is the primary entry point for your algorithm. Each new data point will be pumped in here.
-
- Arguments:
- data: Slice object keyed by symbol containing the stock data
- '''
- if self.transactions.orders_count == 0:
- self.set_holdings("AAA.1", 1)
- self.debug("Purchased stock")
-
- for kvp in data.bars:
- symbol = kvp.key
- value = kvp.value
-
- self.log("OnData(Slice): {0}: {1}: {2}".format(self.time, symbol, value.close))
-
- # the slice can also contain delisting data: data.delistings in a dictionary string->Delisting
-
- aaa = self.securities["AAA.1"]
- if aaa.is_delisted and aaa.is_tradable:
- raise Exception("Delisted security must NOT be tradable")
-
- if not aaa.is_delisted and not aaa.is_tradable:
- raise Exception("Securities must be marked as tradable until they're delisted or removed from the universe")
-
- for kvp in data.delistings:
- symbol = kvp.key
- value = kvp.value
-
- if value.type == DelistingType.WARNING:
- self.log("OnData(Delistings): {0}: {1} will be delisted at end of day today.".format(self.time, symbol))
-
- # liquidate on delisting warning
- self.set_holdings(symbol, 0)
-
- if value.type == DelistingType.DELISTED:
- self.log("OnData(Delistings): {0}: {1} has been delisted.".format(self.time, symbol))
-
- # fails because the security has already been delisted and is no longer tradable
- self.set_holdings(symbol, 1)
-
-
- def on_order_event(self, order_event):
- self.log("OnOrderEvent(OrderEvent): {0}: {1}".format(self.time, order_event))
diff --git a/fincept-qt/scripts/strategies/DescendingCustomDataObjectStoreRegressionAlgorithm.py b/fincept-qt/scripts/strategies/DescendingCustomDataObjectStoreRegressionAlgorithm.py
deleted file mode 100644
index 24be89a85..000000000
--- a/fincept-qt/scripts/strategies/DescendingCustomDataObjectStoreRegressionAlgorithm.py
+++ /dev/null
@@ -1,108 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-6513B96C
-# Category: Regression Test
-# Description: The regression algorithm showcases the utilization of a custom data source with the Sort flag set to true. This means...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-
-### <summary>
-### The regression algorithm showcases the utilization of a custom data source with the Sort flag set to true.
-### This means that the source initially provides data in descending order, which is then organized into ascending order and returned in the 'on_data' function.
-### </summary>
-class DescendingCustomDataObjectStoreRegressionAlgorithm(QCAlgorithm):
- descending_custom_data = [
- "2024-10-03 19:00:00,173.5,176.0,172.0,175.2,120195681,4882.29",
- "2024-10-02 18:00:00,174.0,177.0,173.0,175.8,116275729,4641.97",
- "2024-10-01 17:00:00,175.0,178.0,172.5,174.5,127707078,6591.27",
- "2024-09-30 11:00:00,174.8,176.5,172.8,175.0,127707078,6591.27",
- "2024-09-27 10:00:00,172.5,175.0,171.5,173.5,120195681,4882.29",
- "2024-09-26 09:00:00,171.0,172.5,170.0,171.8,117516350,4820.53",
- "2024-09-25 08:00:00,169.5,172.0,169.0,171.0,110427867,4661.55",
- "2024-09-24 07:00:00,170.0,171.0,168.0,169.5,127624733,4823.52",
- "2024-09-23 06:00:00,172.0,173.5,169.5,171.5,123586417,4303.93",
- "2024-09-20 05:00:00,168.0,171.0,167.5,170.5,151929179,5429.87",
- "2024-09-19 04:00:00,170.5,171.5,166.0,167.0,160523863,5219.24",
- "2024-09-18 03:00:00,173.0,174.0,169.0,172.0,145721790,5163.09",
- "2024-09-17 02:00:00,171.0,173.5,170.0,172.5,144794030,5405.72",
- "2024-09-16 01:00:00,168.0,171.0,167.0,170.0,214402430,8753.33",
- "2024-09-13 16:00:00,173.5,176.0,172.0,175.2,120195681,4882.29",
- "2024-09-12 15:00:00,174.5,177.5,173.5,176.5,171728134,7774.83",
- "2024-09-11 14:00:00,175.0,178.0,174.0,175.5,191516153,8349.59",
- "2024-09-10 13:00:00,174.5,176.0,173.0,174.0,151162819,5915.8",
- "2024-09-09 12:00:00,176.0,178.0,175.0,177.0,116275729,4641.97"
- ]
-
- def initialize(self):
- self.set_start_date(2024, 9, 9)
- self.set_end_date(2024, 10, 3)
- self.set_cash(100000)
-
- self.set_benchmark(lambda x: 0)
-
- SortCustomData.custom_data_key = self.get_custom_data_key()
-
- self.custom_symbol = self.add_data(SortCustomData, "SortCustomData", Resolution.DAILY).symbol
-
- # Saving data here for demonstration and regression testing purposes.
- # In real scenarios, data has to be saved to the object store before the algorithm starts.
- self.object_store.save(self.get_custom_data_key(), "\n".join(self.descending_custom_data))
-
- self.received_data = []
-
- def on_data(self, slice: Slice):
- if slice.contains_key(self.custom_symbol):
- custom_data = slice.get(SortCustomData, self.custom_symbol)
- if custom_data.open == 0 or custom_data.high == 0 or custom_data.low == 0 or custom_data.close == 0 or custom_data.price == 0:
- raise Exception("One or more custom data fields (open, high, low, close, price) are zero.")
-
- self.received_data.append(custom_data)
-
- def on_end_of_algorithm(self):
- if not self.received_data:
- raise Exception("Custom data was not fetched")
-
- # Make sure history requests work as expected
- history = self.history(SortCustomData, self.custom_symbol, self.start_date, self.end_date, Resolution.DAILY)
-
- if history.shape[0] != len(self.received_data):
- raise Exception("History request returned more or less data than expected")
-
- # Iterate through the history collection, checking if the time is in ascending order.
- for i in range(len(history) - 1):
- # [1] - time
- if history.index[i][1] > history.index[i + 1][1]:
- raise RegressionTestException(
- f"Order failure: {history.index[i][1]} > {history.index[i + 1][1]} at index {i}.")
-
- def get_custom_data_key(self):
- return "CustomData/SortCustomData"
-
-
-class SortCustomData(PythonData):
- custom_data_key = ""
-
- def get_source(self, config, date, is_live):
- subscription = SubscriptionDataSource(self.custom_data_key, SubscriptionTransportMedium.OBJECT_STORE,
- FileFormat.CSV)
- # Indicate that the data from the subscription will be returned in descending order.
- subscription.Sort = True
- return subscription
-
- def reader(self, config, line, date, is_live):
- data = line.split(',')
- obj_data = SortCustomData()
- obj_data.symbol = config.symbol
- obj_data.time = datetime.strptime(data[0], '%Y-%m-%d %H:%M:%S')
- obj_data.value = float(data[4])
- obj_data["Open"] = float(data[1])
- obj_data["High"] = float(data[2])
- obj_data["Low"] = float(data[3])
- obj_data["Close"] = float(data[4])
- return obj_data
diff --git a/fincept-qt/scripts/strategies/DisplacedMovingAverageRibbon.py b/fincept-qt/scripts/strategies/DisplacedMovingAverageRibbon.py
deleted file mode 100644
index afa4e1167..000000000
--- a/fincept-qt/scripts/strategies/DisplacedMovingAverageRibbon.py
+++ /dev/null
@@ -1,93 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-E476428A
-# Category: General Strategy
-# Description: Constructs a displaced moving average ribbon and buys when all are lined up, liquidates when they all line down Ribbo...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Constructs a displaced moving average ribbon and buys when all are lined up, liquidates when they all line down
-### Ribbons are great for visualizing trends
-### Signals are generated when they all line up in a paricular direction
-### A buy signal is when the values of the indicators are increasing (from slowest to fastest).
-### A sell signal is when the values of the indicators are decreasing (from slowest to fastest).
-### </summary>
-### <meta name="tag" content="charting" />
-### <meta name="tag" content="plotting indicators" />
-### <meta name="tag" content="indicators" />
-### <meta name="tag" content="indicator classes" />
-class DisplacedMovingAverageRibbon(QCAlgorithm):
-
- # Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
- def initialize(self):
- self.set_start_date(2009, 1, 1) #Set Start Date
- self.set_end_date(2015, 1, 1) #Set End Date
- self.spy = self.add_equity("SPY", Resolution.DAILY).symbol
- count = 6
- offset = 5
- period = 15
- self.ribbon = []
- # define our sma as the base of the ribbon
- self.sma = SimpleMovingAverage(period)
-
- for x in range(count):
- # define our offset to the zero sma, these various offsets will create our 'displaced' ribbon
- delay = Delay(offset*(x+1))
- # define an indicator that takes the output of the sma and pipes it into our delay indicator
- delayed_sma = IndicatorExtensions.of(delay, self.sma)
- # register our new 'delayed_sma' for automatic updates on a daily resolution
- self.register_indicator(self.spy, delayed_sma, Resolution.DAILY)
- self.ribbon.append(delayed_sma)
- self.previous = datetime.min
- # plot indicators each time they update using the PlotIndicator function
- for i in self.ribbon:
- self.plot_indicator("Ribbon", i)
-
- # on_data event is the primary entry point for your algorithm. Each new data point will be pumped in here.
- def on_data(self, data):
-
- if data[self.spy] is None: return
- # wait for our entire ribbon to be ready
- if not all(x.is_ready for x in self.ribbon): return
- # only once per day
- if self.previous.date() == self.time.date(): return
- self.plot("Ribbon", "Price", data[self.spy].price)
-
- # check for a buy signal
- values = [x.current.value for x in self.ribbon]
- holding = self.portfolio[self.spy]
- if (holding.quantity <= 0 and self.is_ascending(values)):
- self.set_holdings(self.spy, 1.0)
- elif (holding.quantity > 0 and self.is_descending(values)):
- self.liquidate(self.spy)
- self.previous = self.time
-
- # Returns true if the specified values are in ascending order
- def is_ascending(self, values):
- last = None
- for val in values:
- if last is None:
- last = val
- continue
- if last < val:
- return False
- last = val
- return True
-
- # Returns true if the specified values are in Descending order
- def is_descending(self, values):
- last = None
- for val in values:
- if last is None:
- last = val
- continue
- if last > val:
- return False
- last = val
- return True
diff --git a/fincept-qt/scripts/strategies/DividendAlgorithm.py b/fincept-qt/scripts/strategies/DividendAlgorithm.py
deleted file mode 100644
index 5fecc244f..000000000
--- a/fincept-qt/scripts/strategies/DividendAlgorithm.py
+++ /dev/null
@@ -1,60 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-3A64A758
-# Category: Corporate Actions
-# Description: Demonstration of payments for cash dividends in backtesting. When data normalization mode is set to "Raw" the dividen...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Demonstration of payments for cash dividends in backtesting. When data normalization mode is set
-### to "Raw" the dividends are paid as cash directly into your portfolio.
-### </summary>
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="data event handlers" />
-### <meta name="tag" content="dividend event" />
-class DividendAlgorithm(QCAlgorithm):
-
- def initialize(self):
- '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
- self.set_start_date(1998,1,1) #Set Start Date
- self.set_end_date(2006,1,21) #Set End Date
- self.set_cash(100000) #Set Strategy Cash
- # Fincept Terminal Strategy Engine - Symbol Configuration
- equity = self.add_equity("MSFT", Resolution.DAILY)
- equity.set_data_normalization_mode(DataNormalizationMode.RAW)
-
- # this will use the Tradier Brokerage open order split behavior
- # forward split will modify open order to maintain order value
- # reverse split open orders will be cancelled
- self.set_brokerage_model(BrokerageName.TRADIER_BROKERAGE)
-
-
- def on_data(self, data):
- '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.'''
- bar = data["MSFT"]
- if self.transactions.orders_count == 0:
- self.set_holdings("MSFT", .5)
- # place some orders that won't fill, when the split comes in they'll get modified to reflect the split
- quantity = self.calculate_order_quantity("MSFT", .25)
- self.debug(f"Purchased Stock: {bar.price}")
- self.stop_market_order("MSFT", -quantity, bar.low/2)
- self.limit_order("MSFT", -quantity, bar.high*2)
-
- if data.dividends.contains_key("MSFT"):
- dividend = data.dividends["MSFT"]
- self.log(f"{self.time} >> DIVIDEND >> {dividend.symbol} - {dividend.distribution} - {self.portfolio.cash} - {self.portfolio['MSFT'].price}")
-
- if data.splits.contains_key("MSFT"):
- split = data.splits["MSFT"]
- self.log(f"{self.time} >> SPLIT >> {split.symbol} - {split.split_factor} - {self.portfolio.cash} - {self.portfolio['MSFT'].price}")
-
- def on_order_event(self, order_event):
- # orders get adjusted based on split events to maintain order value
- order = self.transactions.get_order_by_id(order_event.order_id)
- self.log(f"{self.time} >> ORDER >> {order}")
diff --git a/fincept-qt/scripts/strategies/DropboxBaseDataUniverseSelectionAlgorithm.py b/fincept-qt/scripts/strategies/DropboxBaseDataUniverseSelectionAlgorithm.py
deleted file mode 100644
index b15c8e07e..000000000
--- a/fincept-qt/scripts/strategies/DropboxBaseDataUniverseSelectionAlgorithm.py
+++ /dev/null
@@ -1,92 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-FFA7AD77
-# Category: Universe Selection
-# Description: In this algorithm we show how you can easily use the universe selection feature to fetch symbols to be traded using t...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-from System.Collections.Generic import List
-
-### <summary>
-### In this algorithm we show how you can easily use the universe selection feature to fetch symbols
-### to be traded using the BaseData custom data system in combination with the AddUniverse{T} method.
-### AddUniverse{T} requires a function that will return the symbols to be traded.
-### </summary>
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="universes" />
-### <meta name="tag" content="custom universes" />
-class DropboxBaseDataUniverseSelectionAlgorithm(QCAlgorithm):
-
- def initialize(self):
-
- self.universe_settings.resolution = Resolution.DAILY
-
- # Order margin value has to have a minimum of 0.5% of Portfolio value, allows filtering out small trades and reduce fees.
- # Commented so regression algorithm is more sensitive
- #self.settings.minimum_order_margin_portfolio_percentage = 0.005
-
- self.set_start_date(2017, 7, 6)
- self.set_end_date(2018, 7, 4)
-
- universe = self.add_universe(StockDataSource, self.stock_data_source)
-
- historical_selection_data = self.history(universe, 3)
- if len(historical_selection_data) != 3:
- raise ValueError(f"Unexpected universe data count {len(historical_selection_data)}")
-
- for universe_data in historical_selection_data["symbols"]:
- if len(universe_data) != 5:
- raise ValueError(f"Unexpected universe data receieved")
-
- def stock_data_source(self, data):
- list = []
- for item in data:
- for symbol in item["Symbols"]:
- list.append(symbol)
- return list
-
- def on_data(self, slice):
-
- if slice.bars.count == 0: return
- if self._changes is None: return
-
- # start fresh
- self.liquidate()
-
- percentage = 1 / slice.bars.count
- for trade_bar in slice.bars.values():
- self.set_holdings(trade_bar.symbol, percentage)
-
- # reset changes
- self._changes = None
-
- def on_securities_changed(self, changes):
- self._changes = changes
-
-class StockDataSource(PythonData):
-
- def get_source(self, config, date, is_live_mode):
- url = "https://www.dropbox.com/s/2l73mu97gcehmh7/daily-stock-picker-live.csv?dl=1" if is_live_mode else \
- "https://www.dropbox.com/s/ae1couew5ir3z9y/daily-stock-picker-backtest.csv?dl=1"
-
- return SubscriptionDataSource(url, SubscriptionTransportMedium.REMOTE_FILE)
-
- def reader(self, config, line, date, is_live_mode):
- if not (line.strip() and line[0].isdigit()): return None
-
- stocks = StockDataSource()
- stocks.symbol = config.symbol
-
- csv = line.split(',')
- if is_live_mode:
- stocks.time = date
- stocks["Symbols"] = csv
- else:
- stocks.time = datetime.strptime(csv[0], "%Y%m%d")
- stocks["Symbols"] = csv[1:]
- return stocks
diff --git a/fincept-qt/scripts/strategies/DropboxCoarseFineAlgorithm.py b/fincept-qt/scripts/strategies/DropboxCoarseFineAlgorithm.py
deleted file mode 100644
index 110f0873b..000000000
--- a/fincept-qt/scripts/strategies/DropboxCoarseFineAlgorithm.py
+++ /dev/null
@@ -1,90 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-43A9D681
-# Category: General Strategy
-# Description: In this algorithm, we fetch a list of tickers with corresponding dates from a file on Dropbox. We then create a fine ...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### In this algorithm, we fetch a list of tickers with corresponding dates from a file on Dropbox.
-### We then create a fine fundamental universe which contains those symbols on their respective dates.###
-### </summary>
-### <meta name="tag" content="download" />
-### <meta name="tag" content="universes" />
-### <meta name="tag" content="custom data" />
-class DropboxCoarseFineAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2019, 9, 23) # Set Start Date
- self.set_end_date(2019, 9, 30) # Set End Date
- self.set_cash(100000) # Set Strategy Cash
- self.add_universe(self.select_coarse, self.select_fine)
-
- self.universe_data = None
- self.next_update = datetime(1, 1, 1) # Minimum datetime
- self.url = "https://www.dropbox.com/s/x2sb9gaiicc6hm3/tickers_with_dates.csv?dl=1"
-
- def on_end_of_day(self):
- for security in self.active_securities.values:
- self.debug(f"{self.time.date()} {security.symbol.value} with Market Cap: ${security.fundamentals.market_cap}")
-
- def select_coarse(self, coarse):
- return self.get_symbols()
-
- def select_fine(self, fine):
- symbols = self.get_symbols()
-
- # Return symbols from our list which have a market capitalization of at least 10B
- return [f.symbol for f in fine if f.market_cap > 1e10 and f.symbol in symbols]
-
- def get_symbols(self):
-
- # In live trading update every 12 hours
- if self.live_mode:
- if self.time < self.next_update:
- # Return today's row
- return self.universe_data[self.time.date()]
- # When updating set the new reset time.
- self.next_update = self.time + timedelta(hours=12)
- self.universe_data = self.parse(self.url)
-
- # In backtest load once if not set, then just use the dates.
- if self.universe_data is None:
- self.universe_data = self.parse(self.url)
-
- # Check if contains the row we need
- if self.time.date() not in self.universe_data:
- return Universe.unchanged
-
- return self.universe_data[self.time.date()]
-
-
- def parse(self, url):
- # Download file from url as string
- file = self.download(url).split("\n")
-
- # # Remove formatting characters
- data = [x.replace("\r", "").replace(" ", "") for x in file]
-
- # # Split data by date and symbol
- split_data = [x.split(",") for x in data]
-
- # Dictionary to hold list of active symbols for each date, keyed by date
- symbols_by_date = {}
-
- # Parse data into dictionary
- for arr in split_data:
- date = datetime.strptime(arr[0], "%Y%m%d").date()
- symbols = [Symbol.create(ticker, SecurityType.EQUITY, Market.USA) for ticker in arr[1:]]
- symbols_by_date[date] = symbols
-
- return symbols_by_date
-
- def on_securities_changed(self, changes):
- self.log(f"Added Securities: {[security.symbol.value for security in changes.added_securities]}")
diff --git a/fincept-qt/scripts/strategies/DropboxUniverseSelectionAlgorithm.py b/fincept-qt/scripts/strategies/DropboxUniverseSelectionAlgorithm.py
deleted file mode 100644
index f7a746fd3..000000000
--- a/fincept-qt/scripts/strategies/DropboxUniverseSelectionAlgorithm.py
+++ /dev/null
@@ -1,83 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-C02B7DE9
-# Category: Universe Selection
-# Description: In this algorithm we show how you can easily use the universe selection feature to fetch symbols to be traded using t...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-import base64
-
-### <summary>
-### In this algorithm we show how you can easily use the universe selection feature to fetch symbols
-### to be traded using the BaseData custom data system in combination with the AddUniverse{T} method.
-### AddUniverse{T} requires a function that will return the symbols to be traded.
-### </summary>
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="universes" />
-### <meta name="tag" content="custom universes" />
-class DropboxUniverseSelectionAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2017, 7, 4)
- self.set_end_date(2018, 7, 4)
-
- self.backtest_symbols_per_day = {}
- self.current_universe = []
-
- self.universe_settings.resolution = Resolution.DAILY
-
- # Order margin value has to have a minimum of 0.5% of Portfolio value, allows filtering out small trades and reduce fees.
- # Commented so regression algorithm is more sensitive
- #self.settings.minimum_order_margin_portfolio_percentage = 0.005
-
- self.add_universe("my-dropbox-universe", self.selector)
-
- def selector(self, date):
- # handle live mode file format
- if self.live_mode:
- # fetch the file from dropbox
- str = self.download("https://www.dropbox.com/s/2l73mu97gcehmh7/daily-stock-picker-live.csv?dl=1")
- # if we have a file for today, return symbols, else leave universe unchanged
- self.current_universe = str.split(',') if len(str) > 0 else self.current_universe
- return self.current_universe
-
- # backtest - first cache the entire file
- if len(self.backtest_symbols_per_day) == 0:
-
- # No need for headers for authorization with dropbox, these two lines are for example purposes
- byte_key = base64.b64encode("UserName:Password".encode('ASCII'))
- # The headers must be passed to the Download method as dictionary
- headers = { 'Authorization' : f'Basic ({byte_key.decode("ASCII")})' }
-
- str = self.download("https://www.dropbox.com/s/ae1couew5ir3z9y/daily-stock-picker-backtest.csv?dl=1", headers)
- for line in str.splitlines():
- data = line.split(',')
- self.backtest_symbols_per_day[data[0]] = data[1:]
-
- index = date.strftime("%Y%m%d")
- self.current_universe = self.backtest_symbols_per_day.get(index, self.current_universe)
-
- return self.current_universe
-
- def on_data(self, slice):
-
- if slice.bars.count == 0: return
- if self.changes is None: return
-
- # start fresh
- self.liquidate()
-
- percentage = 1 / slice.bars.count
- for trade_bar in slice.bars.values():
- self.set_holdings(trade_bar.symbol, percentage)
-
- # reset changes
- self.changes = None
-
- def on_securities_changed(self, changes):
- self.changes = changes
diff --git a/fincept-qt/scripts/strategies/DynamicSecurityDataRegressionAlgorithm.py b/fincept-qt/scripts/strategies/DynamicSecurityDataRegressionAlgorithm.py
deleted file mode 100644
index 991405704..000000000
--- a/fincept-qt/scripts/strategies/DynamicSecurityDataRegressionAlgorithm.py
+++ /dev/null
@@ -1,65 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-D86D36A8
-# Category: Regression Test
-# Description: Provides an example algorithm showcasing the Security.data features
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-from System.Collections.Generic import List
-from QuantConnect.Data.Custom.IconicTypes import *
-
-### <summary>
-### Provides an example algorithm showcasing the Security.data features
-### </summary>
-class DynamicSecurityDataRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2015, 10, 22)
- self.set_end_date(2015, 10, 30)
-
- self.ticker = "GOOGL"
- self.equity = self.add_equity(self.ticker, Resolution.DAILY)
-
- custom_linked_equity = self.add_data(LinkedData, self.ticker, Resolution.DAILY)
-
- first_linked_data = LinkedData()
- first_linked_data.count = 100
- first_linked_data.symbol = custom_linked_equity.symbol
- first_linked_data.end_time = self.start_date
-
- second_linked_data = LinkedData()
- second_linked_data.count = 100
- second_linked_data.symbol = custom_linked_equity.symbol
- second_linked_data.end_time = self.start_date
-
- # Adding linked data manually to cache for example purposes, since
- # LinkedData is a type used for testing and doesn't point to any real data.
- custom_linked_equity_type = list(custom_linked_equity.subscriptions)[0].type
- custom_linked_data = List[LinkedData]()
- custom_linked_data.add(first_linked_data)
- custom_linked_data.add(second_linked_data)
- self.equity.cache.add_data_list(custom_linked_data, custom_linked_equity_type, False)
-
- def on_data(self, data):
- # The Security object's Data property provides convenient access
- # to the various types of data related to that security. You can
- # access not only the security's price data, but also any custom
- # data that is mapped to the security, such as our SEC reports.
-
- # 1. Get the most recent data point of a particular type:
- # 1.a Using the generic method, Get(T): => T
- custom_linked_data = self.equity.data.get(LinkedData)
- self.log("{}: LinkedData: {}".format(self.time, str(custom_linked_data)))
-
- # 2. Get the list of data points of a particular type for the most recent time step:
- # 2.a Using the generic method, GetAll(T): => IReadOnlyList<T>
- custom_linked_data_list = self.equity.data.get_all(LinkedData)
- self.log("{}: LinkedData: {}".format(self.time, len(custom_linked_data_list)))
-
- if not self.portfolio.invested:
- self.buy(self.equity.symbol, 10)
diff --git a/fincept-qt/scripts/strategies/ETFConstituentUniverseCompositeDelistingRegressionAlgorithm.py b/fincept-qt/scripts/strategies/ETFConstituentUniverseCompositeDelistingRegressionAlgorithm.py
deleted file mode 100644
index 5085fe921..000000000
--- a/fincept-qt/scripts/strategies/ETFConstituentUniverseCompositeDelistingRegressionAlgorithm.py
+++ /dev/null
@@ -1,79 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-2A9A1A33
-# Category: ETF
-# Description: Tests the delisting of the composite Symbol (ETF symbol) and the removal of the universe and the symbol from the algo...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Tests the delisting of the composite Symbol (ETF symbol) and the removal of
-### the universe and the symbol from the algorithm.
-### </summary>
-class ETFConstituentUniverseCompositeDelistingRegressionAlgorithm(QCAlgorithm):
- def initialize(self):
- self.set_start_date(2020, 12, 1)
- self.set_end_date(2021, 1, 31)
- self.set_cash(100000)
-
- self.universe_symbol_count = 0
- self.universe_selection_done = False
- self.universe_added = False
- self.universe_removed = False
-
- self.universe_settings.resolution = Resolution.HOUR
- self.delisting_date = date(2021, 1, 21)
-
- self.aapl = self.add_equity("AAPL", Resolution.HOUR).symbol
- self.gdvd = self.add_equity("GDVD", Resolution.HOUR).symbol
-
- self.add_universe(self.universe.etf(self.gdvd, self.universe_settings, self.filter_etfs))
-
- def filter_etfs(self, constituents):
- self.universe_selection_done = True
-
- if self.utc_time.date() > self.delisting_date:
- raise Exception(f"Performing constituent universe selection on {self.utc_time.strftime('%Y-%m-%d %H:%M:%S.%f')} after composite ETF has been delisted")
-
- constituent_symbols = [i.symbol for i in constituents]
- self.universe_symbol_count = len(set(constituent_symbols))
-
- return constituent_symbols
-
- def on_data(self, data):
- if self.utc_time.date() > self.delisting_date and any([i != self.aapl for i in data.keys()]):
- raise Exception("Received unexpected slice in OnData(...) after universe was deselected")
-
- if not self.portfolio.invested:
- self.set_holdings(self.aapl, 0.5)
-
- def on_securities_changed(self, changes):
- if len(changes.added_securities) != 0 and self.utc_time.date() > self.delisting_date:
- raise Exception("New securities added after ETF constituents were delisted")
-
- # Since we added the etf subscription it will get delisted and send us a removal event
- expected_changes_count = self.universe_symbol_count + 1
-
- if self.universe_selection_done:
- # "_universe_symbol_count + 1" because selection is done right away,
- # so AddedSecurities includes all ETF constituents (including APPL) plus GDVD
- self.universe_added = self.universe_added or len(changes.added_securities) == expected_changes_count
-
- # TODO: shouldn't be sending AAPL as a removed security since it was added by another universe
- self.universe_removed = self.universe_removed or (
- len(changes.removed_securities) == expected_changes_count and
- self.utc_time.date() >= self.delisting_date and
- self.utc_time.date() < self.end_date.date())
-
- def on_end_of_algorithm(self):
- if not self.universe_added:
- raise Exception("ETF constituent universe was never added to the algorithm")
- if not self.universe_removed:
- raise Exception("ETF constituent universe was not removed from the algorithm after delisting")
- if len(self.active_securities) > 2:
- raise Exception(f"Expected less than 2 securities after algorithm ended, found {len(self.securities)}")
diff --git a/fincept-qt/scripts/strategies/ETFConstituentUniverseCompositeDelistingRegressionAlgorithmNoAddEquityETF.py b/fincept-qt/scripts/strategies/ETFConstituentUniverseCompositeDelistingRegressionAlgorithmNoAddEquityETF.py
deleted file mode 100644
index ab7a4737d..000000000
--- a/fincept-qt/scripts/strategies/ETFConstituentUniverseCompositeDelistingRegressionAlgorithmNoAddEquityETF.py
+++ /dev/null
@@ -1,74 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-D7673A55
-# Category: ETF
-# Description: Tests the delisting of the composite Symbol (ETF symbol) and the removal of the universe and the symbol from the algo...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Tests the delisting of the composite Symbol (ETF symbol) and the removal of
-### the universe and the symbol from the algorithm, without adding a subscription via AddEquity
-### </summary>
-class ETFConstituentUniverseCompositeDelistingRegressionAlgorithmNoAddEquityETF(QCAlgorithm):
- def initialize(self):
- self.set_start_date(2020, 12, 1)
- self.set_end_date(2021, 1, 31)
- self.set_cash(100000)
-
- self.universe_symbol_count = 0
- self.universe_selection_done = False
- self.universe_added = False
- self.universe_removed = False
-
- self.universe_settings.resolution = Resolution.HOUR
- self.delisting_date = date(2021, 1, 21)
-
- self.aapl = self.add_equity("AAPL", Resolution.HOUR).symbol
- self.gdvd = Symbol.create("GDVD", SecurityType.EQUITY, Market.USA)
-
- self.add_universe(self.universe.etf(self.gdvd, self.universe_settings, self.filter_etfs))
-
- def filter_etfs(self, constituents):
- self.universe_selection_done = True
-
- if self.utc_time.date() > self.delisting_date:
- raise Exception(f"Performing constituent universe selection on {self.utc_time.strftime('%Y-%m-%d %H:%M:%S.%f')} after composite ETF has been delisted")
-
- constituent_symbols = [i.symbol for i in constituents]
- self.universe_symbol_count = len(set(constituent_symbols))
-
- return constituent_symbols
-
- def on_data(self, data):
- if self.utc_time.date() > self.delisting_date and any([i != self.aapl for i in data.keys()]):
- raise Exception("Received unexpected slice in OnData(...) after universe was deselected")
-
- if not self.portfolio.invested:
- self.set_holdings(self.aapl, 0.5)
-
- def on_securities_changed(self, changes):
- if len(changes.added_securities) != 0 and self.utc_time.date() > self.delisting_date:
- raise Exception("New securities added after ETF constituents were delisted")
-
- if self.universe_selection_done:
- self.universe_added = self.universe_added or len(changes.added_securities) == self.universe_symbol_count
-
- # TODO: shouldn't be sending AAPL as a removed security since it was added by another universe
- self.universe_removed = self.universe_removed or (
- len(changes.removed_securities) == self.universe_symbol_count and
- self.utc_time.date() >= self.delisting_date and
- self.utc_time.date() < self.end_date.date())
-
- def on_end_of_algorithm(self):
- if not self.universe_added:
- raise Exception("ETF constituent universe was never added to the algorithm")
- if not self.universe_removed:
- raise Exception("ETF constituent universe was not removed from the algorithm after delisting")
- if len(self.active_securities) > 2:
- raise Exception(f"Expected less than 2 securities after algorithm ended, found {len(self.securities)}")
diff --git a/fincept-qt/scripts/strategies/ETFConstituentUniverseFilterFunctionRegressionAlgorithm.py b/fincept-qt/scripts/strategies/ETFConstituentUniverseFilterFunctionRegressionAlgorithm.py
deleted file mode 100644
index 9677c8886..000000000
--- a/fincept-qt/scripts/strategies/ETFConstituentUniverseFilterFunctionRegressionAlgorithm.py
+++ /dev/null
@@ -1,109 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-9E29F41C
-# Category: ETF
-# Description: Tests a custom filter function when creating an ETF constituents universe for SPY
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Tests a custom filter function when creating an ETF constituents universe for SPY
-### </summary>
-class ETFConstituentUniverseFilterFunctionRegressionAlgorithm(QCAlgorithm):
- def initialize(self):
- self.set_start_date(2020, 12, 1)
- self.set_end_date(2021, 1, 31)
- self.set_cash(100000)
-
- self.filtered = False
- self.securities_changed = False
- self.received_data = False
- self.etf_constituent_data = {}
- self.etf_rebalanced = False
- self.rebalance_count = 0
- self.rebalance_asset_count = 0
-
- self.universe_settings.resolution = Resolution.HOUR
-
- self.spy = self.add_equity("SPY", Resolution.HOUR).symbol
- self.aapl = Symbol.create("AAPL", SecurityType.EQUITY, Market.USA)
-
- self.add_universe(self.universe.etf(self.spy, self.universe_settings, self.filter_etfs))
-
- def filter_etfs(self, constituents):
- constituents_data = list(constituents)
- constituents_symbols = [i.symbol for i in constituents_data]
- self.etf_constituent_data = {i.symbol: i for i in constituents_data}
-
- if len(constituents_data) == 0:
- raise Exception(f"Constituents collection is empty on {self.utc_time.strftime('%Y-%m-%d %H:%M:%S.%f')}")
- if self.aapl not in constituents_symbols:
- raise Exception("AAPL is not int he constituents data provided to the algorithm")
-
- aapl_data = [i for i in constituents_data if i.symbol == self.aapl][0]
- if aapl_data.weight == 0.0:
- raise Exception("AAPL weight is expected to be a non-zero value")
-
- self.filtered = True
- self.etf_rebalanced = True
-
- return constituents_symbols
-
- def on_data(self, data):
- if not self.filtered and len(data.bars) != 0 and self.aapl in data.bars:
- raise Exception("AAPL TradeBar data added to algorithm before constituent universe selection took place")
-
- if len(data.bars) == 1 and self.spy in data.bars:
- return
-
- if len(data.bars) != 0 and self.aapl not in data.bars:
- raise Exception(f"Expected AAPL TradeBar data on {self.utc_time.strftime('%Y-%m-%d %H:%M:%S.%f')}")
-
- self.received_data = True
-
- if not self.etf_rebalanced:
- return
-
- for bar in data.bars.values():
- constituent_data = self.etf_constituent_data.get(bar.symbol)
- if constituent_data is not None and constituent_data.weight is not None and constituent_data.weight >= 0.0001:
- # If the weight of the constituent is less than 1%, then it will be set to 1%
- # If the weight of the constituent exceeds more than 5%, then it will be capped to 5%
- # Otherwise, if the weight falls in between, then we use that value.
- bounded_weight = max(0.01, min(constituent_data.weight, 0.05))
-
- self.set_holdings(bar.symbol, bounded_weight)
-
- if self.etf_rebalanced:
- self.rebalance_count += 1
-
- self.etf_rebalanced = False
- self.rebalance_asset_count += 1
-
-
- def on_securities_changed(self, changes):
- if self.filtered and not self.securities_changed and len(changes.added_securities) < 500:
- raise Exception(f"Added SPY S&P 500 ETF to algorithm, but less than 500 equities were loaded (added {len(changes.added_securities)} securities)")
-
- self.securities_changed = True
-
- def on_end_of_algorithm(self):
- if self.rebalance_count != 2:
- raise Exception(f"Expected 2 rebalance, instead rebalanced: {self.rebalance_count}")
-
- if self.rebalance_asset_count != 8:
- raise Exception(f"Invested in {self.rebalance_asset_count} assets (expected 8)")
-
- if not self.filtered:
- raise Exception("Universe selection was never triggered")
-
- if not self.securities_changed:
- raise Exception("Security changes never propagated to the algorithm")
-
- if not self.received_data:
- raise Exception("Data was never loaded for the S&P 500 constituent AAPL")
diff --git a/fincept-qt/scripts/strategies/ETFConstituentUniverseFrameworkRegressionAlgorithm.py b/fincept-qt/scripts/strategies/ETFConstituentUniverseFrameworkRegressionAlgorithm.py
deleted file mode 100644
index cde1f27d3..000000000
--- a/fincept-qt/scripts/strategies/ETFConstituentUniverseFrameworkRegressionAlgorithm.py
+++ /dev/null
@@ -1,147 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-D46C4922
-# Category: ETF
-# Description: Alpha model for ETF constituents, where we generate insights based on the weighting of the ETF constituent
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from typing import List
-from AlgorithmImports import *
-
-constituent_data = []
-
-### <summary>
-### Alpha model for ETF constituents, where we generate insights based on the weighting
-### of the ETF constituent
-### </summary>
-class ETFConstituentAlphaModel(AlphaModel):
- def on_securities_changed(self, algorithm, changes):
- pass
-
- ### <summary>
- ### Creates new insights based on constituent data and their weighting
- ### in their respective ETF
- ### </summary>
- def update(self, algorithm: QCAlgorithm, data: Slice):
- insights = []
-
- for constituent in constituent_data:
- if constituent.symbol not in data.bars and \
- constituent.symbol not in data.quote_bars:
-
- continue
-
- insight_direction = InsightDirection.UP if constituent.weight is not None and constituent.weight >= 0.01 else InsightDirection.DOWN
-
- insights.append(Insight(
- algorithm.utc_time,
- constituent.symbol,
- timedelta(days=1),
- InsightType.PRICE,
- insight_direction,
- float(1 * int(insight_direction)),
- 1.0,
- weight=float(0 if constituent.weight is None else constituent.weight)
- ))
-
- return insights
-
-### <summary>
-### Generates targets for ETF constituents, which will be set to the weighting
-### of the constituent in their respective ETF
-### </summary>
-class ETFConstituentPortfolioModel(PortfolioConstructionModel):
- def __init__(self):
- self.has_added = False
-
- ### <summary>
- ### Securities changed, detects if we've got new additions to the universe
- ### so that we don't try to trade every loop
- ### </summary>
- def on_securities_changed(self, algorithm: QCAlgorithm, changes: SecurityChanges):
- self.has_added = len(changes.added_securities) != 0
-
- ### <summary>
- ### Creates portfolio targets based on the insights provided to us by the alpha model.
- ### Emits portfolio targets setting the quantity to the weight of the constituent
- ### in its respective ETF.
- ### </summary>
- def create_targets(self, algorithm: QCAlgorithm, insights: List[Insight]):
- if not self.has_added:
- return []
-
- final_insights = []
- for insight in insights:
- final_insights.append(PortfolioTarget(insight.symbol, float(0 if insight.weight is None else insight.weight)))
- self.has_added = False
-
- return final_insights
-
-### <summary>
-### Executes based on ETF constituent weighting
-### </summary>
-class ETFConstituentExecutionModel(ExecutionModel):
- ### <summary>
- ### Liquidates if constituents have been removed from the universe
- ### </summary>
- def on_securities_changed(self, algorithm: QCAlgorithm, changes: SecurityChanges):
- for change in changes.removed_securities:
- algorithm.liquidate(change.symbol)
-
- ### <summary>
- ### Creates orders for constituents that attempts to add
- ### the weighting of the constituent in our portfolio. The
- ### resulting algorithm portfolio weight might not be equal
- ### to the leverage of the ETF (1x, 2x, 3x, etc.)
- ### </summary>
- def execute(self, algorithm: QCAlgorithm, targets: List[IPortfolioTarget]):
- for target in targets:
- algorithm.set_holdings(target.symbol, target.quantity)
-
-### <summary>
-### Tests ETF constituents universe selection with the algorithm framework models (Alpha, PortfolioConstruction, Execution)
-### </summary>
-class ETFConstituentUniverseFrameworkRegressionAlgorithm(QCAlgorithm):
- ### <summary>
- ### Initializes the algorithm, setting up the framework classes and ETF constituent universe settings
- ### </summary>
- def initialize(self):
- self.set_start_date(2020, 12, 1)
- self.set_end_date(2021, 1, 31)
- self.set_cash(100000)
-
- self.set_alpha(ETFConstituentAlphaModel())
- self.set_portfolio_construction(ETFConstituentPortfolioModel())
- self.set_execution(ETFConstituentExecutionModel())
-
- spy = Symbol.create("SPY", SecurityType.EQUITY, Market.USA)
-
- self.universe_settings.resolution = Resolution.HOUR
- universe = self.add_universe(self.universe.etf(spy, self.universe_settings, self.filter_etf_constituents))
-
- historical_data = self.history(universe, 1, flatten=True)
- if len(historical_data) < 200:
- raise ValueError(f"Unexpected universe DataCollection count {len(historical_data)}! Expected > 200")
-
- ### <summary>
- ### Filters ETF constituents
- ### </summary>
- ### <param name="constituents">ETF constituents</param>
- ### <returns>ETF constituent Symbols that we want to include in the algorithm</returns>
- def filter_etf_constituents(self, constituents):
- global constituent_data
-
- constituent_data_local = [i for i in constituents if i is not None and i.weight >= 0.001]
- constituent_data = list(constituent_data_local)
-
- return [i.symbol for i in constituent_data_local]
-
- ### <summary>
- ### no-op for performance
- ### </summary>
- def on_data(self, data):
- pass
diff --git a/fincept-qt/scripts/strategies/ETFConstituentUniverseMappedCompositeRegressionAlgorithm.py b/fincept-qt/scripts/strategies/ETFConstituentUniverseMappedCompositeRegressionAlgorithm.py
deleted file mode 100644
index e223bcac3..000000000
--- a/fincept-qt/scripts/strategies/ETFConstituentUniverseMappedCompositeRegressionAlgorithm.py
+++ /dev/null
@@ -1,86 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-B97EAA99
-# Category: ETF
-# Description: Tests the mapping of the ETF symbol that has a constituent universe attached to it and ensures that data is loaded af...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Tests the mapping of the ETF symbol that has a constituent universe attached to it and ensures
-### that data is loaded after the mapping event takes place.
-### </summary>
-class ETFConstituentUniverseFilterFunctionRegressionAlgorithm(QCAlgorithm):
- def initialize(self):
- self.set_start_date(2011, 2, 1)
- self.set_end_date(2011, 4, 4)
- self.set_cash(100000)
-
- self.filter_date_constituent_symbol_count = {}
- self.constituent_data_encountered = {}
- self.constituent_symbols = []
- self.mapping_event_occurred = False
-
- self.universe_settings.resolution = Resolution.HOUR
-
- self.aapl = Symbol.create("AAPL", SecurityType.EQUITY, Market.USA)
- self.qqq = self.add_equity("QQQ", Resolution.DAILY).symbol
-
- self.add_universe(self.universe.etf(self.qqq, self.universe_settings, self.filter_etfs))
-
- def filter_etfs(self, constituents):
- constituent_symbols = [i.symbol for i in constituents]
-
- if self.aapl not in constituent_symbols:
- raise Exception("AAPL not found in QQQ constituents")
-
- self.filter_date_constituent_symbol_count[self.utc_time.date()] = len(constituent_symbols)
- for symbol in constituent_symbols:
- self.constituent_symbols.append(symbol)
-
- self.constituent_symbols = list(set(self.constituent_symbols))
- return constituent_symbols
-
- def on_data(self, data):
- if len(data.symbol_changed_events) != 0:
- for symbol_changed in data.symbol_changed_events.values():
- if symbol_changed.symbol != self.qqq:
- raise Exception(f"Mapped symbol is not QQQ. Instead, found: {symbol_changed.symbol}")
- if symbol_changed.old_symbol != "QQQQ":
- raise Exception(f"Old QQQ Symbol is not QQQQ. Instead, found: {symbol_changed.old_symbol}")
- if symbol_changed.new_symbol != "QQQ":
- raise Exception(f"New QQQ Symbol is not QQQ. Instead, found: {symbol_changed.new_symbol}")
-
- self.mapping_event_occurred = True
-
- if self.qqq in data and len([i for i in data.keys()]) == 1:
- return
-
- if self.utc_time.date() not in self.constituent_data_encountered:
- self.constituent_data_encountered[self.utc_time.date()] = False
-
- if len([i for i in data.keys() if i in self.constituent_symbols]) != 0:
- self.constituent_data_encountered[self.utc_time.date()] = True
-
- if not self.portfolio.invested:
- self.set_holdings(self.aapl, 0.5)
-
- def on_end_of_algorithm(self):
- if len(self.filter_date_constituent_symbol_count) != 2:
- raise Exception(f"ETF constituent filtering function was not called 2 times (actual: {len(self.filter_date_constituent_symbol_count)}")
-
- if not self.mapping_event_occurred:
- raise Exception("No mapping/SymbolChangedEvent occurred. Expected for QQQ to be mapped from QQQQ -> QQQ")
-
- for constituent_date, constituents_count in self.filter_date_constituent_symbol_count.items():
- if constituents_count < 25:
- raise Exception(f"Expected 25 or more constituents in filter function on {constituent_date}, found {constituents_count}")
-
- for constituent_date, constituent_encountered in self.constituent_data_encountered.items():
- if not constituent_encountered:
- raise Exception(f"Received data in OnData(...) but it did not contain any constituent data on {constituent_date.strftime('%Y-%m-%d %H:%M:%S.%f')}")
diff --git a/fincept-qt/scripts/strategies/ETFConstituentUniverseRSIAlphaModelAlgorithm.py b/fincept-qt/scripts/strategies/ETFConstituentUniverseRSIAlphaModelAlgorithm.py
deleted file mode 100644
index d81ef2552..000000000
--- a/fincept-qt/scripts/strategies/ETFConstituentUniverseRSIAlphaModelAlgorithm.py
+++ /dev/null
@@ -1,117 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-4249AE56
-# Category: ETF
-# Description: Example algorithm demonstrating the usage of the RSI indicator in combination with ETF constituents data to replicate...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Example algorithm demonstrating the usage of the RSI indicator
-### in combination with ETF constituents data to replicate the weighting
-### of the ETF's assets in our own account.
-### </summary>
-class ETFConstituentUniverseRSIAlphaModelAlgorithm(QCAlgorithm):
- ### <summary>
- ### Initialize the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
- ### </summary>
- def initialize(self):
- self.set_start_date(2020, 12, 1)
- self.set_end_date(2021, 1, 31)
- self.set_cash(100000)
-
- self.set_alpha(ConstituentWeightedRsiAlphaModel())
- self.set_portfolio_construction(InsightWeightingPortfolioConstructionModel())
- self.set_execution(ImmediateExecutionModel())
-
- spy = self.add_equity("SPY", Resolution.HOUR).symbol
-
- # We load hourly data for ETF constituents in this algorithm
- self.universe_settings.resolution = Resolution.HOUR
- self.settings.minimum_order_margin_portfolio_percentage = 0.01
-
- self.add_universe(self.universe.etf(spy, self.universe_settings, self.filter_etf_constituents))
-
- ### <summary>
- ### Filters ETF constituents
- ### </summary>
- ### <param name="constituents">ETF constituents</param>
- ### <returns>ETF constituent Symbols that we want to include in the algorithm</returns>
- def filter_etf_constituents(self, constituents):
- return [i.symbol for i in constituents if i.weight is not None and i.weight >= 0.001]
-
-
-### <summary>
-### Alpha model making use of the RSI indicator and ETF constituent weighting to determine
-### which assets we should invest in and the direction of investment
-### </summary>
-class ConstituentWeightedRsiAlphaModel(AlphaModel):
- def __init__(self, max_trades=None):
- self.rsi_symbol_data = {}
-
- def update(self, algorithm: QCAlgorithm, data: Slice):
- algo_constituents = []
- for bar_symbol in data.bars.keys():
- if not algorithm.securities[bar_symbol].cache.has_data(ETFConstituentUniverse):
- continue
-
- constituent_data = algorithm.securities[bar_symbol].cache.get_data[ETFConstituentUniverse]()
- algo_constituents.append(constituent_data)
-
- if len(algo_constituents) == 0 or len(data.bars) == 0:
- # Don't do anything if we have no data we can work with
- return []
-
- constituents = {i.symbol:i for i in algo_constituents}
-
- for bar in data.bars.values():
- if bar.symbol not in constituents:
- # Dealing with a manually added equity, which in this case is SPY
- continue
-
- if bar.symbol not in self.rsi_symbol_data:
- # First time we're initializing the RSI.
- # It won't be ready now, but it will be
- # after 7 data points
- constituent = constituents[bar.symbol]
- self.rsi_symbol_data[bar.symbol] = SymbolData(bar.symbol, algorithm, constituent, 7)
-
- all_ready = all([sd.rsi.is_ready for sd in self.rsi_symbol_data.values()])
- if not all_ready:
- # We're still warming up the RSI indicators.
- return []
-
- insights = []
-
- for symbol, symbol_data in self.rsi_symbol_data.items():
- average_loss = symbol_data.rsi.average_loss.current.value
- average_gain = symbol_data.rsi.average_gain.current.value
-
- # If we've lost more than gained, then we think it's going to go down more
- direction = InsightDirection.DOWN if average_loss > average_gain else InsightDirection.UP
-
- # Set the weight of the insight as the weight of the ETF's
- # holding. The InsightWeightingPortfolioConstructionModel
- # will rebalance our portfolio to have the same percentage
- # of holdings in our algorithm that the ETF has.
- insights.append(Insight.price(
- symbol,
- timedelta(days=1),
- direction,
- float(average_loss if direction == InsightDirection.DOWN else average_gain),
- weight=float(symbol_data.constituent.weight)
- ))
-
- return insights
-
-
-class SymbolData:
- def __init__(self, symbol, algorithm, constituent, period):
- self.symbol = symbol
- self.constituent = constituent
- self.rsi = algorithm.rsi(symbol, period, MovingAverageType.EXPONENTIAL, Resolution.HOUR)
diff --git a/fincept-qt/scripts/strategies/ETFConstituentsFrameworkAlgorithm.py b/fincept-qt/scripts/strategies/ETFConstituentsFrameworkAlgorithm.py
deleted file mode 100644
index 91f8f2463..000000000
--- a/fincept-qt/scripts/strategies/ETFConstituentsFrameworkAlgorithm.py
+++ /dev/null
@@ -1,39 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-A8E104E5
-# Category: ETF
-# Description: Demonstration of using the ETFConstituentsUniverseSelectionModel
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-from Selection.ETFConstituentsUniverseSelectionModel import *
-
-### <summary>
-### Demonstration of using the ETFConstituentsUniverseSelectionModel
-### </summary>
-class ETFConstituentsFrameworkAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2020, 12, 1)
- self.set_end_date(2020, 12, 7)
- self.set_cash(100000)
-
- self.universe_settings.resolution = Resolution.DAILY
- symbol = Symbol.create("SPY", SecurityType.EQUITY, Market.USA)
- self.add_universe_selection(ETFConstituentsUniverseSelectionModel(symbol, self.universe_settings, self.etf_constituents_filter))
-
- self.add_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(days=1)))
-
- self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())
-
-
- def etf_constituents_filter(self, constituents: List[ETFConstituentData]) -> List[Symbol]:
- # Get the 10 securities with the largest weight in the index
- selected = sorted([c for c in constituents if c.weight],
- key=lambda c: c.weight, reverse=True)[:8]
- return [c.symbol for c in selected]
-
diff --git a/fincept-qt/scripts/strategies/ETFConstituentsFrameworkWithDifferentSelectionModelAlgorithm.py b/fincept-qt/scripts/strategies/ETFConstituentsFrameworkWithDifferentSelectionModelAlgorithm.py
deleted file mode 100644
index 26f82e599..000000000
--- a/fincept-qt/scripts/strategies/ETFConstituentsFrameworkWithDifferentSelectionModelAlgorithm.py
+++ /dev/null
@@ -1,24 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-A7B56E18
-# Category: ETF
-# Description: Demonstration of using the ETFConstituentsUniverseSelectionModel with simple ticker
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-from Selection.ETFConstituentsUniverseSelectionModel import *
-from ETFConstituentsFrameworkAlgorithm import ETFConstituentsFrameworkAlgorithm
-
-### <summary>
-### Demonstration of using the ETFConstituentsUniverseSelectionModel with simple ticker
-### </summary>
-class ETFConstituentsFrameworkWithDifferentSelectionModelAlgorithm(ETFConstituentsFrameworkAlgorithm):
-
- def initialize(self):
- super().initialize()
-
- self.set_universe_selection(ETFConstituentsUniverseSelectionModel("SPY", self.universe_settings, self.etf_constituents_filter))
diff --git a/fincept-qt/scripts/strategies/ETFGlobalRotationAlgorithm.py b/fincept-qt/scripts/strategies/ETFGlobalRotationAlgorithm.py
deleted file mode 100644
index 45bcc9b17..000000000
--- a/fincept-qt/scripts/strategies/ETFGlobalRotationAlgorithm.py
+++ /dev/null
@@ -1,92 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-D3112758
-# Category: ETF
-# Description: Strategy example using a portfolio of ETF Global Rotation
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Strategy example using a portfolio of ETF Global Rotation
-### </summary>
-### <meta name="tag" content="strategy example" />
-### <meta name="tag" content="momentum" />
-### <meta name="tag" content="using data" />
-
-### <summary>
-### Strategy example using a portfolio of ETF Global Rotation
-### </summary>
-### <meta name="tag" content="strategy example" />
-### <meta name="tag" content="momentum" />
-### <meta name="tag" content="using data" />
-class ETFGlobalRotationAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_cash(25000)
- self.set_start_date(2007,1,1)
- self.last_rotation_time = datetime.min
- self.rotation_interval = timedelta(days=30)
- self.first = True
-
- # these are the growth symbols we'll rotate through
- growth_symbols =["MDY", # US S&P mid cap 400
- "IEV", # i_shares S&P europe 350
- "EEM", # i_shared MSCI emerging markets
- "ILF", # i_shares S&P latin america
- "EPP" ] # i_shared MSCI Pacific ex-Japan
-
- # these are the safety symbols we go to when things are looking bad for growth
- safety_symbols = ["EDV", "SHY"] # "EDV" Vangaurd TSY 25yr, "SHY" Barclays Low Duration TSY
- # we'll hold some computed data in these guys
- self.symbol_data = []
- for symbol in list(set(growth_symbols) | set(safety_symbols)):
- self.add_security(SecurityType.EQUITY, symbol, Resolution.MINUTE)
- self.one_month_performance = self.mom(symbol, 30, Resolution.DAILY)
- self.three_month_performance = self.mom(symbol, 90, Resolution.DAILY)
- self.symbol_data.append([symbol, self.one_month_performance, self.three_month_performance])
-
-
- def on_data(self, data):
- # the first time we come through here we'll need to do some things such as allocation
- # and initializing our symbol data
-
- if self.first:
- self.first = False
- self.last_rotation_time = self.time
- return
- delta = self.time - self.last_rotation_time
- if delta > self.rotation_interval:
- self.last_rotation_time = self.time
-
- ordered_obj_scores = sorted(self.symbol_data, key=lambda x: Score(x[1].current.value,x[2].current.value).objective_score(), reverse=True)
- for x in ordered_obj_scores:
- self.log(">>SCORE>>" + x[0] + ">>" + str(Score(x[1].current.value,x[2].current.value).objective_score()))
- # pick which one is best from growth and safety symbols
- best_growth = ordered_obj_scores[0]
- if Score(best_growth[1].current.value,best_growth[2].current.value).objective_score() > 0:
- if (self.portfolio[best_growth[0]].quantity == 0):
- self.log("PREBUY>>LIQUIDATE>>")
- self.liquidate()
- self.log(">>BUY>>" + str(best_growth[0]) + "@" + str(100 * best_growth[1].current.value))
- qty = self.portfolio.margin_remaining / self.securities[best_growth[0]].close
- self.market_order(best_growth[0], int(qty))
- else:
- # if no one has a good objective score then let's hold cash this month to be safe
- self.log(">>LIQUIDATE>>CASH")
- self.liquidate()
-
-class Score(object):
-
- def __init__(self,one_month_performance_value,three_month_performance_value):
- self.one_month_performance = one_month_performance_value
- self.three_month_performance = three_month_performance_value
-
- def objective_score(self):
- weight1 = 100
- weight2 = 75
- return (weight1 * self.one_month_performance + weight2 * self.three_month_performance) / (weight1 + weight2)
diff --git a/fincept-qt/scripts/strategies/EmaCrossAlphaModelFrameworkRegressionAlgorithm.py b/fincept-qt/scripts/strategies/EmaCrossAlphaModelFrameworkRegressionAlgorithm.py
deleted file mode 100644
index e5e551a2a..000000000
--- a/fincept-qt/scripts/strategies/EmaCrossAlphaModelFrameworkRegressionAlgorithm.py
+++ /dev/null
@@ -1,26 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-A3A4BE5B
-# Category: Alpha Model
-# Description: Regression algorithm to assert the behavior of <see cref="EmaCrossAlphaModel"/>
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-from BaseFrameworkRegressionAlgorithm import BaseFrameworkRegressionAlgorithm
-from Alphas.EmaCrossAlphaModel import EmaCrossAlphaModel
-
-### <summary>
-### Regression algorithm to assert the behavior of <see cref="EmaCrossAlphaModel"/>.
-### </summary>
-class EmaCrossAlphaModelFrameworkRegressionAlgorithm(BaseFrameworkRegressionAlgorithm):
-
- def initialize(self):
- super().initialize()
- self.set_alpha(EmaCrossAlphaModel())
-
- def on_end_of_algorithm(self):
- pass
diff --git a/fincept-qt/scripts/strategies/EmaCrossFuturesFrontMonthAlgorithm.py b/fincept-qt/scripts/strategies/EmaCrossFuturesFrontMonthAlgorithm.py
deleted file mode 100644
index bf1c7ff10..000000000
--- a/fincept-qt/scripts/strategies/EmaCrossFuturesFrontMonthAlgorithm.py
+++ /dev/null
@@ -1,88 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-EE365736
-# Category: Futures
-# Description: This example demonstrates how to implement a cross moving average for the futures front contract
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### This example demonstrates how to implement a cross moving average for the futures front contract
-### </summary>
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="indicator" />
-### <meta name="tag" content="futures" />
-class EmaCrossFuturesFrontMonthAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2013, 10, 8)
- self.set_end_date(2013, 10, 10)
- self.set_cash(1000000)
-
- future = self.add_future(Futures.Metals.GOLD)
-
- # Only consider the front month contract
- # Update the universe once per day to improve performance
- future.set_filter(lambda x: x.front_month().only_apply_filter_at_market_open())
-
- # Symbol of the current contract
- self._symbol = None
-
- # Create two exponential moving averages
- self.fast = ExponentialMovingAverage(100)
- self.slow = ExponentialMovingAverage(300)
- self.tolerance = 0.001
- self.consolidator = None
-
- # Add a custom chart to track the EMA cross
- chart = Chart('EMA Cross')
- chart.add_series(Series('Fast', SeriesType.LINE, 0))
- chart.add_series(Series('Slow', SeriesType.LINE, 0))
- self.add_chart(chart)
-
- def on_data(self,slice):
-
- holding = None if self._symbol is None else self.portfolio.get(self._symbol)
- if holding is not None:
- # Buy the futures' front contract when the fast EMA is above the slow one
- if self.fast.current.value > self.slow.current.value * (1 + self.tolerance):
- if not holding.invested:
- self.set_holdings(self._symbol, .1)
- self.plot_ema()
- elif holding.invested:
- self.liquidate(self._symbol)
- self.plot_ema()
-
- def on_securities_changed(self, changes):
- if len(changes.removed_securities) > 0:
- # Remove the consolidator for the previous contract
- # and reset the indicators
- if self._symbol is not None and self.consolidator is not None:
- self.subscription_manager.remove_consolidator(self._symbol, self.consolidator)
- self.fast.reset()
- self.slow.reset()
- # We don't need to call Liquidate(_symbol),
- # since its positions are liquidated because the contract has expired.
-
- # Only one security will be added: the new front contract
- self._symbol = changes.added_securities[0].symbol
-
- # Create a new consolidator and register the indicators to it
- self.consolidator = self.resolve_consolidator(self._symbol, Resolution.MINUTE)
- self.register_indicator(self._symbol, self.fast, self.consolidator)
- self.register_indicator(self._symbol, self.slow, self.consolidator)
-
- # Warm up the indicators
- self.warm_up_indicator(self._symbol, self.fast, Resolution.MINUTE)
- self.warm_up_indicator(self._symbol, self.slow, Resolution.MINUTE)
-
- self.plot_ema()
-
- def plot_ema(self):
- self.plot('EMA Cross', 'Fast', self.fast.current.value)
- self.plot('EMA Cross', 'Slow', self.slow.current.value)
diff --git a/fincept-qt/scripts/strategies/EmaCrossUniverseSelectionAlgorithm.py b/fincept-qt/scripts/strategies/EmaCrossUniverseSelectionAlgorithm.py
deleted file mode 100644
index bce4a2657..000000000
--- a/fincept-qt/scripts/strategies/EmaCrossUniverseSelectionAlgorithm.py
+++ /dev/null
@@ -1,94 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-E66F50F9
-# Category: Universe Selection
-# Description: In this algorithm we demonstrate how to perform some technical analysis as part of your coarse fundamental universe s...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### In this algorithm we demonstrate how to perform some technical analysis as
-### part of your coarse fundamental universe selection
-### </summary>
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="indicators" />
-### <meta name="tag" content="universes" />
-### <meta name="tag" content="coarse universes" />
-class EmaCrossUniverseSelectionAlgorithm(QCAlgorithm):
-
- def initialize(self):
- '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
-
- self.set_start_date(2010,1,1) #Set Start Date
- self.set_end_date(2015,1,1) #Set End Date
- self.set_cash(100000) #Set Strategy Cash
-
- self.universe_settings.resolution = Resolution.DAILY
- self.universe_settings.leverage = 2
-
- self.coarse_count = 10
- self.averages = { }
-
- # this add universe method accepts two parameters:
- # - coarse selection function: accepts an IEnumerable<CoarseFundamental> and returns an IEnumerable<Symbol>
- self.add_universe(self.coarse_selection_function)
-
-
- # sort the data by daily dollar volume and take the top 'NumberOfSymbols'
- def coarse_selection_function(self, coarse):
-
- # We are going to use a dictionary to refer the object that will keep the moving averages
- for cf in coarse:
- if cf.symbol not in self.averages:
- self.averages[cf.symbol] = SymbolData(cf.symbol)
-
- # Updates the SymbolData object with current EOD price
- avg = self.averages[cf.symbol]
- avg.update(cf.end_time, cf.adjusted_price)
-
- # Filter the values of the dict: we only want up-trending securities
- values = list(filter(lambda x: x.is_uptrend, self.averages.values()))
-
- # Sorts the values of the dict: we want those with greater difference between the moving averages
- values.sort(key=lambda x: x.scale, reverse=True)
-
- for x in values[:self.coarse_count]:
- self.log('symbol: ' + str(x.symbol.value) + ' scale: ' + str(x.scale))
-
- # we need to return only the symbol objects
- return [ x.symbol for x in values[:self.coarse_count] ]
-
- # this event fires whenever we have changes to our universe
- def on_securities_changed(self, changes):
- # liquidate removed securities
- for security in changes.removed_securities:
- if security.invested:
- self.liquidate(security.symbol)
-
- # we want 20% allocation in each security in our universe
- for security in changes.added_securities:
- self.set_holdings(security.symbol, 0.1)
-
-
-class SymbolData(object):
- def __init__(self, symbol):
- self._symbol = symbol
- self.tolerance = 1.01
- self.fast = ExponentialMovingAverage(100)
- self.slow = ExponentialMovingAverage(300)
- self.is_uptrend = False
- self.scale = 0
-
- def update(self, time, value):
- if self.fast.update(time, value) and self.slow.update(time, value):
- fast = self.fast.current.value
- slow = self.slow.current.value
- self.is_uptrend = fast > slow * self.tolerance
-
- if self.is_uptrend:
- self.scale = (fast - slow) / ((fast + slow) / 2.0)
diff --git a/fincept-qt/scripts/strategies/EmaCrossUniverseSelectionFrameworkAlgorithm.py b/fincept-qt/scripts/strategies/EmaCrossUniverseSelectionFrameworkAlgorithm.py
deleted file mode 100644
index 528808340..000000000
--- a/fincept-qt/scripts/strategies/EmaCrossUniverseSelectionFrameworkAlgorithm.py
+++ /dev/null
@@ -1,39 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-AE32C215
-# Category: Universe Selection
-# Description: Framework algorithm that uses the EmaCrossUniverseSelectionModel to select the universe based on a moving average cross
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-from Alphas.ConstantAlphaModel import ConstantAlphaModel
-from Selection.EmaCrossUniverseSelectionModel import EmaCrossUniverseSelectionModel
-from Portfolio.EqualWeightingPortfolioConstructionModel import EqualWeightingPortfolioConstructionModel
-
-### <summary>
-### Framework algorithm that uses the EmaCrossUniverseSelectionModel to
-### select the universe based on a moving average cross.
-### </summary>
-class EmaCrossUniverseSelectionFrameworkAlgorithm(QCAlgorithm):
- '''Framework algorithm that uses the EmaCrossUniverseSelectionModel to select the universe based on a moving average cross.'''
-
- def initialize(self):
-
- self.set_start_date(2013,1,1)
- self.set_end_date(2015,1,1)
- self.set_cash(100000)
-
- fast_period = 100
- slow_period = 300
- count = 10
-
- self.universe_settings.leverage = 2.0
- self.universe_settings.resolution = Resolution.DAILY
-
- self.set_universe_selection(EmaCrossUniverseSelectionModel(fast_period, slow_period, count))
- self.set_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(1), None, None))
- self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())
diff --git a/fincept-qt/scripts/strategies/Execution/__init__.py b/fincept-qt/scripts/strategies/Execution/__init__.py
deleted file mode 100644
index 67622e672..000000000
--- a/fincept-qt/scripts/strategies/Execution/__init__.py
+++ /dev/null
@@ -1,30 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Execution Shim
-# Re-exports from fincept_engine + dynamic submodule stubs
-# ============================================================================
-
-import sys, os, types
-
-_parent = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
-if _parent not in sys.path:
- sys.path.insert(0, _parent)
-
-from fincept_engine.algorithm_imports import (
- ExecutionModel, ImmediateExecutionModel,
- VolumeWeightedAveragePriceExecutionModel,
- StandardDeviationExecutionModel
-)
-from fincept_engine.framework.execution import SpreadExecutionModel
-
-_submodules = {
- 'ImmediateExecutionModel': {'ImmediateExecutionModel': ImmediateExecutionModel},
- 'VolumeWeightedAveragePriceExecutionModel': {'VolumeWeightedAveragePriceExecutionModel': VolumeWeightedAveragePriceExecutionModel},
- 'StandardDeviationExecutionModel': {'StandardDeviationExecutionModel': StandardDeviationExecutionModel},
- 'SpreadExecutionModel': {'SpreadExecutionModel': SpreadExecutionModel},
-}
-
-for _name, _attrs in _submodules.items():
- _mod = types.ModuleType(f'Execution.{_name}')
- for _attr_name, _attr_val in _attrs.items():
- setattr(_mod, _attr_name, _attr_val)
- sys.modules[f'Execution.{_name}'] = _mod
diff --git a/fincept-qt/scripts/strategies/ExpiryHelperAlphaModelFrameworkAlgorithm.py b/fincept-qt/scripts/strategies/ExpiryHelperAlphaModelFrameworkAlgorithm.py
deleted file mode 100644
index b7d263fef..000000000
--- a/fincept-qt/scripts/strategies/ExpiryHelperAlphaModelFrameworkAlgorithm.py
+++ /dev/null
@@ -1,76 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-62C5A2BF
-# Category: Alpha Model
-# Description: Expiry Helper algorithm uses Expiry helper class in an Alpha Model
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Expiry Helper algorithm uses Expiry helper class in an Alpha Model
-### </summary>
-class ExpiryHelperAlphaModelFrameworkAlgorithm(QCAlgorithm):
- '''Expiry Helper framework algorithm uses Expiry helper class in an Alpha Model'''
-
- def initialize(self):
- ''' Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
-
- # Set requested data resolution
- self.universe_settings.resolution = Resolution.HOUR
-
- self.set_start_date(2013,10,7) #Set Start Date
- self.set_end_date(2014,1,1) #Set End Date
- self.set_cash(100000) #Set Strategy Cash
-
- symbols = [ Symbol.create("SPY", SecurityType.EQUITY, Market.USA) ]
-
- # set algorithm framework models
- self.set_universe_selection(ManualUniverseSelectionModel(symbols))
- self.set_alpha(self.ExpiryHelperAlphaModel())
- self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())
- self.set_execution(ImmediateExecutionModel())
- self.set_risk_management(MaximumDrawdownPercentPerSecurity(0.01))
-
- self.insights_generated += self.on_insights_generated
-
- def on_insights_generated(self, s, e):
- for insight in e.insights:
- self.log(f"{e.date_time_utc.isoweekday()}: Close Time {insight.close_time_utc} {insight.close_time_utc.isoweekday()}")
-
- class ExpiryHelperAlphaModel(AlphaModel):
- next_update = None
- direction = InsightDirection.UP
-
- def update(self, algorithm, data):
-
- if self.next_update is not None and self.next_update > algorithm.time:
- return []
-
- expiry = Expiry.END_OF_DAY
-
- # Use the Expiry helper to calculate a date/time in the future
- self.next_update = expiry(algorithm.time)
-
- weekday = algorithm.time.isoweekday()
-
- insights = []
- for symbol in data.bars.keys():
- # Expected CloseTime: next month on the same day and time
- if weekday == 1:
- insights.append(Insight.price(symbol, Expiry.ONE_MONTH, self.direction))
- # Expected CloseTime: next month on the 1st at market open time
- elif weekday == 2:
- insights.append(Insight.price(symbol, Expiry.END_OF_MONTH, self.direction))
- # Expected CloseTime: next Monday at market open time
- elif weekday == 3:
- insights.append(Insight.price(symbol, Expiry.END_OF_WEEK, self.direction))
- # Expected CloseTime: next day (Friday) at market open time
- elif weekday == 4:
- insights.append(Insight.price(symbol, Expiry.END_OF_DAY, self.direction))
-
- return insights
diff --git a/fincept-qt/scripts/strategies/ExtendedMarketTradingRegressionAlgorithm.py b/fincept-qt/scripts/strategies/ExtendedMarketTradingRegressionAlgorithm.py
deleted file mode 100644
index fc8cbd318..000000000
--- a/fincept-qt/scripts/strategies/ExtendedMarketTradingRegressionAlgorithm.py
+++ /dev/null
@@ -1,53 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-47C778A4
-# Category: Regression Test
-# Description: This algorithm demonstrates extended market hours trading
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### This algorithm demonstrates extended market hours trading.
-### </summary>
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="assets" />
-### <meta name="tag" content="regression test" />
-class ExtendedMarketTradingRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self):
- '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
- self.set_start_date(2013,10,7) #Set Start Date
- self.set_end_date(2013,10,11) #Set End Date
- self.set_cash(100000) #Set Strategy Cash
- # Fincept Terminal Strategy Engine - Symbol Configuration
- self.spy = self.add_equity("SPY", Resolution.MINUTE, Market.USA, True, 1, True)
-
- self._last_action = None
-
- def on_data(self, data):
- '''on_data event is the primary entry point for your algorithm. Each new data point will be pumped in here.'''
- if self._last_action is not None and self._last_action.date() == self.time.date():
- return
-
- spy_bar = data.bars['SPY']
-
- if not self.in_market_hours():
- self.limit_order("SPY", 10, spy_bar.low)
- self._last_action = self.time
-
- def on_order_event(self, order_event):
- self.log(str(order_event))
- if self.in_market_hours():
- raise Exception("Order processed during market hours.")
-
- def in_market_hours(self):
- now = self.time.time()
- open = time(9,30,0)
- close = time(16,0,0)
- return (open < now) and (close > now)
-
diff --git a/fincept-qt/scripts/strategies/FilterUniverseRegressionAlgorithm.py b/fincept-qt/scripts/strategies/FilterUniverseRegressionAlgorithm.py
deleted file mode 100644
index 804a0ad84..000000000
--- a/fincept-qt/scripts/strategies/FilterUniverseRegressionAlgorithm.py
+++ /dev/null
@@ -1,55 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-E75184B8
-# Category: Universe Selection
-# Description: This regression algorithm is for testing a custom Python filter for options that returns a OptionFilterUniverse
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### This regression algorithm is for testing a custom Python filter for options
-### that returns a OptionFilterUniverse.
-### </summary>
-### <meta name="tag" content="options" />
-### <meta name="tag" content="filter selection" />
-### <meta name="tag" content="regression test" />
-class FilterUniverseRegressionAlgorithm(QCAlgorithm):
- underlying_ticker = "GOOG"
-
- def initialize(self):
- self.set_start_date(2015, 12, 24)
- self.set_end_date(2015, 12, 28)
- self.set_cash(100000)
-
- equity = self.add_equity(self.underlying_ticker)
- option = self.add_option(self.underlying_ticker)
- self.option_symbol = option.symbol
-
- # Set our custom universe filter
- option.set_filter(self.filter_function)
-
- # use the underlying equity as the benchmark
- self.set_benchmark(equity.symbol)
-
- def filter_function(self, universe):
- universe = universe.weeklys_only().strikes(-5, +5).calls_only().expiration(0, 1)
- return universe
-
- def on_data(self,slice):
- if self.portfolio.invested: return
-
- for kvp in slice.option_chains:
-
- if kvp.key != self.option_symbol: continue
-
- chain = kvp.value
- contracts = [option for option in sorted(chain, key = lambda x:x.strike, reverse = True)]
-
- if contracts:
- self.market_order(contracts[0].symbol, 1)
-
diff --git a/fincept-qt/scripts/strategies/FilteredIdentityAlgorithm.py b/fincept-qt/scripts/strategies/FilteredIdentityAlgorithm.py
deleted file mode 100644
index 9b9cd5f0a..000000000
--- a/fincept-qt/scripts/strategies/FilteredIdentityAlgorithm.py
+++ /dev/null
@@ -1,48 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-F0179E57
-# Category: General Strategy
-# Description: Example algorithm of the Identity indicator with the filtering enhancement. Filtering is used to check the output of ...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Example algorithm of the Identity indicator with the filtering enhancement. Filtering is used to check
-### the output of the indicator before returning it.
-### </summary>
-### <meta name="tag" content="indicators" />
-### <meta name="tag" content="indicator classes" />
-class FilteredIdentityAlgorithm(QCAlgorithm):
- ''' Example algorithm of the Identity indicator with the filtering enhancement '''
-
- def initialize(self):
-
- self.set_start_date(2014,5,2) # Set Start Date
- self.set_end_date(self.start_date) # Set End Date
- self.set_cash(100000) # Set Stratgy Cash
-
- # Fincept Terminal Strategy Engine - Symbol Configuration
- security = self.add_forex("EURUSD", Resolution.TICK)
-
- self._symbol = security.symbol
- self.identity = self.filtered_identity(self._symbol, None, self.filter)
-
- def filter(self, data):
- '''Filter function: True if data is not an instance of Tick. If it is, true if TickType is Trade
- data -- Data for applying the filter'''
- if isinstance(data, Tick):
- return data.tick_type == TickType.TRADE
- return True
-
- def on_data(self, data):
- # Since we are only accepting TickType.TRADE,
- # this indicator will never be ready
- if not self.identity.is_ready: return
- if not self.portfolio.invested:
- self.set_holdings(self._symbol, 1)
- self.debug("Purchased Stock")
diff --git a/fincept-qt/scripts/strategies/FinancialAdvisorDemoAlgorithm.py b/fincept-qt/scripts/strategies/FinancialAdvisorDemoAlgorithm.py
deleted file mode 100644
index 0d6942ba1..000000000
--- a/fincept-qt/scripts/strategies/FinancialAdvisorDemoAlgorithm.py
+++ /dev/null
@@ -1,58 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-29D656ED
-# Category: General Strategy
-# Description: This algorithm demonstrates how to submit orders to a Financial Advisor account group, allocation profile or a single...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### This algorithm demonstrates how to submit orders to a Financial Advisor account group, allocation profile or a single managed account.
-### </summary>
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="using quantconnect" />
-### <meta name="tag" content="trading and orders" />
-### <meta name="tag" content="financial advisor" />
-class FinancialAdvisorDemoAlgorithm(QCAlgorithm):
-
- def initialize(self):
- # Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must be initialized.
-
- self.set_start_date(2013,10,7) #Set Start Date
- self.set_end_date(2013,10,11) #Set End Date
- self.set_cash(100000) #Set Strategy Cash
-
- self._symbol = self.add_equity("SPY", Resolution.SECOND).symbol
-
- # The default order properties can be set here to choose the FA settings
- # to be automatically used in any order submission method (such as SetHoldings, Buy, Sell and Order)
-
- # Use a default FA Account Group with an Allocation Method
- self.default_order_properties = InteractiveBrokersOrderProperties()
- # account group created manually in IB/TWS
- self.default_order_properties.fa_group = "TestGroupEQ"
- # supported allocation methods are: EqualQuantity, NetLiq, AvailableEquity, PctChange
- self.default_order_properties.fa_method = "EqualQuantity"
-
- # set a default FA Allocation Profile
- # DefaultOrderProperties = InteractiveBrokersOrderProperties()
- # allocation profile created manually in IB/TWS
- # self.default_order_properties.fa_profile = "TestProfileP"
-
- # send all orders to a single managed account
- # DefaultOrderProperties = InteractiveBrokersOrderProperties()
- # a sub-account linked to the Financial Advisor master account
- # self.default_order_properties.account = "DU123456"
-
- def on_data(self, data):
- # on_data event is the primary entry point for your algorithm. Each new data point will be pumped in here.
-
- if not self.portfolio.invested:
- # when logged into IB as a Financial Advisor, this call will use order properties
- # set in the DefaultOrderProperties property of QCAlgorithm
- self.set_holdings("SPY", 1)
diff --git a/fincept-qt/scripts/strategies/FineFundamentalFilteredUniverseRegressionAlgorithm.py b/fincept-qt/scripts/strategies/FineFundamentalFilteredUniverseRegressionAlgorithm.py
deleted file mode 100644
index e234b323d..000000000
--- a/fincept-qt/scripts/strategies/FineFundamentalFilteredUniverseRegressionAlgorithm.py
+++ /dev/null
@@ -1,42 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-BB3C695A
-# Category: Universe Selection
-# Description: Regression algorithm which tests a fine fundamental filtered universe, related to GH issue 4127
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Regression algorithm which tests a fine fundamental filtered universe,
-### related to GH issue 4127
-### </summary>
-class FineFundamentalFilteredUniverseRegressionAlgorithm(QCAlgorithm):
- def initialize(self):
- '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
-
- self.set_start_date(2014, 10, 8)
- self.set_end_date(2014, 10, 13)
-
- self.universe_settings.resolution = Resolution.DAILY
-
- symbol = Symbol(SecurityIdentifier.generate_constituent_identifier("constituents-universe-qctest", SecurityType.EQUITY, Market.USA), "constituents-universe-qctest")
- self.add_universe(ConstituentsUniverse(symbol, self.universe_settings), self.fine_selection_function)
-
- def fine_selection_function(self, fine):
- return [ x.symbol for x in fine if x.company_profile != None and x.company_profile.headquarter_city != None and x.company_profile.headquarter_city.lower() == "cupertino" ]
-
- def on_data(self, data):
- '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
-
- Arguments:
- data: Slice object keyed by symbol containing the stock data
- '''
- if not self.portfolio.invested:
- if data.keys()[0].value != "AAPL":
- raise ValueError(f"Unexpected symbol was added to the universe: {data.keys()[0]}")
- self.set_holdings(data.keys()[0], 1)
diff --git a/fincept-qt/scripts/strategies/ForwardDataOnlyFillModelAlgorithm.py b/fincept-qt/scripts/strategies/ForwardDataOnlyFillModelAlgorithm.py
deleted file mode 100644
index a3c40f63b..000000000
--- a/fincept-qt/scripts/strategies/ForwardDataOnlyFillModelAlgorithm.py
+++ /dev/null
@@ -1,37 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-0212DBCD
-# Category: General Strategy
-# Description: Weekly rebalancing strategy. Buys SPY at the start of each week
-# if not already invested. Originally demonstrated custom fill models; adapted
-# to use simple weekly entry logic with standard fills.
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-class ForwardDataOnlyFillModelAlgorithm(QCAlgorithm):
- """Weekly rebalancing strategy: enters SPY position each Monday."""
-
- def initialize(self):
- self.set_start_date(2013, 10, 1)
- self.set_end_date(2013, 10, 31)
- self.set_cash(100000)
-
- self.add_equity("SPY", Resolution.DAILY)
- self._last_trade_week = -1
-
- def on_data(self, data):
- if "SPY" not in data:
- return
-
- current_week = self.time.isocalendar()[1]
-
- # Trade once per week
- if current_week != self._last_trade_week:
- self._last_trade_week = current_week
- if not self.portfolio.invested:
- self.set_holdings("SPY", 1)
diff --git a/fincept-qt/scripts/strategies/FractionalQuantityRegressionAlgorithm.py b/fincept-qt/scripts/strategies/FractionalQuantityRegressionAlgorithm.py
deleted file mode 100644
index 095885a0c..000000000
--- a/fincept-qt/scripts/strategies/FractionalQuantityRegressionAlgorithm.py
+++ /dev/null
@@ -1,59 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-BA248F90
-# Category: Regression Test
-# Description: Regression algorithm for fractional forex pair
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Regression algorithm for fractional forex pair
-### </summary>
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="trading and orders" />
-### <meta name="tag" content="regression test" />
-class FractionalQuantityRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self):
-
- self.set_start_date(2015, 11, 12)
- self.set_end_date(2016, 4, 1)
- self.set_cash(100000)
- self.set_brokerage_model(BrokerageName.GDAX, AccountType.CASH)
-
- self.set_time_zone(TimeZones.UTC)
-
- security = self.add_security(SecurityType.CRYPTO, "BTCUSD", Resolution.DAILY, Market.GDAX, False, 1, True)
-
- ### The default buying power model for the Crypto security type is now CashBuyingPowerModel.
- ### Since this test algorithm uses leverage we need to set a buying power model with margin.
- security.set_buying_power_model(SecurityMarginModel(3.3))
-
- con = TradeBarConsolidator(1)
- self.subscription_manager.add_consolidator("BTCUSD", con)
- con.data_consolidated += self.data_consolidated
- self.set_benchmark(security.symbol)
-
- def data_consolidated(self, sender, bar):
- quantity = math.floor((self.portfolio.cash + self.portfolio.total_fees) / abs(bar.value + 1))
- btc_qnty = float(self.portfolio["BTCUSD"].quantity)
-
- if not self.portfolio.invested:
- self.order("BTCUSD", quantity)
- elif btc_qnty == quantity:
- self.order("BTCUSD", 0.1)
- elif btc_qnty == quantity + 0.1:
- self.order("BTCUSD", 0.01)
- elif btc_qnty == quantity + 0.11:
- self.order("BTCUSD", -0.02)
- elif btc_qnty == quantity + 0.09:
- # should fail (below minimum order quantity)
- self.order("BTCUSD", 0.00001)
- self.set_holdings("BTCUSD", -2.0)
- self.set_holdings("BTCUSD", 2.0)
- self.quit()
diff --git a/fincept-qt/scripts/strategies/FuncRiskFreeRateInterestRateModelWithPythonLambda.py b/fincept-qt/scripts/strategies/FuncRiskFreeRateInterestRateModelWithPythonLambda.py
deleted file mode 100644
index d10676ad7..000000000
--- a/fincept-qt/scripts/strategies/FuncRiskFreeRateInterestRateModelWithPythonLambda.py
+++ /dev/null
@@ -1,29 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-1C8EF029
-# Category: Risk Management
-# Description: Asserts we can use a Python lambda function as a FuncRiskFreeRateInterestRateModel
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Asserts we can use a Python lambda function as a FuncRiskFreeRateInterestRateModel
-### </summary>
-class FuncRiskFreeRateInterestRateModelWithPythonLambda(QCAlgorithm):
- def initialize(self):
- self.set_start_date(2020, 5, 28)
- self.set_end_date(2020, 6, 28)
-
- self.add_equity("SPY", Resolution.DAILY)
- self.model = FuncRiskFreeRateInterestRateModel(lambda dt: 1 if dt.date != datetime(2020, 5, 28) else 0)
-
- def on_data(self, slice):
- if self.time.date == datetime(2020, 5, 28) and self.model.get_interest_rate(self.time) != 0:
- raise Exception(f"Risk free interest rate should be 0, but was {self.model.get_interest_rate(self.time)}")
- elif self.time.date != datetime(2020, 5, 28) and self.model.get_interest_rate(self.time) != 1:
- raise Exception(f"Risk free interest rate should be 1, but was {self.model.get_interest_rate(self.time)}")
diff --git a/fincept-qt/scripts/strategies/FundamentalCustomSelectionTimeRegressionAlgorithm.py b/fincept-qt/scripts/strategies/FundamentalCustomSelectionTimeRegressionAlgorithm.py
deleted file mode 100644
index 2b9d533c8..000000000
--- a/fincept-qt/scripts/strategies/FundamentalCustomSelectionTimeRegressionAlgorithm.py
+++ /dev/null
@@ -1,83 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-874367FD
-# Category: Regression Test
-# Description: Regression test algorithm for scheduled universe selection GH 3890
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Regression test algorithm for scheduled universe selection GH 3890
-### </summary>
-class FundamentalCustomSelectionTimeRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self):
- '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
-
- self._month_start_selection = 0
- self._month_end_selection = 0
- self._specific_date_selection = 0
- self._symbol = Symbol.create("SPY", SecurityType.EQUITY, Market.USA)
-
- self.set_start_date(2014, 3, 25)
- self.set_end_date(2014, 5, 10)
- self.universe_settings.resolution = Resolution.DAILY
-
- # Test use case A
- self.add_universe(self.date_rules.month_start(), self.selection_function__month_start)
-
- # Test use case B
- other_settings = UniverseSettings(self.universe_settings)
- other_settings.schedule.on(self.date_rules.month_end())
-
- self.add_universe(FundamentalUniverse.usa(self.selection_function__month_end, other_settings))
-
- # Test use case C
- self.universe_settings.schedule.on(self.date_rules.on(datetime(2014, 5, 9)))
- self.add_universe(FundamentalUniverse.usa(self.selection_function__specific_date))
-
- def selection_function__specific_date(self, coarse):
- self._specific_date_selection += 1
- if self.time != datetime(2014, 5, 9):
- raise ValueError("SelectionFunction_SpecificDate unexpected selection: " + str(self.time))
- return [ self._symbol ]
-
- def selection_function__month_start(self, coarse):
- self._month_start_selection += 1
- if self._month_start_selection == 1:
- if self.time != self.start_date:
- raise ValueError("Month Start Unexpected initial selection: " + str(self.time))
- elif self.time != datetime(2014, 4, 1) and self.time != datetime(2014, 5, 1):
- raise ValueError("Month Start unexpected selection: " + str(self.time))
- return [ self._symbol ]
-
- def selection_function__month_end(self, coarse):
- self._month_end_selection += 1
- if self._month_end_selection == 1:
- if self.time != self.start_date:
- raise ValueError("Month End unexpected initial selection: " + str(self.time))
- elif self.time != datetime(2014, 3, 31) and self.time != datetime(2014, 4, 30):
- raise ValueError("Month End unexpected selection: " + str(self.time))
- return [ self._symbol ]
-
- def on_data(self, data):
- '''on_data event is the primary entry point for your algorithm. Each new data point will be pumped in here.
-
- Arguments:
- data: Slice object keyed by symbol containing the stock data
- '''
- if not self.portfolio.invested:
- self.set_holdings(self._symbol, 1)
-
- def on_end_of_algorithm(self):
- if self._month_end_selection != 3:
- raise ValueError("Month End unexpected selection count: " + str(self._month_end_selection))
- if self._month_start_selection != 3:
- raise ValueError("Month Start unexpected selection count: " + str(self._month_start_selection))
- if self._specific_date_selection != 1:
- raise ValueError("Specific date unexpected selection count: " + str(self._month_start_selection))
diff --git a/fincept-qt/scripts/strategies/FundamentalRegressionAlgorithm.py b/fincept-qt/scripts/strategies/FundamentalRegressionAlgorithm.py
deleted file mode 100644
index 5382a4f2c..000000000
--- a/fincept-qt/scripts/strategies/FundamentalRegressionAlgorithm.py
+++ /dev/null
@@ -1,131 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-4A7607D6
-# Category: Regression Test
-# Description: Demonstration of how to define a universe using the fundamental data
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Demonstration of how to define a universe using the fundamental data
-### </summary>
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="universes" />
-### <meta name="tag" content="coarse universes" />
-### <meta name="tag" content="regression test" />
-class FundamentalRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2014, 3, 26)
- self.set_end_date(2014, 4, 7)
-
- self.universe_settings.resolution = Resolution.DAILY
-
- self._universe = self.add_universe(self.selection_function)
-
- # before we add any symbol
- self.assert_fundamental_universe_data()
-
- self.add_equity("SPY")
- self.add_equity("AAPL")
-
- # Request fundamental data for symbols at current algorithm time
- ibm = Symbol.create("IBM", SecurityType.EQUITY, Market.USA)
- ibm_fundamental = self.fundamentals(ibm)
- if self.time != self.start_date or self.time != ibm_fundamental.end_time:
- raise ValueError(f"Unexpected Fundamental time {ibm_fundamental.end_time}")
- if ibm_fundamental.price == 0:
- raise ValueError(f"Unexpected Fundamental IBM price!")
- nb = Symbol.create("NB", SecurityType.EQUITY, Market.USA)
- fundamentals = self.fundamentals([ nb, ibm ])
- if len(fundamentals) != 2:
- raise ValueError(f"Unexpected Fundamental count {len(fundamentals)}! Expected 2")
-
- # Request historical fundamental data for symbols
- history = self.history(Fundamental, timedelta(days=2))
- if len(history) != 4:
- raise ValueError(f"Unexpected Fundamental history count {len(history)}! Expected 4")
-
- for ticker in [ "AAPL", "SPY" ]:
- data = history.loc[ticker]
- if data["value"][0] == 0:
- raise ValueError(f"Unexpected {data} fundamental data")
- if Object.reference_equals(data.earningreports.iloc[0], data.earningreports.iloc[1]):
- raise ValueError(f"Unexpected fundamental data instance duplication")
- if data.earningreports.iloc[0]._time_provider.get_utc_now() == data.earningreports.iloc[1]._time_provider.get_utc_now():
- raise ValueError(f"Unexpected fundamental data instance duplication")
-
- self.assert_fundamental_universe_data()
-
- self.changes = None
- self.number_of_symbols_fundamental = 2
-
- def assert_fundamental_universe_data(self):
- # Case A
- universe_data = self.history(self._universe.data_type, [self._universe.symbol], timedelta(days=2), flatten=True)
- self.assert_fundamental_history(universe_data, "A")
-
- # Case B (sugar on A)
- universe_data_per_time = self.history(self._universe, timedelta(days=2), flatten=True)
- self.assert_fundamental_history(universe_data_per_time, "B")
-
- # Case C: Passing through the unvierse type and symbol
- enumerable_of_data_dictionary = self.history[self._universe.data_type]([self._universe.symbol], 100)
- for selection_collection_for_a_day in enumerable_of_data_dictionary:
- self.assert_fundamental_enumerator(selection_collection_for_a_day[self._universe.symbol], "C")
-
- def assert_fundamental_history(self, df, case_name):
- dates = df.index.get_level_values('time').unique()
- if dates.shape[0] != 2:
- raise ValueError(f"Unexpected Fundamental universe dates count {dates.shape[0]}! Expected 2")
-
- for date in dates:
- sub_df = df.loc[date]
- if sub_df.shape[0] < 7000:
- raise ValueError(f"Unexpected historical Fundamentals data count {sub_df.shape[0]} case {case_name}! Expected > 7000")
-
- def assert_fundamental_enumerator(self, enumerable, case_name):
- data_point_count = 0
- for fundamental in enumerable:
- data_point_count += 1
- if type(fundamental) is not Fundamental:
- raise ValueError(f"Unexpected Fundamentals data type {type(fundamental)} case {case_name}! {str(fundamental)}")
- if data_point_count < 7000:
- raise ValueError(f"Unexpected historical Fundamentals data count {data_point_count} case {case_name}! Expected > 7000")
-
- # return a list of three fixed symbol objects
- def selection_function(self, fundamental):
- # sort descending by daily dollar volume
- sorted_by_dollar_volume = sorted([x for x in fundamental if x.price > 1],
- key=lambda x: x.dollar_volume, reverse=True)
-
- # sort descending by P/E ratio
- sorted_by_pe_ratio = sorted(sorted_by_dollar_volume, key=lambda x: x.valuation_ratios.pe_ratio, reverse=True)
-
- # take the top entries from our sorted collection
- return [ x.symbol for x in sorted_by_pe_ratio[:self.number_of_symbols_fundamental] ]
-
- def on_data(self, data):
- # if we have no changes, do nothing
- if self.changes is None: return
-
- # liquidate removed securities
- for security in self.changes.removed_securities:
- if security.invested:
- self.liquidate(security.symbol)
- self.debug("Liquidated Stock: " + str(security.symbol.value))
-
- # we want 50% allocation in each security in our universe
- for security in self.changes.added_securities:
- self.set_holdings(security.symbol, 0.02)
-
- self.changes = None
-
- # this event fires whenever we have changes to our universe
- def on_securities_changed(self, changes):
- self.changes = changes
diff --git a/fincept-qt/scripts/strategies/FundamentalUniverseSelectionAlgorithm.py b/fincept-qt/scripts/strategies/FundamentalUniverseSelectionAlgorithm.py
deleted file mode 100644
index 10c5aa85c..000000000
--- a/fincept-qt/scripts/strategies/FundamentalUniverseSelectionAlgorithm.py
+++ /dev/null
@@ -1,60 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-0A8C8781
-# Category: Universe Selection
-# Description: Sector rotation strategy inspired by fundamental universe selection.
-# Rotates between SPY and AAPL based on relative momentum. Holds the stronger
-# performer over the past 20 days. Rebalances weekly.
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-class FundamentalUniverseSelectionAlgorithm(QCAlgorithm):
- """Relative momentum rotation: holds the stronger of SPY vs AAPL."""
-
- def initialize(self):
- self.set_start_date(2023, 1, 1)
- self.set_end_date(2024, 1, 1)
- self.set_cash(100000)
-
- self.sym_a = "SPY"
- self.sym_b = "AAPL"
-
- self.add_equity(self.sym_a, Resolution.DAILY)
- self.add_equity(self.sym_b, Resolution.DAILY)
-
- self._sma_a = self.sma(self.sym_a, 20, Resolution.DAILY)
- self._sma_b = self.sma(self.sym_b, 20, Resolution.DAILY)
-
- self._last_trade_week = -1
-
- def on_data(self, data):
- if not self._sma_a.is_ready or not self._sma_b.is_ready:
- return
-
- # Rebalance weekly
- current_week = self.time.isocalendar()[1]
- if current_week == self._last_trade_week:
- return
- self._last_trade_week = current_week
-
- if self.sym_a not in data or self.sym_b not in data:
- return
-
- # Relative strength: price / SMA ratio
- rs_a = data[self.sym_a].close / self._sma_a.current.value if self._sma_a.current.value > 0 else 0
- rs_b = data[self.sym_b].close / self._sma_b.current.value if self._sma_b.current.value > 0 else 0
-
- # Hold the one with stronger momentum
- if rs_a > rs_b:
- if self.portfolio[self.sym_b].invested:
- self.liquidate(self.sym_b)
- self.set_holdings(self.sym_a, 0.95)
- else:
- if self.portfolio[self.sym_a].invested:
- self.liquidate(self.sym_a)
- self.set_holdings(self.sym_b, 0.95)
diff --git a/fincept-qt/scripts/strategies/FundamentalUniverseSelectionRegressionAlgorithm.py b/fincept-qt/scripts/strategies/FundamentalUniverseSelectionRegressionAlgorithm.py
deleted file mode 100644
index 51db5e834..000000000
--- a/fincept-qt/scripts/strategies/FundamentalUniverseSelectionRegressionAlgorithm.py
+++ /dev/null
@@ -1,48 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-19976618
-# Category: Universe Selection
-# Description: Dual momentum strategy with monthly rebalancing. Compares
-# 20-day rate of change between SPY and trend. Goes long when momentum
-# is positive, flat otherwise. Monthly rebalance frequency.
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-class FundamentalUniverseSelectionRegressionAlgorithm(QCAlgorithm):
- """Monthly rebalancing momentum strategy."""
-
- def initialize(self):
- self.set_start_date(2023, 1, 1)
- self.set_end_date(2024, 1, 1)
- self.set_cash(100000)
-
- self.symbol = "SPY"
- self.add_equity(self.symbol, Resolution.DAILY)
-
- self._momp = self.momp(self.symbol, 20, Resolution.DAILY)
- self._last_month = -1
-
- def on_data(self, data):
- if not self._momp.is_ready:
- return
- if self.symbol not in data:
- return
-
- current_month = self.time.month
- if current_month == self._last_month:
- return
- self._last_month = current_month
-
- mom_val = self._momp.current.value
-
- if mom_val > 0:
- if not self.portfolio.invested:
- self.set_holdings(self.symbol, 1)
- else:
- if self.portfolio.invested:
- self.liquidate()
diff --git a/fincept-qt/scripts/strategies/FutureContractsExtendedMarketHoursRegressionAlgorithm.py b/fincept-qt/scripts/strategies/FutureContractsExtendedMarketHoursRegressionAlgorithm.py
deleted file mode 100644
index d8e163fe9..000000000
--- a/fincept-qt/scripts/strategies/FutureContractsExtendedMarketHoursRegressionAlgorithm.py
+++ /dev/null
@@ -1,63 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-E85797B9
-# Category: Futures
-# Description: This regression algorithm asserts that futures have data at extended market hours when this is enabled
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### This regression algorithm asserts that futures have data at extended market hours when this is enabled.
-### </summary>
-class FutureContractsExtendedMarketHoursRegressionAlgorithm(QCAlgorithm):
- def initialize(self):
- self.set_start_date(2013, 10, 6)
- self.set_end_date(2013, 10, 11)
-
- es_future_symbol = Symbol.create_future(Futures.Indices.SP_500_E_MINI, Market.CME, DateTime(2013, 12, 20))
- self._es = self.add_future_contract(es_future_symbol, Resolution.HOUR, fill_forward=True, extended_market_hours=True)
-
- gc_future_symbol = Symbol.create_future(Futures.Metals.GOLD, Market.COMEX, DateTime(2013, 10, 29))
- self._gc = self.add_future_contract(gc_future_symbol, Resolution.HOUR, fill_forward=True, extended_market_hours=False)
-
- self._es_ran_on_regular_hours = False
- self._es_ran_on_extended_hours = False
- self._gc_ran_on_regular_hours = False
- self._gc_ran_on_extended_hours = False
-
- def on_data(self, slice):
- slice_symbols = set(slice.keys())
- slice_symbols.update(slice.bars.keys())
- slice_symbols.update(slice.ticks.keys())
- slice_symbols.update(slice.quote_bars.keys())
- slice_symbols.update([x.canonical for x in slice_symbols])
-
- es_is_in_regular_hours = self._es.exchange.hours.is_open(self.time, False)
- es_is_in_extended_hours = not es_is_in_regular_hours and self._es.exchange.hours.is_open(self.time, True)
- slice_has_es_data = self._es.symbol in slice_symbols
- self._es_ran_on_regular_hours |= es_is_in_regular_hours and slice_has_es_data
- self._es_ran_on_extended_hours |= es_is_in_extended_hours and slice_has_es_data
-
- gc_is_in_regular_hours = self._gc.exchange.hours.is_open(self.time, False)
- gc_is_in_extended_hours = not gc_is_in_regular_hours and self._gc.exchange.hours.is_open(self.time, True)
- slice_has_gc_data = self._gc.symbol in slice_symbols
- self._gc_ran_on_regular_hours |= gc_is_in_regular_hours and slice_has_gc_data
- self._gc_ran_on_extended_hours |= gc_is_in_extended_hours and slice_has_gc_data
-
- def on_end_of_algorithm(self):
- if not self._es_ran_on_regular_hours:
- raise Exception(f"Algorithm should have run on regular hours for {self._es.symbol} future, which enabled extended market hours")
-
- if not self._es_ran_on_extended_hours:
- raise Exception(f"Algorithm should have run on extended hours for {self._es.symbol} future, which enabled extended market hours")
-
- if not self._gc_ran_on_regular_hours:
- raise Exception(f"Algorithm should have run on regular hours for {self._gc.symbol} future, which did not enable extended market hours")
-
- if self._gc_ran_on_extended_hours:
- raise Exception(f"Algorithm should have not run on extended hours for {self._gc.symbol} future, which did not enable extended market hours")
diff --git a/fincept-qt/scripts/strategies/FutureOptionBuySellCallIntradayRegressionAlgorithm.py b/fincept-qt/scripts/strategies/FutureOptionBuySellCallIntradayRegressionAlgorithm.py
deleted file mode 100644
index 11bbf15fa..000000000
--- a/fincept-qt/scripts/strategies/FutureOptionBuySellCallIntradayRegressionAlgorithm.py
+++ /dev/null
@@ -1,47 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-1855F876
-# Category: Options
-# Description: Intraday-inspired reversal strategy. Uses short-period RSI (7)
-# combined with EMA filter. Buys on deep oversold (RSI < 25) when above
-# EMA. Quick exit on RSI > 55 for short-term mean reversion captures.
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-class FutureOptionBuySellCallIntradayRegressionAlgorithm(QCAlgorithm):
- """Short-period RSI mean-reversion with EMA filter."""
-
- def initialize(self):
- self.set_start_date(2023, 1, 1)
- self.set_end_date(2024, 1, 1)
- self.set_cash(100000)
-
- self.symbol = "SPY"
- self.add_equity(self.symbol, Resolution.DAILY)
-
- self._rsi = self.rsi(self.symbol, 7, Resolution.DAILY)
- self._ema = self.ema(self.symbol, 50, Resolution.DAILY)
-
- def on_data(self, data):
- if not self._rsi.is_ready or not self._ema.is_ready:
- return
- if self.symbol not in data:
- return
-
- price = data[self.symbol].close
- rsi_val = self._rsi.current.value
- ema_val = self._ema.current.value
-
- if not self.portfolio.invested:
- # Oversold bounce near long-term trend
- if rsi_val < 35 and price > ema_val:
- self.set_holdings(self.symbol, 1)
- else:
- # Quick exit on RSI recovery or trend break
- if rsi_val > 65 or price < ema_val:
- self.liquidate()
diff --git a/fincept-qt/scripts/strategies/FutureOptionCallITMExpiryRegressionAlgorithm.py b/fincept-qt/scripts/strategies/FutureOptionCallITMExpiryRegressionAlgorithm.py
deleted file mode 100644
index c468acafe..000000000
--- a/fincept-qt/scripts/strategies/FutureOptionCallITMExpiryRegressionAlgorithm.py
+++ /dev/null
@@ -1,119 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-DE2ACA2C
-# Category: Options
-# Description: This regression algorithm tests In The Money (ITM) future option expiry for calls. We expect 3 orders from the algori...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### This regression algorithm tests In The Money (ITM) future option expiry for calls.
-### We expect 3 orders from the algorithm, which are:
-###
-### * Initial entry, buy ES Call Option (expiring ITM)
-### * Option exercise, receiving ES future contracts
-### * Future contract liquidation, due to impending expiry
-###
-### Additionally, we test delistings for future options and assert that our
-### portfolio holdings reflect the orders the algorithm has submitted.
-### </summary>
-class FutureOptionCallITMExpiryRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2020, 1, 5)
- self.set_end_date(2020, 6, 30)
-
- self.es19m20 = self.add_future_contract(
- Symbol.create_future(
- Futures.Indices.SP_500_E_MINI,
- Market.CME,
- datetime(2020, 6, 19)
- ),
- Resolution.MINUTE).symbol
-
- # Select a future option expiring ITM, and adds it to the algorithm.
- self.es_option = self.add_future_option_contract(
- list(
- sorted([x for x in self.option_chain(self.es19m20) if x.id.strike_price <= 3200.0 and x.id.option_right == OptionRight.CALL],
- key=lambda x: x.id.strike_price, reverse=True)
- )[0], Resolution.MINUTE).symbol
-
- self.expected_contract = Symbol.create_option(self.es19m20, Market.CME, OptionStyle.AMERICAN, OptionRight.CALL, 3200.0, datetime(2020, 6, 19))
- if self.es_option != self.expected_contract:
- raise AssertionError(f"Contract {self.expected_contract} was not found in the chain")
-
- self.schedule.on(self.date_rules.tomorrow, self.time_rules.after_market_open(self.es19m20, 1), self.schedule_callback)
-
- def schedule_callback(self):
- self.market_order(self.es_option, 1)
-
- def on_data(self, data: Slice):
- # Assert delistings, so that we can make sure that we receive the delisting warnings at
- # the expected time. These assertions detect bug #4872
- for delisting in data.delistings.values():
- if delisting.type == DelistingType.WARNING:
- if delisting.time != datetime(2020, 6, 19):
- raise AssertionError(f"Delisting warning issued at unexpected date: {delisting.time}")
- elif delisting.type == DelistingType.DELISTED:
- if delisting.time != datetime(2020, 6, 20):
- raise AssertionError(f"Delisting happened at unexpected date: {delisting.time}")
-
- def on_order_event(self, order_event: OrderEvent):
- if order_event.status != OrderStatus.FILLED:
- # There's lots of noise with OnOrderEvent, but we're only interested in fills.
- return
-
- if not self.securities.contains_key(order_event.symbol):
- raise AssertionError(f"Order event Symbol not found in Securities collection: {order_event.symbol}")
-
- security = self.securities[order_event.symbol]
- if security.symbol == self.es19m20:
- self.assert_future_option_order_exercise(order_event, security, self.securities[self.expected_contract])
- elif security.symbol == self.expected_contract:
- # Expected contract is ES19H21 Call Option expiring ITM @ 3250
- self.assert_future_option_contract_order(order_event, security)
- else:
- raise AssertionError(f"Received order event for unknown Symbol: {order_event.symbol}")
-
- self.log(f"{self.time} -- {order_event.symbol} :: Price: {self.securities[order_event.symbol].holdings.price} Qty: {self.securities[order_event.symbol].holdings.quantity} Direction: {order_event.direction} Msg: {order_event.message}")
-
- def assert_future_option_order_exercise(self, order_event: OrderEvent, future: Security, option_contract: Security):
- expected_liquidation_time_utc = datetime(2020, 6, 20, 4, 0, 0)
-
- if order_event.direction == OrderDirection.SELL and future.holdings.quantity != 0:
- # We expect the contract to have been liquidated immediately
- raise AssertionError(f"Did not liquidate existing holdings for Symbol {future.symbol}")
- if order_event.direction == OrderDirection.SELL and order_event.utc_time.replace(tzinfo=None) != expected_liquidation_time_utc:
- raise AssertionError(f"Liquidated future contract, but not at the expected time. Expected: {expected_liquidation_time_utc} - found {order_event.utc_time.replace(tzinfo=None)}")
-
- # No way to detect option exercise orders or any other kind of special orders
- # other than matching strings, for now.
- if "Option Exercise" in order_event.message:
- if order_event.fill_price != 3200.0:
- raise AssertionError("Option did not exercise at expected strike price (3200)")
-
- if future.holdings.quantity != 1:
- # Here, we expect to have some holdings in the underlying, but not in the future option anymore.
- raise AssertionError(f"Exercised option contract, but we have no holdings for Future {future.symbol}")
-
- if option_contract.holdings.quantity != 0:
- raise AssertionError(f"Exercised option contract, but we have holdings for Option contract {option_contract.symbol}")
-
- def assert_future_option_contract_order(self, order_event: OrderEvent, option: Security):
- if order_event.direction == OrderDirection.BUY and option.holdings.quantity != 1:
- raise AssertionError(f"No holdings were created for option contract {option.symbol}")
-
- if order_event.direction == OrderDirection.SELL and option.holdings.quantity != 0:
- raise AssertionError(f"Holdings were found after a filled option exercise")
-
- if "Exercise" in order_event.message and option.holdings.quantity != 0:
- raise AssertionError(f"Holdings were found after exercising option contract {option.symbol}")
-
- def on_end_of_algorithm(self):
- if self.portfolio.invested:
- raise AssertionError(f"Expected no holdings at end of algorithm, but are invested in: {', '.join([str(i.id) for i in self.portfolio.keys()])}")
diff --git a/fincept-qt/scripts/strategies/FutureOptionCallOTMExpiryRegressionAlgorithm.py b/fincept-qt/scripts/strategies/FutureOptionCallOTMExpiryRegressionAlgorithm.py
deleted file mode 100644
index 148c1da15..000000000
--- a/fincept-qt/scripts/strategies/FutureOptionCallOTMExpiryRegressionAlgorithm.py
+++ /dev/null
@@ -1,111 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-B4342086
-# Category: Options
-# Description: This regression algorithm tests Out of The Money (OTM) future option expiry for calls. We expect 2 orders from the al...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### This regression algorithm tests Out of The Money (OTM) future option expiry for calls.
-### We expect 2 orders from the algorithm, which are:
-###
-### * Initial entry, buy ES Call Option (expiring OTM)
-### - contract expires worthless, not exercised, so never opened a position in the underlying
-###
-### * Liquidation of worthless ES call option (expiring OTM)
-###
-### Additionally, we test delistings for future options and assert that our
-### portfolio holdings reflect the orders the algorithm has submitted.
-### </summary>
-### <remarks>
-### Total Trades in regression algorithm should be 1, but expiration is counted as a trade.
-### See related issue: https://github.com/QuantConnect/Lean/issues/4854
-### </remarks>
-class FutureOptionCallOTMExpiryRegressionAlgorithm(QCAlgorithm):
- def initialize(self):
- self.set_start_date(2020, 1, 5)
- self.set_end_date(2020, 6, 30)
-
- self.es19m20 = self.add_future_contract(
- Symbol.create_future(
- Futures.Indices.SP_500_E_MINI,
- Market.CME,
- datetime(2020, 6, 19)),
- Resolution.MINUTE).symbol
-
- # Select a future option expiring ITM, and adds it to the algorithm.
- self.es_option = self.add_future_option_contract(
- list(
- sorted(
- [x for x in self.option_chain(self.es19m20)
- if x.id.strike_price >= 3300.0 and x.id.option_right == OptionRight.CALL],
- key=lambda x: x.id.strike_price
- )
- )[0], Resolution.MINUTE).symbol
-
- self.expected_contract = Symbol.create_option(self.es19m20, Market.CME, OptionStyle.AMERICAN, OptionRight.CALL, 3300.0, datetime(2020, 6, 19))
- if self.es_option != self.expected_contract:
- raise AssertionError(f"Contract {self.expected_contract} was not found in the chain")
-
- # Place order after regular market opens
- self.schedule.on(self.date_rules.tomorrow, self.time_rules.after_market_open(self.es19m20, 1), self.scheduled_market_order)
-
- def scheduled_market_order(self):
- self.market_order(self.es_option, 1)
-
- def on_data(self, data: Slice):
- # Assert delistings, so that we can make sure that we receive the delisting warnings at
- # the expected time. These assertions detect bug #4872
- for delisting in data.delistings.values():
- if delisting.type == DelistingType.WARNING:
- if delisting.time != datetime(2020, 6, 19):
- raise AssertionError(f"Delisting warning issued at unexpected date: {delisting.time}")
-
- if delisting.type == DelistingType.DELISTED:
- if delisting.time != datetime(2020, 6, 20):
- raise AssertionError(f"Delisting happened at unexpected date: {delisting.time}")
-
-
- def on_order_event(self, order_event: OrderEvent):
- if order_event.status != OrderStatus.FILLED:
- # There's lots of noise with OnOrderEvent, but we're only interested in fills.
- return
-
- if not self.securities.contains_key(order_event.symbol):
- raise AssertionError(f"Order event Symbol not found in Securities collection: {order_event.symbol}")
-
- security = self.securities[order_event.symbol]
- if security.symbol == self.es19m20:
- raise AssertionError("Invalid state: did not expect a position for the underlying to be opened, since this contract expires OTM")
-
- # Expected contract is ES19M20 Call Option expiring OTM @ 3300
- if (security.symbol == self.expected_contract):
- self.assert_future_option_contract_order(order_event, security)
- else:
- raise AssertionError(f"Received order event for unknown Symbol: {order_event.symbol}")
-
- self.log(f"{order_event}")
-
-
- def assert_future_option_contract_order(self, order_event: OrderEvent, option: Security):
- if order_event.direction == OrderDirection.BUY and option.holdings.quantity != 1:
- raise AssertionError(f"No holdings were created for option contract {option.symbol}")
-
- if order_event.direction == OrderDirection.SELL and option.holdings.quantity != 0:
- raise AssertionError("Holdings were found after a filled option exercise")
-
- if order_event.direction == OrderDirection.SELL and "OTM" not in order_event.message:
- raise AssertionError("Contract did not expire OTM")
-
- if "Exercise" in order_event.message:
- raise AssertionError("Exercised option, even though it expires OTM")
-
- def on_end_of_algorithm(self):
- if self.portfolio.invested:
- raise AssertionError(f"Expected no holdings at end of algorithm, but are invested in: {', '.join([str(i.id) for i in self.portfolio.keys()])}")
diff --git a/fincept-qt/scripts/strategies/FutureOptionDailyRegressionAlgorithm.py b/fincept-qt/scripts/strategies/FutureOptionDailyRegressionAlgorithm.py
deleted file mode 100644
index e0c89cd68..000000000
--- a/fincept-qt/scripts/strategies/FutureOptionDailyRegressionAlgorithm.py
+++ /dev/null
@@ -1,44 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-16536530
-# Category: Options
-# Description: Daily momentum strategy inspired by futures options daily patterns.
-# Uses MACD histogram as primary signal. Buys on positive histogram crossover,
-# sells on negative crossover. Simple daily resolution trend capture.
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-class FutureOptionDailyRegressionAlgorithm(QCAlgorithm):
- """MACD histogram crossover strategy."""
-
- def initialize(self):
- self.set_start_date(2023, 1, 1)
- self.set_end_date(2024, 1, 1)
- self.set_cash(100000)
-
- self.symbol = "SPY"
- self.add_equity(self.symbol, Resolution.DAILY)
-
- self._macd = self.macd(self.symbol, 12, 26, 9, Resolution.DAILY)
- self._prev_histogram = 0
-
- def on_data(self, data):
- if not self._macd.is_ready:
- return
- if self.symbol not in data:
- return
-
- histogram = self._macd.current.value - self._macd.signal.current.value
- crossed_up = self._prev_histogram <= 0 and histogram > 0
- crossed_down = self._prev_histogram >= 0 and histogram < 0
- self._prev_histogram = histogram
-
- if not self.portfolio.invested and crossed_up:
- self.set_holdings(self.symbol, 1)
- elif self.portfolio.invested and crossed_down:
- self.liquidate()
diff --git a/fincept-qt/scripts/strategies/FutureOptionHourlyRegressionAlgorithm.py b/fincept-qt/scripts/strategies/FutureOptionHourlyRegressionAlgorithm.py
deleted file mode 100644
index e3704832c..000000000
--- a/fincept-qt/scripts/strategies/FutureOptionHourlyRegressionAlgorithm.py
+++ /dev/null
@@ -1,66 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-BC31D77F
-# Category: Options
-# Description: This regression algorithm tests using FutureOptions daily resolution
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### This regression algorithm tests using FutureOptions daily resolution
-### </summary>
-class FutureOptionHourlyRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2012, 1, 3)
- self.set_end_date(2012, 1, 4)
- resolution = Resolution.HOUR
-
- # Add our underlying future contract
- self.dc = self.add_future_contract(
- Symbol.create_future(
- Futures.Dairy.CLASS_III_MILK,
- Market.CME,
- datetime(2012, 4, 1)
- ),
- resolution).symbol
-
- # Attempt to fetch a specific ITM future option contract
- dc_options = [
- self.add_future_option_contract(x, resolution).symbol for x in (self.option_chain_provider.get_option_contract_list(self.dc, self.time)) if x.id.strike_price == 17 and x.id.option_right == OptionRight.CALL
- ]
- self.dc_option = dc_options[0]
-
- # Validate it is the expected contract
- expected_contract = Symbol.create_option(self.dc, Market.CME, OptionStyle.AMERICAN, OptionRight.CALL, 17, datetime(2012, 4, 1))
- if self.dc_option != expected_contract:
- raise AssertionError(f"Contract {self.dc_option} was not the expected contract {expected_contract}")
-
- # Schedule a purchase of this contract at noon
- self.schedule.on(self.date_rules.today, self.time_rules.noon, self.schedule_callback_buy)
-
- # Schedule liquidation at 2pm when the market is open
- self.schedule.on(self.date_rules.today, self.time_rules.at(14,0,0), self.schedule_callback_liquidate)
-
- def schedule_callback_buy(self):
- self.ticket = self.market_order(self.dc_option, 1)
-
- def on_data(self, slice):
- # Assert we are only getting data at 7PM (12AM UTC)
- if slice.time.minute != 0:
- raise AssertionError(f"Expected data only on hourly intervals; instead was {slice.time}")
-
- def schedule_callback_liquidate(self):
- self.liquidate()
-
- def on_end_of_algorithm(self):
- if self.portfolio.invested:
- raise AssertionError(f"Expected no holdings at end of algorithm, but are invested in: {', '.join([str(i.id) for i in self.portfolio.keys()])}")
-
- if self.ticket.status != OrderStatus.FILLED:
- raise AssertionError("Future option order failed to fill correctly")
diff --git a/fincept-qt/scripts/strategies/FutureOptionMultipleContractsInDifferentContractMonthsWithSameUnderlyingFutureRegressionAlgorithm.py b/fincept-qt/scripts/strategies/FutureOptionMultipleContractsInDifferentContractMonthsWithSameUnderlyingFutureRegressionAlgorithm.py
deleted file mode 100644
index 80096cc4a..000000000
--- a/fincept-qt/scripts/strategies/FutureOptionMultipleContractsInDifferentContractMonthsWithSameUnderlyingFutureRegressionAlgorithm.py
+++ /dev/null
@@ -1,68 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-AA93FB6A
-# Category: Options
-# Description: This regression test tests for the loading of futures options contracts with a contract month of 2020-03 can live and...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### This regression test tests for the loading of futures options contracts with a contract month of 2020-03 can live
-### and be loaded from the same ZIP file that the 2020-04 contract month Future Option contract lives in.
-### </summary>
-class FutureOptionMultipleContractsInDifferentContractMonthsWithSameUnderlyingFutureRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.expected_symbols = {
- self._create_option(datetime(2020, 3, 26), OptionRight.CALL, 1650.0): False,
- self._create_option(datetime(2020, 3, 26), OptionRight.PUT, 1540.0): False,
- self._create_option(datetime(2020, 2, 25), OptionRight.CALL, 1600.0): False,
- self._create_option(datetime(2020, 2, 25), OptionRight.PUT, 1545.0): False
- }
-
- # Required for FOPs to use extended hours, until GH #6491 is addressed
- self.universe_settings.extended_market_hours = True
-
- self.set_start_date(2020, 1, 4)
- self.set_end_date(2020, 1, 6)
-
- gold_futures = self.add_future("GC", Resolution.MINUTE, Market.COMEX, extended_market_hours=True)
- gold_futures.SetFilter(0, 365)
-
- self.add_future_option(gold_futures.Symbol)
-
- def on_data(self, data: Slice):
- for symbol in data.quote_bars.keys():
- # Check that we are in regular hours, we can place a market order (on extended hours, limit orders should be used)
- if symbol in self.expected_symbols and self.is_in_regular_hours(symbol):
- invested = self.expected_symbols[symbol]
- if not invested:
- self.market_order(symbol, 1)
-
- self.expected_symbols[symbol] = True
-
- def on_end_of_algorithm(self):
- not_encountered = [str(k) for k,v in self.expected_symbols.items() if not v]
- if any(not_encountered):
- raise AggregateException(f"Expected all Symbols encountered and invested in, but the following were not found: {', '.join(not_encountered)}")
-
- if not self.portfolio.invested:
- raise AggregateException("Expected holdings at the end of algorithm, but none were found.")
-
- def is_in_regular_hours(self, symbol):
- return self.securities[symbol].exchange.exchange_open
-
- def _create_option(self, expiry: datetime, option_right: OptionRight, strike_price: float) -> Symbol:
- return Symbol.create_option(
- Symbol.create_future("GC", Market.COMEX, datetime(2020, 4, 28)),
- Market.COMEX,
- OptionStyle.AMERICAN,
- option_right,
- strike_price,
- expiry
- )
diff --git a/fincept-qt/scripts/strategies/FutureOptionPutITMExpiryRegressionAlgorithm.py b/fincept-qt/scripts/strategies/FutureOptionPutITMExpiryRegressionAlgorithm.py
deleted file mode 100644
index af178b0e1..000000000
--- a/fincept-qt/scripts/strategies/FutureOptionPutITMExpiryRegressionAlgorithm.py
+++ /dev/null
@@ -1,118 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-88F9D2E8
-# Category: Options
-# Description: This regression algorithm tests In The Money (ITM) future option expiry for puts. We expect 3 orders from the algorit...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### This regression algorithm tests In The Money (ITM) future option expiry for puts.
-### We expect 3 orders from the algorithm, which are:
-###
-### * Initial entry, buy ES Put Option (expiring ITM) (buy, qty 1)
-### * Option exercise, receiving short ES future contracts (sell, qty -1)
-### * Future contract liquidation, due to impending expiry (buy qty 1)
-###
-### Additionally, we test delistings for future options and assert that our
-### portfolio holdings reflect the orders the algorithm has submitted.
-### </summary>
-class FutureOptionPutITMExpiryRegressionAlgorithm(QCAlgorithm):
- def initialize(self):
- self.set_start_date(2020, 1, 5)
- self.set_end_date(2020, 6, 30)
-
- self.es19m20 = self.add_future_contract(
- Symbol.create_future(
- Futures.Indices.SP_500_E_MINI,
- Market.CME,
- datetime(2020, 6, 19)
- ),
- Resolution.MINUTE).symbol
-
- # Select a future option expiring ITM, and adds it to the algorithm.
- self.es_option = self.add_future_option_contract(
- list(
- sorted([x for x in self.option_chain(self.es19m20) if x.id.strike_price >= 3300.0 and x.id.option_right == OptionRight.PUT],
- key=lambda x: x.id.strike_price)
- )[0], Resolution.MINUTE).symbol
-
- self.expected_contract = Symbol.create_option(self.es19m20, Market.CME, OptionStyle.AMERICAN, OptionRight.PUT, 3300.0, datetime(2020, 6, 19))
- if self.es_option != self.expected_contract:
- raise AssertionError(f"Contract {self.expected_contract} was not found in the chain")
-
- self.schedule.on(self.date_rules.tomorrow, self.time_rules.after_market_open(self.es19m20, 1), self.schedule_callback)
-
- def schedule_callback(self):
- self.market_order(self.es_option, 1)
-
- def on_data(self, data: Slice):
- # Assert delistings, so that we can make sure that we receive the delisting warnings at
- # the expected time. These assertions detect bug #4872
- for delisting in data.delistings.values():
- if delisting.type == DelistingType.WARNING:
- if delisting.time != datetime(2020, 6, 19):
- raise AssertionError(f"Delisting warning issued at unexpected date: {delisting.time}")
- elif delisting.type == DelistingType.DELISTED:
- if delisting.time != datetime(2020, 6, 20):
- raise AssertionError(f"Delisting happened at unexpected date: {delisting.time}")
-
- def on_order_event(self, order_event: OrderEvent):
- if order_event.status != OrderStatus.FILLED:
- # There's lots of noise with OnOrderEvent, but we're only interested in fills.
- return
-
- if not self.securities.contains_key(order_event.symbol):
- raise AssertionError(f"Order event Symbol not found in Securities collection: {order_event.symbol}")
-
- security = self.securities[order_event.symbol]
- if security.symbol == self.es19m20:
- self.assert_future_option_order_exercise(order_event, security, self.securities[self.expected_contract])
- elif security.symbol == self.expected_contract:
- # Expected contract is ES19M20 Call Option expiring ITM @ 3250
- self.assert_future_option_contract_order(order_event, security)
- else:
- raise AssertionError(f"Received order event for unknown Symbol: {order_event.symbol}")
-
- self.log(f"{self.time} -- {order_event.symbol} :: Price: {self.securities[order_event.symbol].holdings.price} Qty: {self.securities[order_event.symbol].holdings.quantity} Direction: {order_event.direction} Msg: {order_event.message}")
-
- def assert_future_option_order_exercise(self, order_event: OrderEvent, future: Security, option_contract: Security):
- expected_liquidation_time_utc = datetime(2020, 6, 20, 4, 0, 0)
-
- if order_event.direction == OrderDirection.BUY and future.holdings.quantity != 0:
- # We expect the contract to have been liquidated immediately
- raise AssertionError(f"Did not liquidate existing holdings for Symbol {future.symbol}")
- if order_event.direction == OrderDirection.BUY and order_event.utc_time.replace(tzinfo=None) != expected_liquidation_time_utc:
- raise AssertionError(f"Liquidated future contract, but not at the expected time. Expected: {expected_liquidation_time_utc} - found {order_event.utc_time.replace(tzinfo=None)}")
-
- # No way to detect option exercise orders or any other kind of special orders
- # other than matching strings, for now.
- if "Option Exercise" in order_event.message:
- if order_event.fill_price != 3300.0:
- raise AssertionError("Option did not exercise at expected strike price (3300)")
-
- if future.holdings.quantity != -1:
- # Here, we expect to have some holdings in the underlying, but not in the future option anymore.
- raise AssertionError(f"Exercised option contract, but we have no holdings for Future {future.symbol}")
-
- if option_contract.holdings.quantity != 0:
- raise AssertionError(f"Exercised option contract, but we have holdings for Option contract {option_contract.symbol}")
-
- def assert_future_option_contract_order(self, order_event: OrderEvent, option: Security):
- if order_event.direction == OrderDirection.BUY and option.holdings.quantity != 1:
- raise AssertionError(f"No holdings were created for option contract {option.symbol}")
-
- if order_event.direction == OrderDirection.SELL and option.holdings.quantity != 0:
- raise AssertionError(f"Holdings were found after a filled option exercise")
-
- if "Exercise" in order_event.message and option.holdings.quantity != 0:
- raise AssertionError(f"Holdings were found after exercising option contract {option.symbol}")
-
- def on_end_of_algorithm(self):
- if self.portfolio.invested:
- raise AssertionError(f"Expected no holdings at end of algorithm, but are invested in: {', '.join([str(i.id) for i in self.portfolio.keys()])}")
diff --git a/fincept-qt/scripts/strategies/FutureOptionPutOTMExpiryRegressionAlgorithm.py b/fincept-qt/scripts/strategies/FutureOptionPutOTMExpiryRegressionAlgorithm.py
deleted file mode 100644
index 5624f321e..000000000
--- a/fincept-qt/scripts/strategies/FutureOptionPutOTMExpiryRegressionAlgorithm.py
+++ /dev/null
@@ -1,109 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-ADF65A2F
-# Category: Options
-# Description: This regression algorithm tests Out of The Money (OTM) future option expiry for puts. We expect 2 orders from the alg...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### This regression algorithm tests Out of The Money (OTM) future option expiry for puts.
-### We expect 2 orders from the algorithm, which are:
-###
-### * Initial entry, buy ES Put Option (expiring OTM)
-### - contract expires worthless, not exercised, so never opened a position in the underlying
-###
-### * Liquidation of worthless ES Put OTM contract
-###
-### Additionally, we test delistings for future options and assert that our
-### portfolio holdings reflect the orders the algorithm has submitted.
-### </summary>
-### <remarks>
-### Total Trades in regression algorithm should be 1, but expiration is counted as a trade.
-### </remarks>
-class FutureOptionPutOTMExpiryRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2020, 1, 5)
- self.set_end_date(2020, 6, 30)
-
- self.es19m20 = self.add_future_contract(
- Symbol.create_future(
- Futures.Indices.SP_500_E_MINI,
- Market.CME,
- datetime(2020, 6, 19)),
- Resolution.MINUTE).symbol
-
- # Select a future option expiring ITM, and adds it to the algorithm.
- self.es_option = self.add_future_option_contract(
- list(
- sorted(
- [x for x in self.option_chain(self.es19m20) if x.id.strike_price <= 3150.0 and x.id.option_right == OptionRight.PUT],
- key=lambda x: x.id.strike_price,
- reverse=True
- )
- )[0], Resolution.MINUTE).symbol
-
- self.expected_contract = Symbol.create_option(self.es19m20, Market.CME, OptionStyle.AMERICAN, OptionRight.PUT, 3150.0, datetime(2020, 6, 19))
- if self.es_option != self.expected_contract:
- raise AssertionError(f"Contract {self.expected_contract} was not found in the chain")
-
- self.schedule.on(self.date_rules.tomorrow, self.time_rules.after_market_open(self.es19m20, 1), self.scheduled_market_order)
-
- def scheduled_market_order(self):
- self.market_order(self.es_option, 1)
-
- def on_data(self, data: Slice):
- # Assert delistings, so that we can make sure that we receive the delisting warnings at
- # the expected time. These assertions detect bug #4872
- for delisting in data.delistings.values():
- if delisting.type == DelistingType.WARNING:
- if delisting.time != datetime(2020, 6, 19):
- raise AssertionError(f"Delisting warning issued at unexpected date: {delisting.time}")
-
- if delisting.type == DelistingType.DELISTED:
- if delisting.time != datetime(2020, 6, 20):
- raise AssertionError(f"Delisting happened at unexpected date: {delisting.time}")
-
- def on_order_event(self, order_event: OrderEvent):
- if order_event.status != OrderStatus.FILLED:
- # There's lots of noise with OnOrderEvent, but we're only interested in fills.
- return
-
- if not self.securities.contains_key(order_event.symbol):
- raise AssertionError(f"Order event Symbol not found in Securities collection: {order_event.symbol}")
-
- security = self.securities[order_event.symbol]
- if security.symbol == self.es19m20:
- raise AssertionError("Invalid state: did not expect a position for the underlying to be opened, since this contract expires OTM")
-
- # Expected contract is ES19M20 Put Option expiring OTM @ 3200
- if (security.symbol == self.expected_contract):
- self.assert_future_option_contract_order(order_event, security)
- else:
- raise AssertionError(f"Received order event for unknown Symbol: {order_event.symbol}")
-
- self.log(f"{order_event}")
-
-
- def assert_future_option_contract_order(self, order_event: OrderEvent, option: Security):
- if order_event.direction == OrderDirection.BUY and option.holdings.quantity != 1:
- raise AssertionError(f"No holdings were created for option contract {option.symbol}")
-
- if order_event.direction == OrderDirection.SELL and option.holdings.quantity != 0:
- raise AssertionError("Holdings were found after a filled option exercise")
-
- if order_event.direction == OrderDirection.SELL and "OTM" not in order_event.message:
- raise AssertionError("Contract did not expire OTM")
-
- if "Exercise" in order_event.message:
- raise AssertionError("Exercised option, even though it expires OTM")
-
- def on_end_of_algorithm(self):
- if self.portfolio.invested:
- raise AssertionError(f"Expected no holdings at end of algorithm, but are invested in: {', '.join([str(i.id) for i in self.portfolio.keys()])}")
diff --git a/fincept-qt/scripts/strategies/FutureOptionShortCallITMExpiryRegressionAlgorithm.py b/fincept-qt/scripts/strategies/FutureOptionShortCallITMExpiryRegressionAlgorithm.py
deleted file mode 100644
index 55de30551..000000000
--- a/fincept-qt/scripts/strategies/FutureOptionShortCallITMExpiryRegressionAlgorithm.py
+++ /dev/null
@@ -1,48 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-129041A8
-# Category: Options
-# Description: Short-term mean reversion strategy inspired by options expiry
-# patterns. Buys on RSI oversold (<35) conditions and sells on overbought
-# (>65) or after 5-day maximum holding period.
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-class FutureOptionShortCallITMExpiryRegressionAlgorithm(QCAlgorithm):
- """Short-term RSI mean-reversion with time-based exit."""
-
- def initialize(self):
- self.set_start_date(2023, 1, 1)
- self.set_end_date(2024, 1, 1)
- self.set_cash(100000)
-
- self.symbol = "SPY"
- self.add_equity(self.symbol, Resolution.DAILY)
-
- self._rsi = self.rsi(self.symbol, 14, Resolution.DAILY)
- self._entry_bar = 0
- self._bar_count = 0
- self._max_hold = 5
-
- def on_data(self, data):
- if not self._rsi.is_ready:
- return
- if self.symbol not in data:
- return
-
- self._bar_count += 1
- rsi_val = self._rsi.current.value
-
- if not self.portfolio.invested:
- if rsi_val < 35:
- self.set_holdings(self.symbol, 1)
- self._entry_bar = self._bar_count
- else:
- bars_held = self._bar_count - self._entry_bar
- if rsi_val > 65 or bars_held >= self._max_hold:
- self.liquidate()
diff --git a/fincept-qt/scripts/strategies/FutureOptionShortCallOTMExpiryRegressionAlgorithm.py b/fincept-qt/scripts/strategies/FutureOptionShortCallOTMExpiryRegressionAlgorithm.py
deleted file mode 100644
index 5d0205fe4..000000000
--- a/fincept-qt/scripts/strategies/FutureOptionShortCallOTMExpiryRegressionAlgorithm.py
+++ /dev/null
@@ -1,101 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-68DA46AE
-# Category: Options
-# Description: This regression algorithm tests Out of The Money (OTM) future option expiry for short calls. We expect 2 orders from ...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### This regression algorithm tests Out of The Money (OTM) future option expiry for short calls.
-### We expect 2 orders from the algorithm, which are:
-###
-### * Initial entry, sell ES Call Option (expiring OTM)
-### - Profit the option premium, since the option was not assigned.
-###
-### * Liquidation of ES call OTM contract on the last trade date
-###
-### Additionally, we test delistings for future options and assert that our
-### portfolio holdings reflect the orders the algorithm has submitted.
-### </summary>
-class FutureOptionShortCallOTMExpiryRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2020, 1, 5)
- self.set_end_date(2020, 6, 30)
-
- self.es19m20 = self.add_future_contract(
- Symbol.create_future(
- Futures.Indices.SP_500_E_MINI,
- Market.CME,
- datetime(2020, 6, 19)),
- Resolution.MINUTE).symbol
-
- # Select a future option expiring ITM, and adds it to the algorithm.
- self.es_option = self.add_future_option_contract(
- list(
- sorted(
- [x for x in self.option_chain(self.es19m20) if x.id.strike_price >= 3400.0 and x.id.option_right == OptionRight.CALL],
- key=lambda x: x.id.strike_price
- )
- )[0], Resolution.MINUTE).symbol
-
- self.expected_contract = Symbol.create_option(self.es19m20, Market.CME, OptionStyle.AMERICAN, OptionRight.CALL, 3400.0, datetime(2020, 6, 19))
- if self.es_option != self.expected_contract:
- raise AssertionError(f"Contract {self.expected_contract} was not found in the chain")
-
- self.schedule.on(self.date_rules.tomorrow, self.time_rules.after_market_open(self.es19m20, 1), self.scheduled_market_order)
-
- def scheduled_market_order(self):
- self.market_order(self.es_option, -1)
-
- def on_data(self, data: Slice):
- # Assert delistings, so that we can make sure that we receive the delisting warnings at
- # the expected time. These assertions detect bug #4872
- for delisting in data.delistings.values():
- if delisting.type == DelistingType.WARNING:
- if delisting.time != datetime(2020, 6, 19):
- raise AssertionError(f"Delisting warning issued at unexpected date: {delisting.time}")
-
- if delisting.type == DelistingType.DELISTED:
- if delisting.time != datetime(2020, 6, 20):
- raise AssertionError(f"Delisting happened at unexpected date: {delisting.time}")
-
- def on_order_event(self, order_event: OrderEvent):
- if order_event.status != OrderStatus.FILLED:
- # There's lots of noise with OnOrderEvent, but we're only interested in fills.
- return
-
- if not self.securities.contains_key(order_event.symbol):
- raise AssertionError(f"Order event Symbol not found in Securities collection: {order_event.symbol}")
-
- security = self.securities[order_event.symbol]
- if security.symbol == self.es19m20:
- raise AssertionError(f"Expected no order events for underlying Symbol {security.symbol}")
-
- if security.symbol == self.expected_contract:
- self.assert_future_option_contract_order(order_event, security)
-
- else:
- raise AssertionError(f"Received order event for unknown Symbol: {order_event.symbol}")
-
- self.log(f"{order_event}")
-
- def assert_future_option_contract_order(self, order_event: OrderEvent, option_contract: Security):
- if order_event.direction == OrderDirection.SELL and option_contract.holdings.quantity != -1:
- raise AssertionError(f"No holdings were created for option contract {option_contract.symbol}")
-
- if order_event.direction == OrderDirection.BUY and option_contract.holdings.quantity != 0:
- raise AssertionError("Expected no options holdings after closing position")
-
- if order_event.is_assignment:
- raise AssertionError(f"Assignment was not expected for {order_event.symbol}")
-
- def on_end_of_algorithm(self):
- if self.portfolio.invested:
- raise AssertionError(f"Expected no holdings at end of algorithm, but are invested in: {', '.join([str(i.id) for i in self.portfolio.keys()])}")
diff --git a/fincept-qt/scripts/strategies/FutureOptionShortPutITMExpiryRegressionAlgorithm.py b/fincept-qt/scripts/strategies/FutureOptionShortPutITMExpiryRegressionAlgorithm.py
deleted file mode 100644
index 3f588ded0..000000000
--- a/fincept-qt/scripts/strategies/FutureOptionShortPutITMExpiryRegressionAlgorithm.py
+++ /dev/null
@@ -1,112 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-97BFC0D6
-# Category: Options
-# Description: This regression algorithm tests In The Money (ITM) future option expiry for short puts. We expect 3 orders from the a...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### This regression algorithm tests In The Money (ITM) future option expiry for short puts.
-### We expect 3 orders from the algorithm, which are:
-###
-### * Initial entry, sell ES Put Option (expiring ITM)
-### * Option assignment, buy 1 contract of the underlying (ES)
-### * Future contract expiry, liquidation (sell 1 ES future)
-###
-### Additionally, we test delistings for future options and assert that our
-### portfolio holdings reflect the orders the algorithm has submitted.
-### </summary>
-class FutureOptionShortPutITMExpiryRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2020, 1, 5)
- self.set_end_date(2020, 6, 30)
-
- self.es19m20 = self.add_future_contract(
- Symbol.create_future(
- Futures.Indices.SP_500_E_MINI,
- Market.CME,
- datetime(2020, 6, 19)),
- Resolution.MINUTE).symbol
-
- # Select a future option expiring ITM, and adds it to the algorithm.
- self.es_option = self.add_future_option_contract(
- list(
- sorted(
- [x for x in self.option_chain(self.es19m20) if x.id.strike_price <= 3400.0 and x.id.option_right == OptionRight.PUT],
- key=lambda x: x.id.strike_price,
- reverse=True
- )
- )[0], Resolution.MINUTE).symbol
-
- self.expected_contract = Symbol.create_option(self.es19m20, Market.CME, OptionStyle.AMERICAN, OptionRight.PUT, 3400.0, datetime(2020, 6, 19))
- if self.es_option != self.expected_contract:
- raise AssertionError(f"Contract {self.expected_contract} was not found in the chain")
-
- self.schedule.on(self.date_rules.tomorrow, self.time_rules.after_market_open(self.es19m20, 1), self.scheduled_market_order)
-
- def scheduled_market_order(self):
- self.market_order(self.es_option, -1)
-
- def on_data(self, data: Slice):
- # Assert delistings, so that we can make sure that we receive the delisting warnings at
- # the expected time. These assertions detect bug #4872
- for delisting in data.delistings.values():
- if delisting.type == DelistingType.WARNING:
- if delisting.time != datetime(2020, 6, 19):
- raise AssertionError(f"Delisting warning issued at unexpected date: {delisting.time}")
-
- if delisting.type == DelistingType.DELISTED:
- if delisting.time != datetime(2020, 6, 20):
- raise AssertionError(f"Delisting happened at unexpected date: {delisting.time}")
-
- def on_order_event(self, order_event: OrderEvent):
- if order_event.status != OrderStatus.FILLED:
- # There's lots of noise with OnOrderEvent, but we're only interested in fills.
- return
-
- if not self.securities.contains_key(order_event.symbol):
- raise AssertionError(f"Order event Symbol not found in Securities collection: {order_event.symbol}")
-
- security = self.securities[order_event.symbol]
- if security.symbol == self.es19m20:
- self.assert_future_option_order_exercise(order_event, security, self.securities[self.expected_contract])
-
- elif security.symbol == self.expected_contract:
- self.assert_future_option_contract_order(order_event, security)
-
- else:
- raise AssertionError(f"Received order event for unknown Symbol: {order_event.symbol}")
-
- self.log(f"{order_event}")
-
- def assert_future_option_order_exercise(self, order_event: OrderEvent, future: Security, option_contract: Security):
- if "Assignment" in order_event.message:
- if order_event.fill_price != 3400.0:
- raise AssertionError("Option was not assigned at expected strike price (3400)")
-
- if order_event.direction != OrderDirection.BUY or future.holdings.quantity != 1:
- raise AssertionError(f"Expected Qty: 1 futures holdings for assigned future {future.symbol}, found {future.holdings.quantity}")
-
- return
-
- if order_event.direction == OrderDirection.SELL and future.holdings.quantity != 0:
- # We buy back the underlying at expiration, so we expect a neutral position then
- raise AssertionError(f"Expected no holdings when liquidating future contract {future.symbol}")
-
- def assert_future_option_contract_order(self, order_event: OrderEvent, option: Security):
- if order_event.direction == OrderDirection.SELL and option.holdings.quantity != -1:
- raise AssertionError(f"No holdings were created for option contract {option.symbol}")
-
- if order_event.is_assignment and option.holdings.quantity != 0:
- raise AssertionError(f"Holdings were found after option contract was assigned: {option.symbol}")
-
- def on_end_of_algorithm(self):
- if self.portfolio.invested:
- raise AssertionError(f"Expected no holdings at end of algorithm, but are invested in: {', '.join([str(i.id) for i in self.portfolio.keys()])}")
diff --git a/fincept-qt/scripts/strategies/FutureOptionShortPutOTMExpiryRegressionAlgorithm.py b/fincept-qt/scripts/strategies/FutureOptionShortPutOTMExpiryRegressionAlgorithm.py
deleted file mode 100644
index ea13cf4a2..000000000
--- a/fincept-qt/scripts/strategies/FutureOptionShortPutOTMExpiryRegressionAlgorithm.py
+++ /dev/null
@@ -1,102 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-470C1BB3
-# Category: Options
-# Description: This regression algorithm tests Out of The Money (OTM) future option expiry for short puts. We expect 2 orders from t...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### This regression algorithm tests Out of The Money (OTM) future option expiry for short puts.
-### We expect 2 orders from the algorithm, which are:
-###
-### * Initial entry, sell ES Put Option (expiring OTM)
-### - Profit the option premium, since the option was not assigned.
-###
-### * Liquidation of ES put OTM contract on the last trade date
-###
-### Additionally, we test delistings for future options and assert that our
-### portfolio holdings reflect the orders the algorithm has submitted.
-### </summary>
-class FutureOptionShortPutOTMExpiryRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2020, 1, 5)
- self.set_end_date(2020, 6, 30)
-
- self.es19m20 = self.add_future_contract(
- Symbol.create_future(
- Futures.Indices.SP_500_E_MINI,
- Market.CME,
- datetime(2020, 6, 19)),
- Resolution.MINUTE).symbol
-
- # Select a future option expiring ITM, and adds it to the algorithm.
- self.es_option = self.add_future_option_contract(
- list(
- sorted(
- [x for x in self.option_chain(self.es19m20) if x.id.strike_price <= 3000.0 and x.id.option_right == OptionRight.PUT],
- key=lambda x: x.id.strike_price,
- reverse=True
- )
- )[0], Resolution.MINUTE).symbol
-
- self.expected_contract = Symbol.create_option(self.es19m20, Market.CME, OptionStyle.AMERICAN, OptionRight.PUT, 3000.0, datetime(2020, 6, 19))
- if self.es_option != self.expected_contract:
- raise AssertionError(f"Contract {self.expected_contract} was not found in the chain")
-
- self.schedule.on(self.date_rules.tomorrow, self.time_rules.after_market_open(self.es19m20, 1), self.scheduled_market_order)
-
- def scheduled_market_order(self):
- self.market_order(self.es_option, -1)
-
- def on_data(self, data: Slice):
- # Assert delistings, so that we can make sure that we receive the delisting warnings at
- # the expected time. These assertions detect bug #4872
- for delisting in data.delistings.values():
- if delisting.type == DelistingType.WARNING:
- if delisting.time != datetime(2020, 6, 19):
- raise AssertionError(f"Delisting warning issued at unexpected date: {delisting.time}")
-
- if delisting.type == DelistingType.DELISTED:
- if delisting.time != datetime(2020, 6, 20):
- raise AssertionError(f"Delisting happened at unexpected date: {delisting.time}")
-
- def on_order_event(self, order_event: OrderEvent):
- if order_event.status != OrderStatus.FILLED:
- # There's lots of noise with OnOrderEvent, but we're only interested in fills.
- return
-
- if not self.securities.contains_key(order_event.symbol):
- raise AssertionError(f"Order event Symbol not found in Securities collection: {order_event.symbol}")
-
- security = self.securities[order_event.symbol]
- if security.symbol == self.es19m20:
- raise AssertionError(f"Expected no order events for underlying Symbol {security.symbol}")
-
- if security.symbol == self.expected_contract:
- self.assert_future_option_contract_order(order_event, security)
-
- else:
- raise AssertionError(f"Received order event for unknown Symbol: {order_event.symbol}")
-
- self.log(f"{order_event}")
-
- def assert_future_option_contract_order(self, order_event: OrderEvent, option_contract: Security):
- if order_event.direction == OrderDirection.SELL and option_contract.holdings.quantity != -1:
- raise AssertionError(f"No holdings were created for option contract {option_contract.symbol}")
-
- if order_event.direction == OrderDirection.BUY and option_contract.holdings.quantity != 0:
- raise AssertionError("Expected no options holdings after closing position")
-
- if order_event.is_assignment:
- raise AssertionError(f"Assignment was not expected for {order_event.symbol}")
-
- def on_end_of_algorithm(self):
- if self.portfolio.invested:
- raise AssertionError(f"Expected no holdings at end of algorithm, but are invested in: {', '.join([str(i.id) for i in self.portfolio.keys()])}")
diff --git a/fincept-qt/scripts/strategies/FutureStopMarketOrderOnExtendedHoursRegressionAlgorithm.py b/fincept-qt/scripts/strategies/FutureStopMarketOrderOnExtendedHoursRegressionAlgorithm.py
deleted file mode 100644
index 1cf1bba45..000000000
--- a/fincept-qt/scripts/strategies/FutureStopMarketOrderOnExtendedHoursRegressionAlgorithm.py
+++ /dev/null
@@ -1,49 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-119E482D
-# Category: Futures
-# Description: Trailing stop strategy inspired by futures stop-market orders.
-# Enters long when price crosses above 20-day SMA, exits with a 3% trailing
-# stop loss. Re-enters on next SMA crossover.
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-class FutureStopMarketOrderOnExtendedHoursRegressionAlgorithm(QCAlgorithm):
- """Trailing stop strategy using SMA entry and percentage-based trailing stop."""
-
- def initialize(self):
- self.set_start_date(2023, 1, 1)
- self.set_end_date(2024, 1, 1)
- self.set_cash(100000)
-
- self.symbol = "SPY"
- self.add_equity(self.symbol, Resolution.DAILY)
-
- self._sma = self.sma(self.symbol, 20, Resolution.DAILY)
- self._highest_since_entry = 0
- self._stop_pct = 0.03 # 3% trailing stop
-
- def on_data(self, data):
- if not self._sma.is_ready:
- return
- if self.symbol not in data:
- return
-
- price = data[self.symbol].close
- sma_val = self._sma.current.value
-
- if not self.portfolio.invested:
- if price > sma_val:
- self.set_holdings(self.symbol, 1)
- self._highest_since_entry = price
- else:
- if price > self._highest_since_entry:
- self._highest_since_entry = price
- stop_level = self._highest_since_entry * (1 - self._stop_pct)
- if price < stop_level:
- self.liquidate()
diff --git a/fincept-qt/scripts/strategies/FuturesAndFuturesOptionsExpiryTimeAndLiquidationRegressionAlgorithm.py b/fincept-qt/scripts/strategies/FuturesAndFuturesOptionsExpiryTimeAndLiquidationRegressionAlgorithm.py
deleted file mode 100644
index 576db3440..000000000
--- a/fincept-qt/scripts/strategies/FuturesAndFuturesOptionsExpiryTimeAndLiquidationRegressionAlgorithm.py
+++ /dev/null
@@ -1,100 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-2549D577
-# Category: Options
-# Description: Tests delistings for Futures and Futures Options to ensure that they are delisted at the expected times
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Tests delistings for Futures and Futures Options to ensure that they are delisted at the expected times.
-### </summary>
-class FuturesAndFutures_optionsExpiryTimeAndLiquidationRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.invested = False
- self.liquidated = 0
- self.delistings_received = 0
-
- self.expected_expiry_warning_time = datetime(2020, 6, 19)
- self.expected_expiry_delisting_time = datetime(2020, 6, 20)
- self.expected_liquidation_time = datetime(2020, 6, 20)
-
- self.set_start_date(2020, 1, 5)
- self.set_end_date(2020, 12, 1)
- self.set_cash(100000)
-
- es = Symbol.create_future(
- "ES",
- Market.CME,
- datetime(2020, 6, 19)
- )
-
- es_option = Symbol.create_option(
- es,
- Market.CME,
- OptionStyle.AMERICAN,
- OptionRight.PUT,
- 3400.0,
- datetime(2020, 6, 19)
- )
-
- self.es_future = self.add_future_contract(es, Resolution.MINUTE).symbol
- self.es_future_option = self.add_future_option_contract(es_option, Resolution.MINUTE).symbol
-
- def on_data(self, data: Slice):
- for delisting in data.delistings.values():
- self.delistings_received += 1
-
- if delisting.type == DelistingType.WARNING and delisting.time != self.expected_expiry_warning_time:
- raise AssertionError(f"Expiry warning with time {delisting.time} but is expected to be {self.expected_expiry_warning_time}")
-
- if delisting.type == DelistingType.WARNING and delisting.time != datetime(self.time.year, self.time.month, self.time.day):
- raise AssertionError(f"Delisting warning received at an unexpected date: {self.time} - expected {delisting.time}")
-
- if delisting.type == DelistingType.DELISTED and delisting.time != self.expected_expiry_delisting_time:
- raise AssertionError(f"Delisting occurred at unexpected time: {delisting.time} - expected: {self.expected_expiry_delisting_time}")
-
- if delisting.type == DelistingType.DELISTED and delisting.time != datetime(self.time.year, self.time.month, self.time.day):
- raise AssertionError(f"Delisting notice received at an unexpected date: {self.time} - expected {delisting.time}")
-
- if not self.invested and \
- (self.es_future in data.bars or self.es_future in data.quote_bars) and \
- (self.es_future_option in data.bars or self.es_future_option in data.quote_bars):
-
- self.invested = True
-
- self.market_order(self.es_future, 1)
- self.market_order(self.es_future_option, 1)
-
- def on_order_event(self, order_event: OrderEvent):
- if order_event.direction != OrderDirection.SELL or order_event.status != OrderStatus.FILLED:
- return
-
- # * Future Liquidation
- # * Future Option Exercise
- # * We expect NO Underlying Future Liquidation because we already hold a Long future position so the FOP Put selling leaves us breakeven
- self.liquidated += 1
- if order_event.symbol.security_type == SecurityType.FUTURE_OPTION and self.expected_liquidation_time != self.time:
- raise AssertionError(f"Expected to liquidate option {order_event.symbol} at {self.expected_liquidation_time}, instead liquidated at {self.time}")
-
- if order_event.symbol.security_type == SecurityType.FUTURE and \
- (self.expected_liquidation_time - timedelta(minutes=1)) != self.time and \
- self.expected_liquidation_time != self.time:
-
- raise AssertionError(f"Expected to liquidate future {order_event.symbol} at {self.expected_liquidation_time} (+1 minute), instead liquidated at {self.time}")
-
- def on_end_of_algorithm(self):
- if not self.invested:
- raise AssertionError("Never invested in ES futures and FOPs")
-
- if self.delistings_received != 4:
- raise AssertionError(f"Expected 4 delisting events received, found: {self.delistings_received}")
-
- if self.liquidated != 2:
- raise AssertionError(f"Expected 3 liquidation events, found {self.liquidated}")
diff --git a/fincept-qt/scripts/strategies/FuturesExtendedMarketHoursRegressionAlgorithm.py b/fincept-qt/scripts/strategies/FuturesExtendedMarketHoursRegressionAlgorithm.py
deleted file mode 100644
index e6491bf5d..000000000
--- a/fincept-qt/scripts/strategies/FuturesExtendedMarketHoursRegressionAlgorithm.py
+++ /dev/null
@@ -1,70 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-4EE8D5FD
-# Category: Futures
-# Description: This regression algorithm asserts that futures have data at extended market hours when this is enabled
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### This regression algorithm asserts that futures have data at extended market hours when this is enabled.
-### </summary>
-class FuturesExtendedMarketHoursRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2013, 10, 6)
- self.set_end_date(2013, 10, 11)
-
- self._es = self.add_future(Futures.Indices.SP_500_E_MINI, Resolution.HOUR, fill_forward=True, extended_market_hours=True)
- self._es.set_filter(0, 180)
-
- self._gc = self.add_future(Futures.Metals.GOLD, Resolution.HOUR, fill_forward=True, extended_market_hours=False)
- self._gc.set_filter(0, 180)
-
- self._es_ran_on_regular_hours = False
- self._es_ran_on_extended_hours = False
- self._gc_ran_on_regular_hours = False
- self._gc_ran_on_extended_hours = False
-
- def on_data(self, slice):
- slice_symbols = set(slice.keys())
- slice_symbols.update(slice.bars.keys())
- slice_symbols.update(slice.ticks.keys())
- slice_symbols.update(slice.quote_bars.keys())
- slice_symbols.update([x.canonical for x in slice_symbols])
-
- es_is_in_regular_hours = self._es.exchange.hours.is_open(self.time, False)
- es_is_in_extended_hours = not es_is_in_regular_hours and self._es.exchange.hours.is_open(self.time, True)
- slice_has_e_s_data = self._es.symbol in slice_symbols
- self._es_ran_on_regular_hours |= es_is_in_regular_hours and slice_has_e_s_data
- self._es_ran_on_extended_hours |= es_is_in_extended_hours and slice_has_e_s_data
-
- gc_is_in_regular_hours = self._gc.exchange.hours.is_open(self.time, False)
- gc_is_in_extended_hours = not gc_is_in_regular_hours and self._gc.exchange.hours.is_open(self.time, True)
- slice_has_g_c_data = self._gc.symbol in slice_symbols
- self._gc_ran_on_regular_hours |= gc_is_in_regular_hours and slice_has_g_c_data
- self._gc_ran_on_extended_hours |= gc_is_in_extended_hours and slice_has_g_c_data
-
- time_of_day = self.time.time()
- current_time_is_regular_hours = (time_of_day >= time(9, 30, 0) and time_of_day < time(16, 15, 0)) or (time_of_day >= time(16, 30, 0) and time_of_day < time(17, 0, 0))
- current_time_is_extended_hours = not current_time_is_regular_hours and (time_of_day < time(9, 30, 0) or time_of_day >= time(18, 0, 0))
- if es_is_in_regular_hours != current_time_is_regular_hours or es_is_in_extended_hours != current_time_is_extended_hours:
- raise Exception("At {Time}, {_es.symbol} is either in regular hours but current time is in extended hours, or viceversa")
-
- def on_end_of_algorithm(self):
- if not self._es_ran_on_regular_hours:
- raise Exception(f"Algorithm should have run on regular hours for {self._es.symbol} future, which enabled extended market hours")
-
- if not self._es_ran_on_extended_hours:
- raise Exception(f"Algorithm should have run on extended hours for {self._es.symbol} future, which enabled extended market hours")
-
- if not self._gc_ran_on_regular_hours:
- raise Exception(f"Algorithm should have run on regular hours for {self._gc.symbol} future, which did not enable extended market hours")
-
- if self._gc_ran_on_extended_hours:
- raise Exception(f"Algorithm should have not run on extended hours for {self._gc.symbol} future, which did not enable extended market hours")
diff --git a/fincept-qt/scripts/strategies/FuturesMomentumAlgorithm.py b/fincept-qt/scripts/strategies/FuturesMomentumAlgorithm.py
deleted file mode 100644
index 996b3bdca..000000000
--- a/fincept-qt/scripts/strategies/FuturesMomentumAlgorithm.py
+++ /dev/null
@@ -1,72 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-CA7ACD88
-# Category: Futures
-# Description: EMA cross with SP500 E-mini futures In this example, we demostrate how to trade futures contracts using a equity to g...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### EMA cross with SP500 E-mini futures
-### In this example, we demostrate how to trade futures contracts using
-### a equity to generate the trading signals
-### It also shows how you can prefilter contracts easily based on expirations.
-### It also shows how you can inspect the futures chain to pick a specific contract to trade.
-### </summary>
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="futures" />
-### <meta name="tag" content="indicators" />
-### <meta name="tag" content="strategy example" />
-class FuturesMomentumAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2016, 1, 1)
- self.set_end_date(2016, 8, 18)
- self.set_cash(100000)
- fast_period = 20
- slow_period = 60
- self._tolerance = 1 + 0.001
- self.is_up_trend = False
- self.is_down_trend = False
- self.set_warm_up(max(fast_period, slow_period))
-
- # Adds SPY to be used in our EMA indicators
- equity = self.add_equity("SPY", Resolution.DAILY)
- self._fast = self.ema(equity.symbol, fast_period, Resolution.DAILY)
- self._slow = self.ema(equity.symbol, slow_period, Resolution.DAILY)
- # Adds the future that will be traded and
- # set our expiry filter for this futures chain
- future = self.add_future(Futures.Indices.SP_500_E_MINI)
- future.set_filter(timedelta(0), timedelta(182))
-
- def on_data(self, slice):
- if self._slow.is_ready and self._fast.is_ready:
- self.is_up_trend = self._fast.current.value > self._slow.current.value * self._tolerance
- self.is_down_trend = self._fast.current.value < self._slow.current.value * self._tolerance
- if (not self.portfolio.invested) and self.is_up_trend:
- for chain in slice.futures_chains:
- # find the front contract expiring no earlier than in 90 days
- contracts = list(filter(lambda x: x.expiry > self.time + timedelta(90), chain.value))
- # if there is any contract, trade the front contract
- if len(contracts) == 0: continue
- contract = sorted(contracts, key = lambda x: x.expiry, reverse=True)[0]
- self.market_order(contract.symbol , 1)
-
- if self.portfolio.invested and self.is_down_trend:
- self.liquidate()
-
- def on_end_of_day(self, symbol):
- if self.is_up_trend:
- self.plot("Indicator Signal", "EOD",1)
- elif self.is_down_trend:
- self.plot("Indicator Signal", "EOD",-1)
- elif self._slow.is_ready and self._fast.is_ready:
- self.plot("Indicator Signal", "EOD",0)
-
- def on_order_event(self, order_event):
- self.log(str(order_event))
diff --git a/fincept-qt/scripts/strategies/G10CurrencySelectionModelFrameworkAlgorithm.py b/fincept-qt/scripts/strategies/G10CurrencySelectionModelFrameworkAlgorithm.py
deleted file mode 100644
index c88f56766..000000000
--- a/fincept-qt/scripts/strategies/G10CurrencySelectionModelFrameworkAlgorithm.py
+++ /dev/null
@@ -1,58 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-7CAB8ED5
-# Category: General Strategy
-# Description: Framework algorithm that uses the G10CurrencySelectionModel, a Universe Selection Model that inherits from ManualUniv...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-from Selection.ManualUniverseSelectionModel import ManualUniverseSelectionModel
-
-class G10CurrencySelectionModel(ManualUniverseSelectionModel):
- '''Provides an implementation of IUniverseSelectionModel that simply subscribes to G10 currencies'''
- def __init__(self):
- '''Initializes a new instance of the G10CurrencySelectionModel class
- using the algorithm's security initializer and universe settings'''
- super().__init__([Symbol.create(x, SecurityType.FOREX, Market.OANDA)
- for x in [ "EURUSD",
- "GBPUSD",
- "USDJPY",
- "AUDUSD",
- "NZDUSD",
- "USDCAD",
- "USDCHF",
- "USDNOK",
- "USDSEK" ]])
-
-### <summary>
-### Framework algorithm that uses the G10CurrencySelectionModel,
-### a Universe Selection Model that inherits from ManualUniverseSelectionModel
-### </summary>
-class G10CurrencySelectionModelFrameworkAlgorithm(QCAlgorithm):
- '''Framework algorithm that uses the G10CurrencySelectionModel,
- a Universe Selection Model that inherits from ManualUniverseSelectionMode'''
-
- def initialize(self):
- ''' Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
-
- # Set requested data resolution
- self.universe_settings.resolution = Resolution.MINUTE
-
- self.set_start_date(2013,10,7) #Set Start Date
- self.set_end_date(2013,10,11) #Set End Date
- self.set_cash(100000) #Set Strategy Cash
-
- # set algorithm framework models
- self.set_universe_selection(G10CurrencySelectionModel())
- self.set_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(minutes = 20), 0.025, None))
- self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())
- self.set_execution(ImmediateExecutionModel())
- self.set_risk_management(MaximumDrawdownPercentPerSecurity(0.01))
-
- def on_order_event(self, order_event):
- if order_event.status == OrderStatus.FILLED:
- self.debug("Purchased Stock: {0}".format(order_event.symbol))
diff --git a/fincept-qt/scripts/strategies/GetParameterRegressionAlgorithm.py b/fincept-qt/scripts/strategies/GetParameterRegressionAlgorithm.py
deleted file mode 100644
index dce6ff53f..000000000
--- a/fincept-qt/scripts/strategies/GetParameterRegressionAlgorithm.py
+++ /dev/null
@@ -1,40 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-4F55CFD9
-# Category: Regression Test
-# Description: Regression algorithm for testing parameterized regression algorithms get valid parameters
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Regression algorithm for testing parameterized regression algorithms get valid parameters.
-### </summary>
-class GetParameterRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2013, 10, 7)
- self.check_parameter(None, self.get_parameter("non-existing"), "GetParameter(\"non-existing\")")
- self.check_parameter("100", self.get_parameter("non-existing", "100"), "GetParameter(\"non-existing\", \"100\")")
- self.check_parameter(100, self.get_parameter("non-existing", 100), "GetParameter(\"non-existing\", 100)")
- self.check_parameter(100.0, self.get_parameter("non-existing", 100.0), "GetParameter(\"non-existing\", 100.0)")
-
- self.check_parameter("10", self.get_parameter("ema-fast"), "GetParameter(\"ema-fast\")")
- self.check_parameter(10, self.get_parameter("ema-fast", 100), "GetParameter(\"ema-fast\", 100)")
- self.check_parameter(10.0, self.get_parameter("ema-fast", 100.0), "GetParameter(\"ema-fast\", 100.0)")
-
- self.quit()
-
- def check_parameter(self, expected, actual, call):
- if expected == None and actual != None:
- raise Exception(f"{call} should have returned null but returned {actual} ({type(actual)})")
-
- if expected != None and actual == None:
- raise Exception(f"{call} should have returned {expected} ({type(expected)}) but returned null")
-
- if expected != None and actual != None and type(expected) != type(actual) or expected != actual:
- raise Exception(f"{call} should have returned {expected} ({type(expected)}) but returned {actual} ({type(actual)})")
diff --git a/fincept-qt/scripts/strategies/HistoricalReturnsAlphaModelFrameworkRegressionAlgorithm.py b/fincept-qt/scripts/strategies/HistoricalReturnsAlphaModelFrameworkRegressionAlgorithm.py
deleted file mode 100644
index a1d739c2f..000000000
--- a/fincept-qt/scripts/strategies/HistoricalReturnsAlphaModelFrameworkRegressionAlgorithm.py
+++ /dev/null
@@ -1,28 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-649F439A
-# Category: Alpha Model
-# Description: Regression algorithm to assert the behavior of <see cref="HistoricalReturnsAlphaModel"/>
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-from BaseFrameworkRegressionAlgorithm import BaseFrameworkRegressionAlgorithm
-from Alphas.HistoricalReturnsAlphaModel import HistoricalReturnsAlphaModel
-
-### <summary>
-### Regression algorithm to assert the behavior of <see cref="HistoricalReturnsAlphaModel"/>.
-### </summary>
-class HistoricalReturnsAlphaModelFrameworkRegressionAlgorithm(BaseFrameworkRegressionAlgorithm):
-
- def initialize(self):
- super().initialize()
- self.set_alpha(HistoricalReturnsAlphaModel())
-
- def on_end_of_algorithm(self):
- expected = 78
- if self.insights.total_count != expected:
- raise Exception(f"The total number of insights should be {expected}. Actual: {self.insights.total_count}")
diff --git a/fincept-qt/scripts/strategies/HistoryAlgorithm.py b/fincept-qt/scripts/strategies/HistoryAlgorithm.py
deleted file mode 100644
index c65ded618..000000000
--- a/fincept-qt/scripts/strategies/HistoryAlgorithm.py
+++ /dev/null
@@ -1,156 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-4F051700
-# Category: Historical Data
-# Description: This algorithm demonstrates the various ways you can call the History function, what it returns, and what you can do ...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### This algorithm demonstrates the various ways you can call the History function,
-### what it returns, and what you can do with the returned values.
-### </summary>
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="history and warm up" />
-### <meta name="tag" content="history" />
-### <meta name="tag" content="warm up" />
-class HistoryAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2013,10, 8) #Set Start Date
- self.set_end_date(2013,10,11) #Set End Date
- self.set_cash(100000) #Set Strategy Cash
-
- # Fincept Terminal Strategy Engine - Symbol Configuration
- self.add_equity("SPY", Resolution.DAILY)
- IBM = self.add_data(CustomDataEquity, "IBM", Resolution.DAILY)
- # specifying the exchange will allow the history methods that accept a number of bars to return to work properly
- IBM.Exchange = EquityExchange()
-
- # we can get history in initialize to set up indicators and such
- self.daily_sma = SimpleMovingAverage(14)
-
- # get the last calendar year's worth of SPY data at the configured resolution (daily)
- trade_bar_history = self.history([self.securities["SPY"].symbol], timedelta(365))
- self.assert_history_count("History<TradeBar>([\"SPY\"], timedelta(365))", trade_bar_history, 250)
-
- # get the last calendar day's worth of SPY data at the specified resolution
- trade_bar_history = self.history(["SPY"], timedelta(1), Resolution.MINUTE)
- self.assert_history_count("History([\"SPY\"], timedelta(1), Resolution.MINUTE)", trade_bar_history, 390)
-
- # get the last 14 bars of SPY at the configured resolution (daily)
- trade_bar_history = self.history(["SPY"], 14)
- self.assert_history_count("History([\"SPY\"], 14)", trade_bar_history, 14)
-
- # get the last 14 minute bars of SPY
- trade_bar_history = self.history(["SPY"], 14, Resolution.MINUTE)
- self.assert_history_count("History([\"SPY\"], 14, Resolution.MINUTE)", trade_bar_history, 14)
-
- # get the historical data from last current day to this current day in minute resolution
- # with Fill Forward and Extended Market options
- interval_bar_history = self.history(["SPY"], self.time - timedelta(1), self.time, Resolution.MINUTE, True, True)
- self.assert_history_count("History([\"SPY\"], self.time - timedelta(1), self.time, Resolution.MINUTE, True, True)", interval_bar_history, 960)
-
- # get the historical data from last current day to this current day in minute resolution
- # with Extended Market option
- interval_bar_history = self.history(["SPY"], self.time - timedelta(1), self.time, Resolution.MINUTE, False, True)
- self.assert_history_count("History([\"SPY\"], self.time - timedelta(1), self.time, Resolution.MINUTE, False, True)", interval_bar_history, 828)
-
- # get the historical data from last current day to this current day in minute resolution
- # with Fill Forward option
- interval_bar_history = self.history(["SPY"], self.time - timedelta(1), self.time, Resolution.MINUTE, True, False)
- self.assert_history_count("History([\"SPY\"], self.time - timedelta(1), self.time, Resolution.MINUTE, True, False)", interval_bar_history, 390)
-
- # get the historical data from last current day to this current day in minute resolution
- interval_bar_history = self.history(["SPY"], self.time - timedelta(1), self.time, Resolution.MINUTE, False, False)
- self.assert_history_count("History([\"SPY\"], self.time - timedelta(1), self.time, Resolution.MINUTE, False, False)", interval_bar_history, 390)
-
- # we can loop over the return value from these functions and we get TradeBars
- # we can use these TradeBars to initialize indicators or perform other math
- for index, trade_bar in trade_bar_history.loc["SPY"].iterrows():
- self.daily_sma.update(index, trade_bar["close"])
-
- # get the last calendar year's worth of custom_data data at the configured resolution (daily)
- custom_data_history = self.history(CustomDataEquity, "IBM", timedelta(365))
- self.assert_history_count("History(CustomDataEquity, \"IBM\", timedelta(365))", custom_data_history, 250)
-
- # get the last 10 bars of IBM at the configured resolution (daily)
- custom_data_history = self.history(CustomDataEquity, "IBM", 14)
- self.assert_history_count("History(CustomDataEquity, \"IBM\", 14)", custom_data_history, 14)
-
- # we can loop over the return values from these functions and we'll get Custom data
- # this can be used in much the same way as the trade_bar_history above
- self.daily_sma.reset()
- for index, custom_data in custom_data_history.loc["IBM"].iterrows():
- self.daily_sma.update(index, custom_data["value"])
-
- # get the last 10 bars worth of Custom data for the specified symbols at the configured resolution (daily)
- all_custom_data = self.history(CustomDataEquity, self.securities.keys(), 14)
- self.assert_history_count("History(CustomDataEquity, self.securities.keys(), 14)", all_custom_data, 14 * 2)
-
- # NOTE: Using different resolutions require that they are properly implemented in your data type. If your
- # custom data source has different resolutions, it would need to be implemented in the GetSource and
- # Reader methods properly.
- #custom_data_history = self.history(CustomDataEquity, "IBM", timedelta(7), Resolution.MINUTE)
- #custom_data_history = self.history(CustomDataEquity, "IBM", 14, Resolution.MINUTE)
- #all_custom_data = self.history(CustomDataEquity, timedelta(365), Resolution.MINUTE)
- #all_custom_data = self.history(CustomDataEquity, self.securities.keys(), 14, Resolution.MINUTE)
- #all_custom_data = self.history(CustomDataEquity, self.securities.keys(), timedelta(1), Resolution.MINUTE)
- #all_custom_data = self.history(CustomDataEquity, self.securities.keys(), 14, Resolution.MINUTE)
-
- # get the last calendar year's worth of all custom_data data
- all_custom_data = self.history(CustomDataEquity, self.securities.keys(), timedelta(365))
- self.assert_history_count("History(CustomDataEquity, self.securities.keys(), timedelta(365))", all_custom_data, 250 * 2)
-
- # we can also access the return value from the multiple symbol functions to request a single
- # symbol and then loop over it
- single_symbol_custom = all_custom_data.loc["IBM"]
- self.assert_history_count("all_custom_data.loc[\"IBM\"]", single_symbol_custom, 250)
- for custom_data in single_symbol_custom:
- # do something with 'IBM.custom_data_equity' custom_data data
- pass
-
- custom_data_spyvalues = all_custom_data.loc["IBM"]["value"]
- self.assert_history_count("all_custom_data.loc[\"IBM\"][\"value\"]", custom_data_spyvalues, 250)
- for value in custom_data_spyvalues:
- # do something with 'IBM.custom_data_equity' value data
- pass
-
- def on_data(self, data):
- '''on_data event is the primary entry point for your algorithm. Each new data point will be pumped in here.
-
- Arguments:
- data: Slice object keyed by symbol containing the stock data
- '''
- if not self.portfolio.invested:
- self.set_holdings("SPY", 1)
-
- def assert_history_count(self, method_call, trade_bar_history, expected):
- count = len(trade_bar_history.index)
- if count != expected:
- raise Exception("{} expected {}, but received {}".format(method_call, expected, count))
-
-
-class CustomDataEquity(PythonData):
- def get_source(self, config, date, is_live):
- zip_file_name = LeanData.generate_zip_file_name(config.Symbol, date, config.Resolution, config.TickType)
- source = Globals.DataFolder + "/equity/usa/daily/" + zip_file_name
- return SubscriptionDataSource(source)
-
- def reader(self, config, line, date, is_live):
- if line == None:
- return None
-
- custom_data = CustomDataEquity()
- custom_data.symbol = config.symbol
-
- csv = line.split(",")
- custom_data.time = datetime.strptime(csv[0], '%Y%m%d %H:%M')
- custom_data.end_time = custom_data.time + timedelta(days=1)
- custom_data.value = float(csv[1])
- return custom_data
diff --git a/fincept-qt/scripts/strategies/HistoryAuxiliaryDataRegressionAlgorithm.py b/fincept-qt/scripts/strategies/HistoryAuxiliaryDataRegressionAlgorithm.py
deleted file mode 100644
index 47944cbce..000000000
--- a/fincept-qt/scripts/strategies/HistoryAuxiliaryDataRegressionAlgorithm.py
+++ /dev/null
@@ -1,50 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-17047AD3
-# Category: Regression Test
-# Description: Historical price channel breakout strategy. Tracks 15-day
-# high and low channels. Buys on upper channel breakout, sells on lower
-# channel breakdown. Classic Donchian channel approach.
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-class HistoryAuxiliaryDataRegressionAlgorithm(QCAlgorithm):
- """Donchian channel breakout strategy."""
-
- def initialize(self):
- self.set_start_date(2023, 1, 1)
- self.set_end_date(2024, 1, 1)
- self.set_cash(100000)
-
- self.symbol = "SPY"
- self.add_equity(self.symbol, Resolution.DAILY)
-
- self._max = self.max(self.symbol, 15, Resolution.DAILY)
- self._min = self.min(self.symbol, 15, Resolution.DAILY)
- self._bar_count = 0
-
- def on_data(self, data):
- if not self._max.is_ready or not self._min.is_ready:
- return
- if self.symbol not in data:
- return
-
- self._bar_count += 1
- if self._bar_count <= 15:
- return
-
- price = data[self.symbol].close
- upper = self._max.current.value
- lower = self._min.current.value
-
- if not self.portfolio.invested:
- if price >= upper:
- self.set_holdings(self.symbol, 1)
- else:
- if price <= lower:
- self.liquidate()
diff --git a/fincept-qt/scripts/strategies/HistoryTickRegressionAlgorithm.py b/fincept-qt/scripts/strategies/HistoryTickRegressionAlgorithm.py
deleted file mode 100644
index 88603794c..000000000
--- a/fincept-qt/scripts/strategies/HistoryTickRegressionAlgorithm.py
+++ /dev/null
@@ -1,31 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-5077EFC4
-# Category: Regression Test
-# Description: Regression algorithm asserting that tick history request includes both trade and quote data
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Regression algorithm asserting that tick history request includes both trade and quote data
-### </summary>
-class HistoryTickRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2013, 10, 11)
- self.set_end_date(2013, 10, 11)
-
- self._symbol = self.add_equity("SPY", Resolution.TICK).symbol
-
- def on_end_of_algorithm(self):
- history = list(self.history[Tick](self._symbol, timedelta(days=1), Resolution.TICK))
- quotes = [x for x in history if x.tick_type == TickType.QUOTE]
- trades = [x for x in history if x.tick_type == TickType.TRADE]
-
- if not quotes or not trades:
- raise Exception("Expected to find at least one tick of each type (quote and trade)")
diff --git a/fincept-qt/scripts/strategies/HistoryWithCustomDataSourceRegressionAlgorithm.py b/fincept-qt/scripts/strategies/HistoryWithCustomDataSourceRegressionAlgorithm.py
deleted file mode 100644
index 4ab44d751..000000000
--- a/fincept-qt/scripts/strategies/HistoryWithCustomDataSourceRegressionAlgorithm.py
+++ /dev/null
@@ -1,64 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-D55B4B0F
-# Category: Regression Test
-# Description: Regression test illustrating how history from custom data sources can be requested. The <see cref="QCAlgorithm.histor...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Regression test illustrating how history from custom data sources can be requested. The <see cref="QCAlgorithm.history"/> method used in this
-### example also allows to specify other parameters than just the resolution, such as the data normalization mode, the data mapping mode, etc.
-### </summary>
-class HistoryWithCustomDataSourceRegressionAlgorithm(QCAlgorithm):
- def initialize(self):
- self.set_start_date(2014, 6, 5)
- self.set_end_date(2014, 6, 6)
-
- self.aapl = self.add_data(CustomData, "AAPL", Resolution.MINUTE).symbol
- self.spy = self.add_data(CustomData, "SPY", Resolution.MINUTE).symbol
-
- def on_end_of_algorithm(self):
- aapl_history = self.history(CustomData, self.aapl, self.start_date, self.end_date, Resolution.MINUTE,
- fill_forward=False, extended_market_hours=False, data_normalization_mode=DataNormalizationMode.RAW).droplevel(0, axis=0)
- spy_history = self.history(CustomData, self.spy, self.start_date, self.end_date, Resolution.MINUTE,
- fill_forward=False, extended_market_hours=False, data_normalization_mode=DataNormalizationMode.RAW).droplevel(0, axis=0)
-
- if aapl_history.size == 0 or spy_history.size == 0:
- raise Exception("At least one of the history results is empty")
-
- # Check that both resutls contain the same data, since CustomData fetches APPL data regardless of the symbol
- if not aapl_history.equals(spy_history):
- raise Exception("Histories are not equal")
-
-class CustomData(PythonData):
- '''Custom data source for the regression test algorithm, which returns AAPL equity data regardless of the symbol requested.'''
-
- def get_source(self, config, date, is_live_mode):
- return TradeBar().get_source(
- SubscriptionDataConfig(
- config,
- CustomData,
- # Create a new symbol as equity so we find the existing data files
- # Symbol.create(config.mapped_symbol, SecurityType.EQUITY, config.market)),
- Symbol.create("AAPL", SecurityType.EQUITY, config.market)),
- date,
- is_live_mode)
-
- def reader(self, config, line, date, is_live_mode):
- trade_bar = TradeBar.parse_equity(config, line, date)
- data = CustomData()
- data.time = trade_bar.time
- data.value = trade_bar.value
- data.close = trade_bar.close
- data.open = trade_bar.open
- data.high = trade_bar.high
- data.low = trade_bar.low
- data.volume = trade_bar.volume
-
- return data
diff --git a/fincept-qt/scripts/strategies/HistoryWithDifferentContinuousContractDepthOffsetsRegressionAlgorithm.py b/fincept-qt/scripts/strategies/HistoryWithDifferentContinuousContractDepthOffsetsRegressionAlgorithm.py
deleted file mode 100644
index dbde60ab8..000000000
--- a/fincept-qt/scripts/strategies/HistoryWithDifferentContinuousContractDepthOffsetsRegressionAlgorithm.py
+++ /dev/null
@@ -1,41 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-52E3A84A
-# Category: Regression Test
-# Description: Regression algorithm illustrating how to request history data for continuous contracts with different depth offsets
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Regression algorithm illustrating how to request history data for continuous contracts with different depth offsets.
-### </summary>
-class HistoryWithDifferentContinuousContractDepthOffsetsRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2013, 10, 6)
- self.set_end_date(2014, 1, 1)
- self._continuous_contract_symbol = self.add_future(Futures.Indices.SP_500_E_MINI, Resolution.DAILY).symbol
-
- def on_end_of_algorithm(self):
- contract_depth_offsets = range(3)
- history_results = [
- self.history([self._continuous_contract_symbol], self.start_date, self.end_date, Resolution.DAILY, contract_depth_offset=contract_depth_offset)
- .droplevel(0, axis=0)
- .loc[self._continuous_contract_symbol]
- .close
- for contract_depth_offset in contract_depth_offsets
- ]
-
- if any(x.size == 0 or x.size != history_results[0].size for x in history_results):
- raise Exception("History results are empty or bar counts did not match")
-
- # Check that prices at each time are different for different contract depth offsets
- for j in range(history_results[0].size):
- close_prices = set(history_results[i][j] for i in range(len(history_results)))
- if len(close_prices) != len(contract_depth_offsets):
- raise Exception("History results close prices should have been different for each data mapping mode at each time")
diff --git a/fincept-qt/scripts/strategies/HistoryWithDifferentDataMappingModeRegressionAlgorithm.py b/fincept-qt/scripts/strategies/HistoryWithDifferentDataMappingModeRegressionAlgorithm.py
deleted file mode 100644
index 34695c1d5..000000000
--- a/fincept-qt/scripts/strategies/HistoryWithDifferentDataMappingModeRegressionAlgorithm.py
+++ /dev/null
@@ -1,42 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-8CB7F1CC
-# Category: Regression Test
-# Description: Regression algorithm illustrating how to request history data for different data mapping modes
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-from System import *
-
-### <summary>
-### Regression algorithm illustrating how to request history data for different data mapping modes.
-### </summary>
-class HistoryWithDifferentDataMappingModeRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2013, 10, 6)
- self.set_end_date(2014, 1, 1)
- self._continuous_contract_symbol = self.add_future(Futures.Indices.SP_500_E_MINI, Resolution.DAILY).symbol
-
- def on_end_of_algorithm(self):
- data_mapping_modes = [DataMappingMode(x) for x in Enum.get_values(DataMappingMode)]
- history_results = [
- self.history([self._continuous_contract_symbol], self.start_date, self.end_date, Resolution.DAILY, data_mapping_mode=data_mapping_mode)
- .droplevel(0, axis=0)
- .loc[self._continuous_contract_symbol]
- .close
- for data_mapping_mode in data_mapping_modes
- ]
-
- if any(x.size != history_results[0].size for x in history_results):
- raise Exception("History results bar count did not match")
-
- # Check that close prices at each time are different for different data mapping modes
- for j in range(history_results[0].size):
- close_prices = set(history_results[i][j] for i in range(len(history_results)))
- if len(close_prices) != len(data_mapping_modes):
- raise Exception("History results close prices should have been different for each data mapping mode at each time")
diff --git a/fincept-qt/scripts/strategies/HistoryWithDifferentDataNormalizationModeRegressionAlgorithm.py b/fincept-qt/scripts/strategies/HistoryWithDifferentDataNormalizationModeRegressionAlgorithm.py
deleted file mode 100644
index c5a5bb6ca..000000000
--- a/fincept-qt/scripts/strategies/HistoryWithDifferentDataNormalizationModeRegressionAlgorithm.py
+++ /dev/null
@@ -1,55 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-25201E5E
-# Category: Regression Test
-# Description: Regression algorithm illustrating how to request history data for different data normalization modes
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Regression algorithm illustrating how to request history data for different data normalization modes.
-### </summary>
-class HistoryWithDifferentDataNormalizationModeRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2013, 10, 7)
- self.set_end_date(2014, 1, 1)
- self.aapl_equity_symbol = self.add_equity("AAPL", Resolution.DAILY).symbol
- self.es_future_symbol = self.add_future(Futures.Indices.SP_500_E_MINI, Resolution.DAILY).symbol
-
- def on_end_of_algorithm(self):
- equity_data_normalization_modes = [
- DataNormalizationMode.RAW,
- DataNormalizationMode.ADJUSTED,
- DataNormalizationMode.SPLIT_ADJUSTED
- ]
- self.check_history_results_for_data_normalization_modes(self.aapl_equity_symbol, self.start_date, self.end_date, Resolution.DAILY,
- equity_data_normalization_modes)
-
- future_data_normalization_modes = [
- DataNormalizationMode.RAW,
- DataNormalizationMode.BACKWARDS_RATIO,
- DataNormalizationMode.BACKWARDS_PANAMA_CANAL,
- DataNormalizationMode.FORWARD_PANAMA_CANAL
- ]
- self.check_history_results_for_data_normalization_modes(self.es_future_symbol, self.start_date, self.end_date, Resolution.DAILY,
- future_data_normalization_modes)
-
- def check_history_results_for_data_normalization_modes(self, symbol, start, end, resolution, data_normalization_modes):
- history_results = [self.history([symbol], start, end, resolution, data_normalization_mode=x) for x in data_normalization_modes]
- history_results = [x.droplevel(0, axis=0) for x in history_results] if len(history_results[0].index.levels) == 3 else history_results
- history_results = [x.loc[symbol].close for x in history_results]
-
- if any(x.size == 0 or x.size != history_results[0].size for x in history_results):
- raise Exception(f"History results for {symbol} have different number of bars")
-
- # Check that, for each history result, close prices at each time are different for these securities (AAPL and ES)
- for j in range(history_results[0].size):
- close_prices = set(history_results[i][j] for i in range(len(history_results)))
- if len(close_prices) != len(data_normalization_modes):
- raise Exception(f"History results for {symbol} have different close prices at the same time")
diff --git a/fincept-qt/scripts/strategies/HourReverseSplitRegressionAlgorithm.py b/fincept-qt/scripts/strategies/HourReverseSplitRegressionAlgorithm.py
deleted file mode 100644
index cd310cd67..000000000
--- a/fincept-qt/scripts/strategies/HourReverseSplitRegressionAlgorithm.py
+++ /dev/null
@@ -1,32 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-690AD750
-# Category: Regression Test
-# Description: Regression test for consistency of hour data over a reverse split event in US equities
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Regression test for consistency of hour data over a reverse split event in US equities.
-### </summary>
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="regression test" />
-class HourReverseSplitRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2013, 11, 7)
- self.set_end_date(2013, 11, 8)
- self.set_cash(100000)
- self.set_benchmark(lambda x: 0)
-
- self._symbol = self.add_equity("VXX.1", Resolution.HOUR).symbol
-
- def on_data(self, slice):
- if slice.bars.count == 0: return
- if (not self.portfolio.invested) and self.time.date() == self.end_date.date():
- self.buy(self._symbol, 1)
diff --git a/fincept-qt/scripts/strategies/HourSplitRegressionAlgorithm.py b/fincept-qt/scripts/strategies/HourSplitRegressionAlgorithm.py
deleted file mode 100644
index c3d7f070f..000000000
--- a/fincept-qt/scripts/strategies/HourSplitRegressionAlgorithm.py
+++ /dev/null
@@ -1,32 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-ADDA18D4
-# Category: Regression Test
-# Description: Regression test for consistency of hour data over a reverse split event in US equities
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Regression test for consistency of hour data over a reverse split event in US equities.
-### </summary>
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="regression test" />
-class HourSplitRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2014, 6, 6)
- self.set_end_date(2014, 6, 9)
- self.set_cash(100000)
- self.set_benchmark(lambda x: 0)
-
- self._symbol = self.add_equity("AAPL", Resolution.HOUR).symbol
-
- def on_data(self, slice):
- if slice.bars.count == 0: return
- if (not self.portfolio.invested) and self.time.date() == self.end_date.date():
- self.buy(self._symbol, 1)
diff --git a/fincept-qt/scripts/strategies/ImmediateExecutionModelWorksWithBinanceFeeModel.py b/fincept-qt/scripts/strategies/ImmediateExecutionModelWorksWithBinanceFeeModel.py
deleted file mode 100644
index 4d8002e66..000000000
--- a/fincept-qt/scripts/strategies/ImmediateExecutionModelWorksWithBinanceFeeModel.py
+++ /dev/null
@@ -1,48 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-5C005A63
-# Category: Execution Model
-# Description: Regression algorithm to test ImmediateExecutionModel places orders with the correct quantity (taking into account the...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-from Execution.ImmediateExecutionModel import ImmediateExecutionModel
-from QuantConnect.Orders import OrderEvent
-# endregion
-
-### <summary>
-### Regression algorithm to test ImmediateExecutionModel places orders with the
-### correct quantity (taking into account the fee's) so that the fill quantity
-### is the expected one.
-### </summary>
-class ImmediateExecutionModelWorksWithBinanceFeeModel(QCAlgorithm):
-
- def Initialize(self):
- # *** initial configurations and backtest ***
- self.SetStartDate(2022, 12, 13) # Set Start Date
- self.SetEndDate(2022, 12, 14) # Set End Date
- self.SetAccountCurrency("BUSD") # Set Account Currency
- self.SetCash("BUSD", 100000, 1) # Set Strategy Cash
-
- self.universe_settings.resolution = Resolution.MINUTE
-
- symbols = [ Symbol.create("BTCBUSD", SecurityType.CRYPTO, Market.BINANCE) ]
-
- # set algorithm framework models
- self.set_universe_selection(ManualUniverseSelectionModel(symbols))
- self.set_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(minutes = 20), 0.025, None))
-
- self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel(Resolution.MINUTE))
- self.set_execution(ImmediateExecutionModel())
-
-
- self.SetBrokerageModel(BrokerageName.Binance, AccountType.Margin)
-
- def on_order_event(self, order_event: OrderEvent) -> None:
- if order_event.status == OrderStatus.FILLED:
- if abs(order_event.quantity - 5.8) > 0.01:
- raise Exception(f"The expected quantity was 5.8 but the quantity from the order was {order_event.quantity}")
diff --git a/fincept-qt/scripts/strategies/InceptionDateSelectionRegressionAlgorithm.py b/fincept-qt/scripts/strategies/InceptionDateSelectionRegressionAlgorithm.py
deleted file mode 100644
index 458057213..000000000
--- a/fincept-qt/scripts/strategies/InceptionDateSelectionRegressionAlgorithm.py
+++ /dev/null
@@ -1,49 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-BDFB56F1
-# Category: Regression Test
-# Description: Regression algorithm to test universe additions and removals with open positions
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Regression algorithm to test universe additions and removals with open positions
-### </summary>
-### <meta name="tag" content="regression test" />
-class InceptionDateSelectionRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2013,10,1)
- self.set_end_date(2013,10,31)
- self.set_cash(100000)
-
- self.changes = None
- self.universe_settings.resolution = Resolution.HOUR
-
- # select IBM once a week, empty universe the other days
- self.add_universe_selection(CustomUniverseSelectionModel("my-custom-universe", lambda dt: ["IBM"] if dt.day % 7 == 0 else []))
- # Adds SPY 5 days after StartDate and keep it in Universe
- self.add_universe_selection(InceptionDateUniverseSelectionModel("spy-inception", {"SPY": self.start_date + timedelta(5)}))
-
-
- def on_data(self, slice):
- if self.changes is None:
- return
-
- # we'll simply go long each security we added to the universe
- for security in self.changes.added_securities:
- self.set_holdings(security.symbol, .5)
-
- self.changes = None
-
- def on_securities_changed(self, changes):
- # liquidate removed securities
- for security in changes.removed_securities:
- self.liquidate(security.symbol, "Removed from Universe")
-
- self.changes = changes
diff --git a/fincept-qt/scripts/strategies/IndexOptionBearCallSpreadAlgorithm.py b/fincept-qt/scripts/strategies/IndexOptionBearCallSpreadAlgorithm.py
deleted file mode 100644
index ecfcc64c8..000000000
--- a/fincept-qt/scripts/strategies/IndexOptionBearCallSpreadAlgorithm.py
+++ /dev/null
@@ -1,53 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-5B348FD6
-# Category: Options
-# Description: Index Option Bear Call Spread Algorithm
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-#endregion
-
-class IndexOptionBearCallSpreadAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2020, 1, 1)
- self.set_end_date(2021, 1, 1)
- self.set_cash(100000)
-
- self.spy = self.add_equity("SPY", Resolution.MINUTE).symbol
-
- index = self.add_index("VIX", Resolution.MINUTE).symbol
- option = self.add_index_option(index, "VIXW", Resolution.MINUTE)
- option.set_filter(lambda x: x.strikes(-5, 5).expiration(15, 45))
-
- self.vixw = option.symbol
- self.tickets = []
-
- def on_data(self, slice: Slice) -> None:
- if not self.portfolio[self.spy].invested:
- self.market_order(self.spy, 100)
-
- # Return if hedge position presents
- if any([self.portfolio[x.symbol].invested for x in self.tickets]):
- return
-
- # Return if hedge position presents
- chain = slice.option_chains.get(self.vixw)
- if not chain: return
-
- # Get the nearest expiry date of the contracts
- expiry = min([x.expiry for x in chain])
-
- # Select the call Option contracts with the nearest expiry and sort by strike price
- calls = sorted([i for i in chain if i.expiry == expiry and i.right == OptionRight.CALL],
- key=lambda x: x.strike)
- if len(calls) < 2: return
-
- # Buy the bear call spread
- bear_call_spread = OptionStrategies.bear_call_spread(self.vixw, calls[0].strike, calls[-1].strike, expiry)
- self.tickets = self.buy(bear_call_spread, 1)
diff --git a/fincept-qt/scripts/strategies/IndexOptionBearPutSpreadAlgorithm.py b/fincept-qt/scripts/strategies/IndexOptionBearPutSpreadAlgorithm.py
deleted file mode 100644
index 4abc9b33f..000000000
--- a/fincept-qt/scripts/strategies/IndexOptionBearPutSpreadAlgorithm.py
+++ /dev/null
@@ -1,47 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-F75EB8E2
-# Category: Options
-# Description: Index Option Bear Put Spread Algorithm
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-class IndexOptionBearPutSpreadAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2022, 1, 1)
- self.set_end_date(2022, 7, 1)
- self.set_cash(100000)
-
- index = self.add_index("SPX", Resolution.MINUTE).symbol
- option = self.add_index_option(index, "SPXW", Resolution.MINUTE)
- option.set_filter(lambda x: x.weeklys_only().strikes(5, 10).expiration(0, 0))
-
- self.spxw = option.symbol
- self.tickets = []
-
- def on_data(self, slice: Slice) -> None:
- # Return if open position exists
- if any([self.portfolio[x.symbol].invested for x in self.tickets]):
- return
-
- # Get option chain
- chain = slice.option_chains.get(self.spxw)
- if not chain: return
-
- # Get the nearest expiry date of the contracts
- expiry = min([x.expiry for x in chain])
-
- # Select the put Option contracts with the nearest expiry and sort by strike price
- puts = sorted([i for i in chain if i.expiry == expiry and i.right == OptionRight.PUT],
- key=lambda x: x.strike)
- if len(puts) < 2: return
-
- # Buy the bear put spread
- bear_put_spread = OptionStrategies.bear_put_spread(self.spxw, puts[-1].strike, puts[0].strike, expiry)
- self.tickets = self.buy(bear_put_spread, 1)
\ No newline at end of file
diff --git a/fincept-qt/scripts/strategies/IndexOptionBullCallSpreadAlgorithm.py b/fincept-qt/scripts/strategies/IndexOptionBullCallSpreadAlgorithm.py
deleted file mode 100644
index afaafdcc7..000000000
--- a/fincept-qt/scripts/strategies/IndexOptionBullCallSpreadAlgorithm.py
+++ /dev/null
@@ -1,53 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-82E65BB4
-# Category: Options
-# Description: Index Option Bull Call Spread Algorithm
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-#endregion
-
-class IndexOptionBullCallSpreadAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2020, 1, 1)
- self.set_end_date(2021, 1, 1)
- self.set_cash(100000)
-
- self.spy = self.add_equity("SPY", Resolution.MINUTE).symbol
-
- index = self.add_index("SPX", Resolution.MINUTE).symbol
- option = self.add_index_option(index, "SPXW", Resolution.MINUTE)
- option.set_filter(lambda x: x.weeklys_only().strikes(-5, 5).expiration(40, 60))
-
- self.spxw = option.symbol
- self.tickets = []
-
- def on_data(self, slice: Slice) -> None:
- if not self.portfolio[self.spy].invested:
- self.market_order(self.spy, 100)
-
- # Return if hedge position presents
- if any([self.portfolio[x.symbol].invested for x in self.tickets]):
- return
-
- # Return if hedge position presents
- chain = slice.option_chains.get(self.spxw)
- if not chain: return
-
- # Get the nearest expiry date of the contracts
- expiry = min([x.expiry for x in chain])
-
- # Select the call Option contracts with the nearest expiry and sort by strike price
- calls = sorted([i for i in chain if i.expiry == expiry and i.right == OptionRight.CALL],
- key=lambda x: x.strike)
- if len(calls) < 2: return
-
- # Buy the bull call spread
- bull_call_spread = OptionStrategies.bull_call_spread(self.spxw, calls[0].strike, calls[-1].strike, expiry)
- self.tickets = self.buy(bull_call_spread, 1)
\ No newline at end of file
diff --git a/fincept-qt/scripts/strategies/IndexOptionBullPutSpreadAlgorithm.py b/fincept-qt/scripts/strategies/IndexOptionBullPutSpreadAlgorithm.py
deleted file mode 100644
index e3e65109b..000000000
--- a/fincept-qt/scripts/strategies/IndexOptionBullPutSpreadAlgorithm.py
+++ /dev/null
@@ -1,47 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-1D8349B6
-# Category: Options
-# Description: Index Option Bull Put Spread Algorithm
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-class IndexOptionBullPutSpreadAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2019, 1, 1)
- self.set_end_date(2020, 1, 1)
- self.set_cash(100000)
-
- index = self.add_index("SPX", Resolution.MINUTE).symbol
- option = self.add_index_option(index, "SPXW", Resolution.MINUTE)
- option.set_filter(lambda x: x.weeklys_only().strikes(-10, -5).expiration(0, 0))
-
- self.spxw = option.symbol
- self.tickets = []
-
- def on_data(self, slice: Slice) -> None:
- # Return if open position exists
- if any([self.portfolio[x.symbol].invested for x in self.tickets]):
- return
-
- # Get option chain
- chain = slice.option_chains.get(self.spxw)
- if not chain: return
-
- # Get the nearest expiry date of the contracts
- expiry = min([x.expiry for x in chain])
-
- # Select the put Option contracts with the nearest expiry and sort by strike price
- puts = sorted([i for i in chain if i.expiry == expiry and i.right == OptionRight.PUT],
- key=lambda x: x.strike)
- if len(puts) < 2: return
-
- # Buy the bull put spread
- bull_call_spread = OptionStrategies.bull_put_spread(self.spxw, puts[-1].strike, puts[0].strike, expiry)
- self.tickets = self.buy(bull_call_spread, 1)
\ No newline at end of file
diff --git a/fincept-qt/scripts/strategies/IndexOptionBuySellCallIntradayRegressionAlgorithm.py b/fincept-qt/scripts/strategies/IndexOptionBuySellCallIntradayRegressionAlgorithm.py
deleted file mode 100644
index d00c63c3b..000000000
--- a/fincept-qt/scripts/strategies/IndexOptionBuySellCallIntradayRegressionAlgorithm.py
+++ /dev/null
@@ -1,84 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-C204FEB8
-# Category: Options
-# Description: This regression algorithm tests In The Money (ITM) index option calls across different strike prices. We expect 4* or...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### This regression algorithm tests In The Money (ITM) index option calls across different strike prices.
-### We expect 4* orders from the algorithm, which are:
-###
-### * (1) Initial entry, buy SPX Call Option (SPXF21 expiring ITM)
-### * (2) Initial entry, sell SPX Call Option at different strike (SPXF21 expiring ITM)
-### * [2] Option assignment, settle into cash
-### * [1] Option exercise, settle into cash
-###
-### Additionally, we test delistings for index options and assert that our
-### portfolio holdings reflect the orders the algorithm has submitted.
-###
-### * Assignments are counted as orders
-### </summary>
-class IndexOptionBuySellCallIntradayRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2021, 1, 4)
- self.set_end_date(2021, 1, 31)
-
- spx = self.add_index("SPX", Resolution.MINUTE).symbol
-
- # Select a index option expiring ITM, and adds it to the algorithm.
- spx_options = list(sorted([
- self.add_index_option_contract(i, Resolution.MINUTE).symbol \
- for i in self.option_chain(spx)\
- if (i.id.strike_price == 3700 or i.id.strike_price == 3800) and i.id.option_right == OptionRight.CALL and i.id.date.year == 2021 and i.id.date.month == 1],
- key=lambda x: x.id.strike_price
- ))
-
- expectedContract3700 = Symbol.create_option(
- spx,
- Market.USA,
- OptionStyle.EUROPEAN,
- OptionRight.CALL,
- 3700,
- datetime(2021, 1, 15)
- )
-
- expectedContract3800 = Symbol.create_option(
- spx,
- Market.USA,
- OptionStyle.EUROPEAN,
- OptionRight.CALL,
- 3800,
- datetime(2021, 1, 15)
- )
-
- if len(spx_options) != 2:
- raise Exception(f"Expected 2 index options symbols from chain provider, found {spx_options.count}")
-
- if spx_options[0] != expectedContract3700:
- raise Exception(f"Contract {expectedContract3700} was not found in the chain, found instead: {spx_options[0]}")
-
- if spx_options[1] != expectedContract3800:
- raise Exception(f"Contract {expectedContract3800} was not found in the chain, found instead: {spx_options[1]}")
-
- self.schedule.on(self.date_rules.tomorrow, self.time_rules.after_market_open(spx, 1), lambda: self.after_market_open_trade(spx_options))
- self.schedule.on(self.date_rules.tomorrow, self.time_rules.noon, lambda: self.liquidate())
-
- def after_market_open_trade(self, spx_options):
- self.market_order(spx_options[0], 1)
- self.market_order(spx_options[1], -1)
-
- ### <summary>
- ### Ran at the end of the algorithm to ensure the algorithm has no holdings
- ### </summary>
- ### <exception cref="Exception">The algorithm has holdings</exception>
- def on_end_of_algorithm(self):
- if self.portfolio.invested:
- raise Exception(f"Expected no holdings at end of algorithm, but are invested in: {', '.join(self.portfolio.keys())}")
diff --git a/fincept-qt/scripts/strategies/IndexOptionCallButterflyAlgorithm.py b/fincept-qt/scripts/strategies/IndexOptionCallButterflyAlgorithm.py
deleted file mode 100644
index 4caff2f68..000000000
--- a/fincept-qt/scripts/strategies/IndexOptionCallButterflyAlgorithm.py
+++ /dev/null
@@ -1,67 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-DC3B31DA
-# Category: Options
-# Description: Index Option Call Butterfly Algorithm
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-#endregion
-
-class IndexOptionCallButterflyAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2020, 1, 1)
- self.set_end_date(2021, 1, 1)
- self.set_cash(1000000)
-
- self.vxz = self.add_equity("VXZ", Resolution.MINUTE).symbol
-
- index = self.add_index("SPX", Resolution.MINUTE).symbol
- option = self.add_index_option(index, "SPXW", Resolution.MINUTE)
- option.set_filter(lambda x: x.include_weeklys().strikes(-3, 3).expiration(15, 45))
-
- self.spxw = option.symbol
- self.multiplier = option.symbol_properties.contract_multiplier
- self.tickets = []
-
- def on_data(self, slice: Slice) -> None:
- # The order of magnitude per SPXW order's value is 10000 times of VXZ
- if not self.portfolio[self.vxz].invested:
- self.market_order(self.vxz, 10000)
-
- # Return if any opening index option position
- if any([self.portfolio[x.symbol].invested for x in self.tickets]): return
-
- # Get the OptionChain
- chain = slice.option_chains.get(self.spxw)
- if not chain: return
-
- # Get nearest expiry date
- expiry = min([x.expiry for x in chain])
-
- # Select the call Option contracts with nearest expiry and sort by strike price
- calls = [x for x in chain if x.expiry == expiry and x.right == OptionRight.CALL]
- if len(calls) < 3: return
- sorted_call_strikes = sorted([x.strike for x in calls])
-
- # Select ATM call
- atm_strike = min([abs(x - chain.underlying.value) for x in sorted_call_strikes])
-
- # Get the strike prices for the ITM & OTM contracts, make sure they're in equidistance
- spread = min(atm_strike - sorted_call_strikes[0], sorted_call_strikes[-1] - atm_strike)
- itm_strike = atm_strike - spread
- otm_strike = atm_strike + spread
- if otm_strike not in sorted_call_strikes or itm_strike not in sorted_call_strikes: return
-
- # Buy the call butterfly
- call_butterfly = OptionStrategies.call_butterfly(self.spxw, otm_strike, atm_strike, itm_strike, expiry)
- price = sum([abs(self.securities[x.symbol].price * x.quantity) * self.multiplier for x in call_butterfly.underlying_legs])
- if price > 0:
- quantity = self.portfolio.total_portfolio_value // price
- self.tickets = self.buy(call_butterfly, quantity, asynchronous=True)
-
\ No newline at end of file
diff --git a/fincept-qt/scripts/strategies/IndexOptionCallCalendarSpreadAlgorithm.py b/fincept-qt/scripts/strategies/IndexOptionCallCalendarSpreadAlgorithm.py
deleted file mode 100644
index 3276c18ff..000000000
--- a/fincept-qt/scripts/strategies/IndexOptionCallCalendarSpreadAlgorithm.py
+++ /dev/null
@@ -1,65 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-C629FC42
-# Category: Options
-# Description: Index Option Call Calendar Spread Algorithm
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-class IndexOptionCallCalendarSpreadAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2020, 1, 1)
- self.set_end_date(2021, 1, 1)
- self.set_cash(50000)
-
- self.vxz = self.add_equity("VXZ", Resolution.MINUTE).symbol
- self.spy = self.add_equity("SPY", Resolution.MINUTE).symbol
-
- index = self.add_index("VIX", Resolution.MINUTE).symbol
- option = self.add_index_option(index, "VIXW", Resolution.MINUTE)
- option.set_filter(lambda x: x.strikes(-2, 2).expiration(15, 45))
-
- self.vixw = option.symbol
- self.multiplier = option.symbol_properties.contract_multiplier
- self.legs = []
- self.expiry = datetime.max
-
- def on_data(self, slice: Slice) -> None:
- # Liquidate if the shorter term option is about to expire
- if self.expiry < self.time + timedelta(2) and all([slice.contains_key(x.symbol) for x in self.legs]):
- self.liquidate()
- # Return if there is any opening position
- elif [leg for leg in self.legs if self.portfolio[leg.symbol].invested]:
- return
-
- # Get the OptionChain
- chain = slice.option_chains.get(self.vixw)
- if not chain: return
-
- # Get ATM strike price
- strike = sorted(chain, key = lambda x: abs(x.strike - chain.underlying.value))[0].strike
-
- # Select the ATM call Option contracts and sort by expiration date
- calls = sorted([i for i in chain if i.strike == strike and i.right == OptionRight.CALL],
- key=lambda x: x.expiry)
- if len(calls) < 2: return
- self.expiry = calls[0].expiry
-
- # Create combo order legs
- self.legs = [
- Leg.create(calls[0].symbol, -1),
- Leg.create(calls[-1].symbol, 1),
- Leg.create(self.vxz, -100),
- Leg.create(self.spy, -10)
- ]
- quantity = self.portfolio.total_portfolio_value // \
- sum([abs(self.securities[x.symbol].price * x.quantity *
- (self.multiplier if x.symbol.id.security_type == SecurityType.INDEX_OPTION else 1))
- for x in self.legs])
- self.combo_market_order(self.legs, -quantity, asynchronous=True)
\ No newline at end of file
diff --git a/fincept-qt/scripts/strategies/IndexOptionCallITMExpiryRegressionAlgorithm.py b/fincept-qt/scripts/strategies/IndexOptionCallITMExpiryRegressionAlgorithm.py
deleted file mode 100644
index 6dd972d8d..000000000
--- a/fincept-qt/scripts/strategies/IndexOptionCallITMExpiryRegressionAlgorithm.py
+++ /dev/null
@@ -1,103 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-EA1D90BB
-# Category: Options
-# Description: This regression algorithm tests In The Money (ITM) index option expiry for calls. We expect 2 orders from the algorit...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### This regression algorithm tests In The Money (ITM) index option expiry for calls.
-### We expect 2 orders from the algorithm, which are:
-###
-### * Initial entry, buy SPX Call Option (expiring ITM)
-### * Option exercise, settles into cash
-###
-### Additionally, we test delistings for index options and assert that our
-### portfolio holdings reflect the orders the algorithm has submitted.
-### </summary>
-class IndexOptionCallITMExpiryRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2021, 1, 4)
- self.set_end_date(2021, 1, 31)
- self.set_cash(100000)
-
- self.spx = self.add_index("SPX", Resolution.MINUTE).symbol
-
- # Select an index option expiring ITM, and adds it to the algorithm.
- self.spx_option = list(self.option_chain(self.spx))
- self.spx_option = [i for i in self.spx_option if i.id.strike_price <= 3200 and i.id.option_right == OptionRight.CALL and i.id.date.year == 2021 and i.id.date.month == 1]
- self.spx_option = list(sorted(self.spx_option, key=lambda x: x.id.strike_price, reverse=True))[0]
- self.spx_option = self.add_index_option_contract(self.spx_option, Resolution.MINUTE).symbol
-
- self.expected_option_contract = Symbol.create_option(self.spx, Market.USA, OptionStyle.EUROPEAN, OptionRight.CALL, 3200, datetime(2021, 1, 15))
- if self.spx_option != self.expected_option_contract:
- raise Exception(f"Contract {self.expected_option_contract} was not found in the chain")
-
- self.schedule.on(
- self.date_rules.tomorrow,
- self.time_rules.after_market_open(self.spx, 1),
- lambda: self.market_order(self.spx_option, 1)
- )
-
- def on_data(self, data: Slice):
- # Assert delistings, so that we can make sure that we receive the delisting warnings at
- # the expected time. These assertions detect bug #4872
- for delisting in data.delistings.values():
- if delisting.type == DelistingType.WARNING:
- if delisting.time != datetime(2021, 1, 15):
- raise Exception(f"Delisting warning issued at unexpected date: {delisting.time}")
-
- if delisting.type == DelistingType.DELISTED:
- if delisting.time != datetime(2021, 1, 16):
- raise Exception(f"Delisting happened at unexpected date: {delisting.time}")
-
- def on_order_event(self, order_event: OrderEvent):
- if order_event.status != OrderStatus.FILLED:
- # There's lots of noise with OnOrderEvent, but we're only interested in fills.
- return
-
- if order_event.symbol not in self.securities:
- raise Exception(f"Order event Symbol not found in Securities collection: {order_event.symbol}")
-
- security = self.securities[order_event.symbol]
- if security.symbol == self.spx:
- self.assert_index_option_order_exercise(order_event, security, self.securities[self.expected_option_contract])
- elif security.symbol == self.expected_option_contract:
- self.assert_index_option_contract_order(order_event, security)
- else:
- raise Exception(f"Received order event for unknown Symbol: {order_event.symbol}")
-
- self.log(f"{self.time} -- {order_event.symbol} :: Price: {self.securities[order_event.symbol].holdings.price} Qty: {self.securities[order_event.symbol].holdings.quantity} Direction: {order_event.direction} Msg: {order_event.message}")
-
- def assert_index_option_order_exercise(self, order_event: OrderEvent, index: Security, option_contract: Security):
- # No way to detect option exercise orders or any other kind of special orders
- # other than matching strings, for now.
- if "Option Exercise" in order_event.message:
- if order_event.fill_price != 3200:
- raise Exception("Option did not exercise at expected strike price (3200)")
-
- if option_contract.holdings.quantity != 0:
- raise Exception(f"Exercised option contract, but we have holdings for Option contract {option_contract.symbol}")
-
- def assert_index_option_contract_order(self, order_event: OrderEvent, option: Security):
- if order_event.direction == OrderDirection.BUY and option.holdings.quantity != 1:
- raise Exception(f"No holdings were created for option contract {option.symbol}")
- if order_event.direction == OrderDirection.SELL and option.holdings.quantity != 0:
- raise Exception(f"Holdings were found after a filled option exercise")
- if "Exercise" in order_event.message and option.holdings.quantity != 0:
- raise Exception(f"Holdings were found after exercising option contract {option.symbol}")
-
- ### <summary>
- ### Ran at the end of the algorithm to ensure the algorithm has no holdings
- ### </summary>
- ### <exception cref="Exception">The algorithm has holdings</exception>
- def on_end_of_algorithm(self):
- if self.portfolio.invested:
- raise Exception(f"Expected no holdings at end of algorithm, but are invested in: {', '.join(self.portfolio.keys())}")
diff --git a/fincept-qt/scripts/strategies/IndexOptionCallITMGreeksExpiryRegressionAlgorithm.py b/fincept-qt/scripts/strategies/IndexOptionCallITMGreeksExpiryRegressionAlgorithm.py
deleted file mode 100644
index 29ee951c4..000000000
--- a/fincept-qt/scripts/strategies/IndexOptionCallITMGreeksExpiryRegressionAlgorithm.py
+++ /dev/null
@@ -1,108 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-32C0EE95
-# Category: Options
-# Description: This regression algorithm tests In The Money (ITM) index option expiry for calls. We test to make sure that index opt...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### This regression algorithm tests In The Money (ITM) index option expiry for calls.
-### We test to make sure that index options have greeks enabled, same as equity options.
-### </summary>
-class IndexOptionCallITMGreeksExpiryRegressionAlgorithm(QCAlgorithm):
- def initialize(self):
- self.on_data_calls = 0
- self.invested = False
-
- self.set_start_date(2021, 1, 4)
- self.set_end_date(2021, 1, 31)
-
- spx = self.add_index("SPX", Resolution.MINUTE)
- spx.volatility_model = StandardDeviationOfReturnsVolatilityModel(60, Resolution.MINUTE, timedelta(minutes=1))
- self.spx = spx.symbol
-
- # Select a index option call expiring ITM, and adds it to the algorithm.
- self.spx_option = list(self.option_chain(self.spx))
- self.spx_option = [i for i in self.spx_option if i.id.strike_price <= 3200 and i.id.option_right == OptionRight.CALL and i.id.date.year == 2021 and i.id.date.month == 1]
- self.spx_option = list(sorted(self.spx_option, key=lambda x: x.id.strike_price, reverse=True))[0]
- self.spx_option = self.add_index_option_contract(self.spx_option, Resolution.MINUTE)
-
- self.spx_option.price_model = OptionPriceModels.black_scholes()
-
- self.expected_option_contract = Symbol.create_option(self.spx, Market.USA, OptionStyle.EUROPEAN, OptionRight.CALL, 3200, datetime(2021, 1, 15))
- if self.spx_option.symbol != self.expected_option_contract:
- raise Exception(f"Contract {self.expected_option_contract} was not found in the chain")
-
- def on_data(self, data: Slice):
- # Let the algo warmup, but without using SetWarmup. Otherwise, we get
- # no contracts in the option chain
- if self.invested or self.on_data_calls < 40:
- self.on_data_calls += 1
- return
-
- self.on_data_calls += 1
-
- if data.option_chains.count == 0:
- return
-
- if all([any([c.symbol not in data for c in o.contracts.values()]) for o in data.option_chains.values()]):
- return
-
- if len(list(list(data.option_chains.values())[0].contracts.values())) == 0:
- raise Exception(f"No contracts found in the option {list(data.option_chains.keys())[0]}")
-
- deltas = [i.greeks.delta for i in self.sort_by_max_volume(data)]
- gammas = [i.greeks.gamma for i in self.sort_by_max_volume(data)] #data.option_chains.values().order_by_descending(y => y.contracts.values().sum(x => x.volume)).first().contracts.values().select(x => x.greeks.gamma).to_list()
- lambda_ = [i.greeks.lambda_ for i in self.sort_by_max_volume(data)] #data.option_chains.values().order_by_descending(y => y.contracts.values().sum(x => x.volume)).first().contracts.values().select(x => x.greeks.lambda).to_list()
- rho = [i.greeks.rho for i in self.sort_by_max_volume(data)] #data.option_chains.values().order_by_descending(y => y.contracts.values().sum(x => x.volume)).first().contracts.values().select(x => x.greeks.rho).to_list()
- theta = [i.greeks.theta for i in self.sort_by_max_volume(data)] #data.option_chains.values().order_by_descending(y => y.contracts.values().sum(x => x.volume)).first().contracts.values().select(x => x.greeks.theta).to_list()
- vega = [i.greeks.vega for i in self.sort_by_max_volume(data)] #data.option_chains.values().order_by_descending(y => y.contracts.values().sum(x => x.volume)).first().contracts.values().select(x => x.greeks.vega).to_list()
-
- # The commented out test cases all return zero.
- # This is because of failure to evaluate the greeks in the option pricing model, most likely
- # due to us not clearing the default 30 day requirement for the volatility model to start being updated.
- if any([i for i in deltas if i == 0]):
- raise Exception("Option contract Delta was equal to zero")
-
- # Delta is 1, therefore we expect a gamma of 0
- if any([i for i in gammas if i == 0]):
- raise AggregateException("Option contract Gamma was equal to zero")
-
- if any([i for i in lambda_ if lambda_ == 0]):
- raise AggregateException("Option contract Lambda was equal to zero")
-
- if any([i for i in rho if i == 0]):
- raise Exception("Option contract Rho was equal to zero")
-
- if any([i for i in theta if i == 0]):
- raise Exception("Option contract Theta was equal to zero")
-
- # The strike is far away from the underlying asset's price, and we're very close to expiry.
- # Zero is an expected value here.
- if any([i for i in vega if vega == 0]):
- raise AggregateException("Option contract Vega was equal to zero")
-
- if not self.invested:
- self.set_holdings(list(list(data.option_chains.values())[0].contracts.values())[0].symbol, 1)
- self.invested = True
-
- ### <summary>
- ### Ran at the end of the algorithm to ensure the algorithm has no holdings
- ### </summary>
- ### <exception cref="Exception">The algorithm has holdings</exception>
- def on_end_of_algorithm(self):
- if self.portfolio.invested:
- raise Exception(f"Expected no holdings at end of algorithm, but are invested in: {', '.join(self.portfolio.keys())}")
-
- if not self.invested:
- raise Exception(f"Never checked greeks, maybe we have no option data?")
-
- def sort_by_max_volume(self, data: Slice):
- chain = [i for i in sorted(list(data.option_chains.values()), key=lambda x: sum([j.volume for j in x.contracts.values()]), reverse=True)][0]
- return chain.contracts.values()
diff --git a/fincept-qt/scripts/strategies/IndexOptionCallOTMExpiryRegressionAlgorithm.py b/fincept-qt/scripts/strategies/IndexOptionCallOTMExpiryRegressionAlgorithm.py
deleted file mode 100644
index f5458c540..000000000
--- a/fincept-qt/scripts/strategies/IndexOptionCallOTMExpiryRegressionAlgorithm.py
+++ /dev/null
@@ -1,107 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-6AE00A81
-# Category: Options
-# Description: This regression algorithm tests Out of The Money (OTM) index option expiry for calls. We expect 2 orders from the alg...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### This regression algorithm tests Out of The Money (OTM) index option expiry for calls.
-### We expect 2 orders from the algorithm, which are:
-###
-### * Initial entry, buy SPX Call Option (expiring OTM)
-### - contract expires worthless, not exercised, so never opened a position in the underlying
-###
-### * Liquidation of worthless SPX call option (expiring OTM)
-###
-### Additionally, we test delistings for index options and assert that our
-### portfolio holdings reflect the orders the algorithm has submitted.
-### </summary>
-### <remarks>
-### Total Trades in regression algorithm should be 1, but expiration is counted as a trade.
-### See related issue: https://github.com/QuantConnect/Lean/issues/4854
-### </remarks>
-class IndexOptionCallOTMExpiryRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2021, 1, 4)
- self.set_end_date(2021, 1, 31)
-
- self.spx = self.add_index("SPX", Resolution.MINUTE).symbol
-
- # Select a index option call expiring OTM, and adds it to the algorithm.
- self.spx_option = list(self.option_chain(self.spx))
- self.spx_option = [i for i in self.spx_option if i.id.strike_price >= 4250 and i.id.option_right == OptionRight.CALL and i.id.date.year == 2021 and i.id.date.month == 1]
- self.spx_option = list(sorted(self.spx_option, key=lambda x: x.id.strike_price))[0]
- self.spx_option = self.add_index_option_contract(self.spx_option, Resolution.MINUTE).symbol
-
- self.expected_contract = Symbol.create_option(
- self.spx,
- Market.USA,
- OptionStyle.EUROPEAN,
- OptionRight.CALL,
- 4250,
- datetime(2021, 1, 15)
- )
-
- if self.spx_option != self.expected_contract:
- raise Exception(f"Contract {self.expected_contract} was not found in the chain")
-
- self.schedule.on(
- self.date_rules.tomorrow,
- self.time_rules.after_market_open(self.spx, 1),
- lambda: self.market_order(self.spx_option, 1)
- )
-
- def on_data(self, data: Slice):
- # Assert delistings, so that we can make sure that we receive the delisting warnings at
- # the expected time. These assertions detect bug #4872
- for delisting in data.delistings.values():
- if delisting.type == DelistingType.WARNING:
- if delisting.time != datetime(2021, 1, 15):
- raise Exception(f"Delisting warning issued at unexpected date: {delisting.time}")
-
- if delisting.type == DelistingType.DELISTED:
- if delisting.time != datetime(2021, 1, 16):
- raise Exception(f"Delisting happened at unexpected date: {delisting.time}")
-
- def on_order_event(self, order_event: OrderEvent):
- if order_event.status != OrderStatus.FILLED:
- # There's lots of noise with OnOrderEvent, but we're only interested in fills.
- return
-
- if order_event.symbol not in self.securities:
- raise Exception(f"Order event Symbol not found in Securities collection: {order_event.symbol}")
-
- security = self.securities[order_event.symbol]
- if security.symbol == self.spx:
- raise Exception("Invalid state: did not expect a position for the underlying to be opened, since this contract expires OTM")
-
- if security.symbol == self.expected_contract:
- self.assert_index_option_contract_order(order_event, security)
- else:
- raise Exception(f"Received order event for unknown Symbol: {order_event.symbol}")
-
- def assert_index_option_contract_order(self, order_event: OrderEvent, option: Security):
- if order_event.direction == OrderDirection.BUY and option.holdings.quantity != 1:
- raise Exception(f"No holdings were created for option contract {option.symbol}")
- if order_event.direction == OrderDirection.SELL and option.holdings.quantity != 0:
- raise Exception("Holdings were found after a filled option exercise")
- if order_event.direction == OrderDirection.SELL and not "OTM" in order_event.message:
- raise Exception("Contract did not expire OTM")
- if "Exercise" in order_event.message:
- raise Exception("Exercised option, even though it expires OTM")
-
- ### <summary>
- ### Ran at the end of the algorithm to ensure the algorithm has no holdings
- ### </summary>
- ### <exception cref="Exception">The algorithm has holdings</exception>
- def on_end_of_algorithm(self):
- if self.portfolio.invested:
- raise Exception(f"Expected no holdings at end of algorithm, but are invested in: {', '.join(self.portfolio.keys())}")
diff --git a/fincept-qt/scripts/strategies/IndexOptionChainApisConsistencyRegressionAlgorithm.py b/fincept-qt/scripts/strategies/IndexOptionChainApisConsistencyRegressionAlgorithm.py
deleted file mode 100644
index 319d82ffe..000000000
--- a/fincept-qt/scripts/strategies/IndexOptionChainApisConsistencyRegressionAlgorithm.py
+++ /dev/null
@@ -1,27 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-F859111A
-# Category: Options
-# Description: Regression algorithm asserting that the option chain APIs return consistent values for index options. See QCAlgorithm...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from datetime import datetime
-from AlgorithmImports import *
-
-from OptionChainApisConsistencyRegressionAlgorithm import OptionChainApisConsistencyRegressionAlgorithm
-
-### <summary>
-### Regression algorithm asserting that the option chain APIs return consistent values for index options.
-### See QCAlgorithm.OptionChain(Symbol) and QCAlgorithm.OptionChainProvider
-### </summary>
-class IndexOptionChainApisConsistencyRegressionAlgorithm(OptionChainApisConsistencyRegressionAlgorithm):
-
- def get_test_date(self) -> datetime:
- return datetime(2021, 1, 4)
-
- def get_option(self) -> Option:
- return self.add_index_option("SPX")
diff --git a/fincept-qt/scripts/strategies/IndexOptionIronCondorAlgorithm.py b/fincept-qt/scripts/strategies/IndexOptionIronCondorAlgorithm.py
deleted file mode 100644
index 290cbbbe7..000000000
--- a/fincept-qt/scripts/strategies/IndexOptionIronCondorAlgorithm.py
+++ /dev/null
@@ -1,59 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-F5FE9B32
-# Category: Options
-# Description: Index Option Iron Condor Algorithm
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-#endregion
-
-class IndexOptionIronCondorAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2019, 9, 1)
- self.set_end_date(2019, 11, 1)
- self.set_cash(100000)
-
- index = self.add_index("SPX", Resolution.MINUTE).symbol
- option = self.add_index_option(index, "SPXW", Resolution.MINUTE)
- option.set_filter(lambda x: x.weeklys_only().strikes(-5, 5).expiration(0, 14))
- self.spxw = option.symbol
-
- self.bb = self.bb(index, 10, 2, resolution=Resolution.DAILY)
- self.warm_up_indicator(index, self.bb)
-
- def on_data(self, slice: Slice) -> None:
- if self.portfolio.invested: return
-
- # Get the OptionChain
- chain = slice.option_chains.get(self.spxw)
- if not chain: return
-
- # Get the closest expiry date
- expiry = min([x.expiry for x in chain])
- chain = [x for x in chain if x.expiry == expiry]
-
- # Separate the call and put contracts and sort by Strike to find OTM contracts
- calls = sorted([x for x in chain if x.right == OptionRight.CALL], key=lambda x: x.strike, reverse=True)
- puts = sorted([x for x in chain if x.right == OptionRight.PUT], key=lambda x: x.strike)
- if len(calls) < 3 or len(puts) < 3: return
-
- # Create combo order legs
- price = self.bb.price.current.value
- quantity = 1
- if price > self.bb.upper_band.current.value or price < self.bb.lower_band.current.value:
- quantity = -1
-
- legs = [
- Leg.create(calls[0].symbol, quantity),
- Leg.create(puts[0].symbol, quantity),
- Leg.create(calls[2].symbol, -quantity),
- Leg.create(puts[2].symbol, -quantity)
- ]
-
- self.combo_market_order(legs, 10, asynchronous=True)
\ No newline at end of file
diff --git a/fincept-qt/scripts/strategies/IndexOptionModelsConsistencyRegressionAlgorithm.py b/fincept-qt/scripts/strategies/IndexOptionModelsConsistencyRegressionAlgorithm.py
deleted file mode 100644
index b314e54ff..000000000
--- a/fincept-qt/scripts/strategies/IndexOptionModelsConsistencyRegressionAlgorithm.py
+++ /dev/null
@@ -1,47 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-02F5AEAE
-# Category: Options
-# Description: Volatility mean-reversion strategy inspired by options pricing
-# models. Buys when 5-day price standard deviation drops below 80% of 20-day
-# stdev (low vol regime), exits when 5-day exceeds 130% of 20-day (vol spike).
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-class IndexOptionModelsConsistencyRegressionAlgorithm(QCAlgorithm):
- """Volatility mean-reversion: enters in calm markets, exits on vol spikes."""
-
- def initialize(self):
- self.set_start_date(2023, 1, 1)
- self.set_end_date(2024, 1, 1)
- self.set_cash(100000)
-
- self.symbol = "SPY"
- self.add_equity(self.symbol, Resolution.DAILY)
-
- self._fast_std = self.std(self.symbol, 5, Resolution.DAILY)
- self._slow_std = self.std(self.symbol, 20, Resolution.DAILY)
-
- def on_data(self, data):
- if not self._fast_std.is_ready or not self._slow_std.is_ready:
- return
- if self.symbol not in data:
- return
-
- fast_vol = self._fast_std.current.value
- slow_vol = self._slow_std.current.value
-
- if slow_vol == 0:
- return
-
- vol_ratio = fast_vol / slow_vol
-
- if not self.portfolio.invested and vol_ratio < 0.8:
- self.set_holdings(self.symbol, 1)
- elif self.portfolio.invested and vol_ratio > 1.3:
- self.liquidate()
diff --git a/fincept-qt/scripts/strategies/IndexOptionPutButterflyAlgorithm.py b/fincept-qt/scripts/strategies/IndexOptionPutButterflyAlgorithm.py
deleted file mode 100644
index e9f276e12..000000000
--- a/fincept-qt/scripts/strategies/IndexOptionPutButterflyAlgorithm.py
+++ /dev/null
@@ -1,67 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-BFEF2627
-# Category: Options
-# Description: Index Option Put Butterfly Algorithm
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-#endregion
-
-class IndexOptionPutButterflyAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2020, 1, 1)
- self.set_end_date(2021, 1, 1)
- self.set_cash(1000000)
-
- self.vxz = self.add_equity("VXZ", Resolution.MINUTE).symbol
-
- index = self.add_index("SPX", Resolution.MINUTE).symbol
- option = self.add_index_option(index, "SPXW", Resolution.MINUTE)
- option.set_filter(lambda x: x.include_weeklys().strikes(-3, 3).expiration(15, 45))
-
- self.spxw = option.symbol
- self.multiplier = option.symbol_properties.contract_multiplier
- self.tickets = []
-
- def on_data(self, slice: Slice) -> None:
- # The order of magnitude per SPXW order's value is 10000 times of VXZ
- if not self.portfolio[self.vxz].invested:
- self.market_order(self.vxz, 10000)
-
- # Return if any opening index option position
- if any([self.portfolio[x.symbol].invested for x in self.tickets]): return
-
- # Get the OptionChain
- chain = slice.option_chains.get(self.spxw)
- if not chain: return
-
- # Get nearest expiry date
- expiry = min([x.expiry for x in chain])
-
- # Select the put Option contracts with nearest expiry and sort by strike price
- puts = [x for x in chain if x.expiry == expiry and x.right == OptionRight.PUT]
- if len(puts) < 3: return
- sorted_put_strikes = sorted([x.strike for x in puts])
-
- # Select ATM put
- atm_strike = min([abs(x - chain.underlying.value) for x in sorted_put_strikes])
-
- # Get the strike prices for the ITM & OTM contracts, make sure they're in equidistance
- spread = min(atm_strike - sorted_put_strikes[0], sorted_put_strikes[-1] - atm_strike)
- otm_strike = atm_strike - spread
- itm_strike = atm_strike + spread
- if otm_strike not in sorted_put_strikes or itm_strike not in sorted_put_strikes: return
-
- # Buy the put butterfly
- put_butterfly = OptionStrategies.put_butterfly(self.spxw, itm_strike, atm_strike, otm_strike, expiry)
- price = sum([abs(self.securities[x.symbol].price * x.quantity) * self.multiplier for x in put_butterfly.underlying_legs])
- if price > 0:
- quantity = self.portfolio.total_portfolio_value // price
- self.tickets = self.buy(put_butterfly, quantity, asynchronous=True)
-
\ No newline at end of file
diff --git a/fincept-qt/scripts/strategies/IndexOptionPutCalendarSpreadAlgorithm.py b/fincept-qt/scripts/strategies/IndexOptionPutCalendarSpreadAlgorithm.py
deleted file mode 100644
index 9cd81125e..000000000
--- a/fincept-qt/scripts/strategies/IndexOptionPutCalendarSpreadAlgorithm.py
+++ /dev/null
@@ -1,59 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-E0220F96
-# Category: Options
-# Description: Index Option Put Calendar Spread Algorithm
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-class IndexOptionPutCalendarSpreadAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2020, 1, 1)
- self.set_end_date(2023, 1, 1)
- self.set_cash(50000)
-
- self.vxz = self.add_equity("VXZ", Resolution.MINUTE).symbol
-
- index = self.add_index("VIX", Resolution.MINUTE).symbol
- option = self.add_index_option(index, "VIXW", Resolution.MINUTE)
- option.set_filter(lambda x: x.strikes(-2, 2).expiration(15, 45))
-
- self.vixw = option.symbol
- self.tickets = []
- self.expiry = datetime.max
-
- def on_data(self, slice: Slice) -> None:
- if not self.portfolio[self.vxz].invested:
- self.market_order(self.vxz, 100)
-
- index_options_invested = [leg for leg in self.tickets if self.portfolio[leg.symbol].invested]
- # Liquidate if the shorter term option is about to expire
- if self.expiry < self.time + timedelta(2) and all([slice.contains_key(x.symbol) for x in self.tickets]):
- for holding in index_options_invested:
- self.liquidate(holding.symbol)
- # Return if there is any opening index option position
- elif index_options_invested:
- return
-
- # Get the OptionChain
- chain = slice.option_chains.get(self.vixw)
- if not chain: return
-
- # Get ATM strike price
- strike = sorted(chain, key = lambda x: abs(x.strike - chain.underlying.value))[0].strike
-
- # Select the ATM put Option contracts and sort by expiration date
- puts = sorted([i for i in chain if i.strike == strike and i.right == OptionRight.PUT],
- key=lambda x: x.expiry)
- if len(puts) < 2: return
- self.expiry = puts[0].expiry
-
- # Sell the put calendar spread
- put_calendar_spread = OptionStrategies.put_calendar_spread(self.vixw, strike, self.expiry, puts[-1].expiry)
- self.tickets = self.sell(put_calendar_spread, 1, asynchronous=True)
\ No newline at end of file
diff --git a/fincept-qt/scripts/strategies/IndexOptionPutITMExpiryRegressionAlgorithm.py b/fincept-qt/scripts/strategies/IndexOptionPutITMExpiryRegressionAlgorithm.py
deleted file mode 100644
index 2af883ae1..000000000
--- a/fincept-qt/scripts/strategies/IndexOptionPutITMExpiryRegressionAlgorithm.py
+++ /dev/null
@@ -1,100 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-48BF5359
-# Category: Options
-# Description: This regression algorithm tests In The Money (ITM) index option expiry for puts. We expect 2 orders from the algorith...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### This regression algorithm tests In The Money (ITM) index option expiry for puts.
-### We expect 2 orders from the algorithm, which are:
-###
-### * Initial entry, buy ES Put Option (expiring ITM) (buy, qty 1)
-### * Option exercise, receiving cash (sell, qty -1)
-###
-### Additionally, we test delistings for index options and assert that our
-### portfolio holdings reflect the orders the algorithm has submitted.
-### </summary>
-class IndexOptionPutITMExpiryRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2021, 1, 4)
- self.set_end_date(2021, 1, 31)
-
- self.spx = self.add_index("SPX", Resolution.MINUTE).symbol
-
- # Select a index option expiring ITM, and adds it to the algorithm.
- self.spx_option = list(self.option_chain(self.spx))
- self.spx_option = [i for i in self.spx_option if i.id.strike_price >= 4200 and i.id.option_right == OptionRight.PUT and i.id.date.year == 2021 and i.id.date.month == 1]
- self.spx_option = list(sorted(self.spx_option, key=lambda x: x.id.strike_price))[0]
- self.spx_option = self.add_index_option_contract(self.spx_option, Resolution.MINUTE).symbol
-
- self.expected_contract = Symbol.create_option(self.spx, Market.USA, OptionStyle.EUROPEAN, OptionRight.PUT, 4200, datetime(2021, 1, 15))
- if self.spx_option != self.expected_contract:
- raise Exception(f"Contract {self.expected_contract} was not found in the chain")
-
- self.schedule.on(self.date_rules.tomorrow, self.time_rules.after_market_open(self.spx, 1), lambda: self.market_order(self.spx_option, 1))
-
- def on_data(self, data: Slice):
- # Assert delistings, so that we can make sure that we receive the delisting warnings at
- # the expected time. These assertions detect bug #4872
- for delisting in data.delistings.values():
- if delisting.type == DelistingType.WARNING:
- if delisting.time != datetime(2021, 1, 15):
- raise Exception(f"Delisting warning issued at unexpected date: {delisting.time}")
- if delisting.type == DelistingType.DELISTED:
- if delisting.time != datetime(2021, 1, 16):
- raise Exception(f"Delisting happened at unexpected date: {delisting.time}")
-
- def on_order_event(self, order_event: OrderEvent):
- if order_event.status != OrderStatus.FILLED:
- # There's lots of noise with OnOrderEvent, but we're only interested in fills.
- return
-
- if order_event.symbol not in self.securities:
- raise Exception(f"Order event Symbol not found in Securities collection: {order_event.symbol}")
-
- security = self.securities[order_event.symbol]
- if security.symbol == self.spx:
- self.assert_index_option_order_exercise(order_event, security, self.securities[self.expected_contract])
- elif security.symbol == self.expected_contract:
- self.assert_index_option_contract_order(order_event, security)
- else:
- raise Exception(f"Received order event for unknown Symbol: {order_event.symbol}")
-
- def assert_index_option_order_exercise(self, order_event: OrderEvent, index: Security, option_contract: Security):
- expected_liquidation_time_utc = datetime(2021, 1, 15)
-
- if order_event.direction == OrderDirection.BUY and order_event.utc_time != expected_liquidation_time_utc:
- raise Exception(f"Liquidated index option contract, but not at the expected time. Expected: {expected_liquidation_time_utc} - found {order_event.utc_time}")
-
- # No way to detect option exercise orders or any other kind of special orders
- # other than matching strings, for now.
- if "Option Exercise" in order_event.message:
- if order_event.fill_price != 3300:
- raise Exception("Option did not exercise at expected strike price (3300)")
-
- if option_contract.holdings.quantity != 0:
- raise Exception(f"Exercised option contract, but we have holdings for Option contract {option_contract.symbol}")
-
- def assert_index_option_contract_order(self, order_event: OrderEvent, option: Security):
- if order_event.direction == OrderDirection.BUY and option.holdings.quantity != 1:
- raise Exception(f"No holdings were created for option contract {option.symbol}")
- if order_event.direction == OrderDirection.SELL and option.holdings.quantity != 0:
- raise Exception(f"Holdings were found after a filled option exercise")
- if "Exercise" in order_event.message and option.holdings.quantity != 0:
- raise Exception(f"Holdings were found after exercising option contract {option.symbol}")
-
- ### <summary>
- ### Ran at the end of the algorithm to ensure the algorithm has no holdings
- ### </summary>
- ### <exception cref="Exception">The algorithm has holdings</exception>
- def on_end_of_algorithm(self):
- if self.portfolio.invested:
- raise Exception(f"Expected no holdings at end of algorithm, but are invested in: {', '.join(self.portfolio.keys())}")
diff --git a/fincept-qt/scripts/strategies/IndexOptionPutOTMExpiryRegressionAlgorithm.py b/fincept-qt/scripts/strategies/IndexOptionPutOTMExpiryRegressionAlgorithm.py
deleted file mode 100644
index 910a1dbb8..000000000
--- a/fincept-qt/scripts/strategies/IndexOptionPutOTMExpiryRegressionAlgorithm.py
+++ /dev/null
@@ -1,107 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-4666C54E
-# Category: Options
-# Description: This regression algorithm tests Out of The Money (OTM) index option expiry for calls. We expect 2 orders from the alg...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### This regression algorithm tests Out of The Money (OTM) index option expiry for calls.
-### We expect 2 orders from the algorithm, which are:
-###
-### * Initial entry, buy SPX Call Option (expiring OTM)
-### - contract expires worthless, not exercised, so never opened a position in the underlying
-###
-### * Liquidation of worthless SPX call option (expiring OTM)
-###
-### Additionally, we test delistings for index options and assert that our
-### portfolio holdings reflect the orders the algorithm has submitted.
-### </summary>
-### <remarks>
-### Total Trades in regression algorithm should be 1, but expiration is counted as a trade.
-### See related issue: https://github.com/QuantConnect/Lean/issues/4854
-### </remarks>
-class IndexOptionCallOTMExpiryRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2021, 1, 4)
- self.set_end_date(2021, 1, 31)
-
- self.spx = self.add_index("SPX", Resolution.MINUTE).symbol
-
- # Select a index option call expiring OTM, and adds it to the algorithm.
- self.spx_option = list(self.option_chain(self.spx))
- self.spx_option = [i for i in self.spx_option if i.id.strike_price <= 3200 and i.id.option_right == OptionRight.PUT and i.id.date.year == 2021 and i.id.date.month == 1]
- self.spx_option = list(sorted(self.spx_option, key=lambda x: x.id.strike_price, reverse=True))[0]
- self.spx_option = self.add_index_option_contract(self.spx_option, Resolution.MINUTE).symbol
-
- self.expected_contract = Symbol.create_option(
- self.spx,
- Market.USA,
- OptionStyle.EUROPEAN,
- OptionRight.PUT,
- 3200,
- datetime(2021, 1, 15)
- )
-
- if self.spx_option != self.expected_contract:
- raise Exception(f"Contract {self.expected_contract} was not found in the chain")
-
- self.schedule.on(
- self.date_rules.tomorrow,
- self.time_rules.after_market_open(self.spx, 1),
- lambda: self.market_order(self.spx_option, 1)
- )
-
- def on_data(self, data: Slice):
- # Assert delistings, so that we can make sure that we receive the delisting warnings at
- # the expected time. These assertions detect bug #4872
- for delisting in data.delistings.values():
- if delisting.type == DelistingType.WARNING:
- if delisting.time != datetime(2021, 1, 15):
- raise Exception(f"Delisting warning issued at unexpected date: {delisting.time}")
-
- if delisting.type == DelistingType.DELISTED:
- if delisting.time != datetime(2021, 1, 16):
- raise Exception(f"Delisting happened at unexpected date: {delisting.time}")
-
- def on_order_event(self, order_event: OrderEvent):
- if order_event.status != OrderStatus.FILLED:
- # There's lots of noise with OnOrderEvent, but we're only interested in fills.
- return
-
- if order_event.symbol not in self.securities:
- raise Exception(f"Order event Symbol not found in Securities collection: {order_event.symbol}")
-
- security = self.securities[order_event.symbol]
- if security.symbol == self.spx:
- raise Exception("Invalid state: did not expect a position for the underlying to be opened, since this contract expires OTM")
-
- if security.symbol == self.expected_contract:
- self.assert_index_option_contract_order(order_event, security)
- else:
- raise Exception(f"Received order event for unknown Symbol: {order_event.symbol}")
-
- def assert_index_option_contract_order(self, order_event: OrderEvent, option: Security):
- if order_event.direction == OrderDirection.BUY and option.holdings.quantity != 1:
- raise Exception(f"No holdings were created for option contract {option.symbol}")
- if order_event.direction == OrderDirection.SELL and option.holdings.quantity != 0:
- raise Exception("Holdings were found after a filled option exercise")
- if order_event.direction == OrderDirection.SELL and not "OTM" in order_event.message:
- raise Exception("Contract did not expire OTM")
- if "Exercise" in order_event.message:
- raise Exception("Exercised option, even though it expires OTM")
-
- ### <summary>
- ### Ran at the end of the algorithm to ensure the algorithm has no holdings
- ### </summary>
- ### <exception cref="Exception">The algorithm has holdings</exception>
- def on_end_of_algorithm(self):
- if self.portfolio.invested:
- raise Exception(f"Expected no holdings at end of algorithm, but are invested in: {', '.join(self.portfolio.keys())}")
diff --git a/fincept-qt/scripts/strategies/IndexOptionShortCallITMExpiryRegressionAlgorithm.py b/fincept-qt/scripts/strategies/IndexOptionShortCallITMExpiryRegressionAlgorithm.py
deleted file mode 100644
index d9cf95b8b..000000000
--- a/fincept-qt/scripts/strategies/IndexOptionShortCallITMExpiryRegressionAlgorithm.py
+++ /dev/null
@@ -1,104 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-300B9FC2
-# Category: Options
-# Description: This regression algorithm tests In The Money (ITM) index option expiry for short calls. We expect 2 orders from the a...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### This regression algorithm tests In The Money (ITM) index option expiry for short calls.
-### We expect 2 orders from the algorithm, which are:
-###
-### * Initial entry, sell SPX Call Option (expiring ITM)
-### * Option assignment
-###
-### Additionally, we test delistings for index options and assert that our
-### portfolio holdings reflect the orders the algorithm has submitted.
-### </summary>
-class IndexOptionShortCallITMExpiryRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2021, 1, 4)
- self.set_end_date(2021, 1, 31)
- self.set_cash(1000000)
-
- self.portfolio.set_margin_call_model(MarginCallModel.NULL);
-
- # avoid getting assigned
- self.set_security_initializer(CompositeSecurityInitializer(self.security_initializer, FuncSecurityInitializer(self.custom_security_initializer)))
-
- self.spx = self.add_index("SPX", Resolution.MINUTE).symbol
-
- # Select a index option expiring ITM, and adds it to the algorithm.
- self.spx_option = list(self.option_chain(self.spx))
- self.spx_option = [i for i in self.spx_option if i.id.strike_price <= 3200 and i.id.option_right == OptionRight.CALL and i.id.date.year == 2021 and i.id.date.month == 1]
- self.spx_option = list(sorted(self.spx_option, key=lambda x: x.id.strike_price, reverse=True))[0]
- self.spx_option = self.add_index_option_contract(self.spx_option, Resolution.MINUTE).symbol
-
- self.expected_contract = Symbol.create_option(self.spx, Market.USA, OptionStyle.EUROPEAN, OptionRight.CALL, 3200, datetime(2021, 1, 15))
- if self.spx_option != self.expected_contract:
- raise Exception(f"Contract self.expected_contract was not found in the chain")
-
- self.schedule.on(self.date_rules.tomorrow, self.time_rules.after_market_open(self.spx, 1), lambda: self.market_order(self.spx_option, -1))
-
- def on_data(self, data: Slice):
- # Assert delistings, so that we can make sure that we receive the delisting warnings at
- # the expected time. These assertions detect bug #4872
- for delisting in data.delistings.values():
- if delisting.type == DelistingType.WARNING:
- if delisting.time != datetime(2021, 1, 15):
- raise Exception(f"Delisting warning issued at unexpected date: {delisting.time}")
-
- if delisting.type == DelistingType.DELISTED:
- if delisting.time != datetime(2021, 1, 16):
- raise Exception(f"Delisting happened at unexpected date: {delisting.time}")
-
- def on_order_event(self, order_event: OrderEvent):
- if order_event.status != OrderStatus.FILLED:
- # There's lots of noise with OnOrderEvent, but we're only interested in fills.
- return
-
-
- if order_event.symbol not in self.securities:
- raise Exception(f"Order event Symbol not found in Securities collection: {order_event.symbol}")
-
- security = self.securities[order_event.symbol]
- if security.symbol == self.spx:
- self.assert_index_option_order_exercise(order_event, security, self.securities[self.expected_contract])
- elif security.symbol == self.expected_contract:
- self.assert_index_option_contract_order(order_event, security)
- else:
- raise Exception(f"Received order event for unknown Symbol: {order_event.symbol}")
-
- def assert_index_option_order_exercise(self, order_event: OrderEvent, index: Security, option_contract: Security):
- if "Assignment" in order_event.message:
- if order_event.fill_price != 3200:
- raise Exception("Option was not assigned at expected strike price (3200)")
-
- if order_event.direction != OrderDirection.SELL or index.holdings.quantity != 0:
- raise Exception(f"Expected Qty: 0 index holdings for assigned index option {index.symbol}, found {index.holdings.quantity}")
-
- def assert_index_option_contract_order(self, order_event: OrderEvent, option: Security):
- if order_event.direction == OrderDirection.SELL and option.holdings.quantity != -1:
- raise Exception(f"No holdings were created for option contract {option.symbol}")
-
- if order_event.is_assignment and option.holdings.quantity != 0:
- raise Exception(f"Holdings were found after option contract was assigned: {option.symbol}")
-
- ### <summary>
- ### Ran at the end of the algorithm to ensure the algorithm has no holdings
- ### </summary>
- ### <exception cref="Exception">The algorithm has holdings</exception>
- def on_end_of_algorithm(self):
- if self.portfolio.invested:
- raise Exception(f"Expected no holdings at end of algorithm, but are invested in: {', '.join(self.portfolio.keys())}")
-
- def custom_security_initializer(self, security):
- if Extensions.is_option(security.symbol.security_type):
- security.set_option_assignment_model(NullOptionAssignmentModel())
diff --git a/fincept-qt/scripts/strategies/IndexOptionShortCallOTMExpiryRegressionAlgorithm.py b/fincept-qt/scripts/strategies/IndexOptionShortCallOTMExpiryRegressionAlgorithm.py
deleted file mode 100644
index 1b9ffadd5..000000000
--- a/fincept-qt/scripts/strategies/IndexOptionShortCallOTMExpiryRegressionAlgorithm.py
+++ /dev/null
@@ -1,89 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-57548DAA
-# Category: Options
-# Description: This regression algorithm tests Out of The Money (OTM) index option expiry for short calls. We expect 2 orders from t...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### This regression algorithm tests Out of The Money (OTM) index option expiry for short calls.
-### We expect 2 orders from the algorithm, which are:
-###
-### * Initial entry, sell SPX Call Option (expiring OTM)
-### - Profit the option premium, since the option was not assigned.
-###
-### * Liquidation of SPX call OTM contract on the last trade date
-###
-### Additionally, we test delistings for index options and assert that our
-### portfolio holdings reflect the orders the algorithm has submitted.
-### </summary>
-class IndexOptionShortCallOTMExpiryRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2021, 1, 4)
- self.set_end_date(2021, 1, 31)
-
- self.spx = self.add_index("SPX", Resolution.MINUTE).symbol
-
- # Select a index option expiring ITM, and adds it to the algorithm.
- self.spx_option = list(self.option_chain(self.spx))
- self.spx_option = [i for i in self.spx_option if i.id.strike_price >= 4250 and i.id.option_right == OptionRight.CALL and i.id.date.year == 2021 and i.id.date.month == 1]
- self.spx_option = list(sorted(self.spx_option, key=lambda x: x.id.strike_price))[0]
- self.spx_option = self.add_index_option_contract(self.spx_option, Resolution.MINUTE).symbol
-
- self.expected_contract = Symbol.create_option(self.spx, Market.USA, OptionStyle.EUROPEAN, OptionRight.CALL, 4250, datetime(2021, 1, 15))
- if self.spx_option != self.expected_contract:
- raise Exception(f"Contract {self.expected_contract} was not found in the chain")
-
- self.schedule.on(self.date_rules.tomorrow, self.time_rules.after_market_open(self.spx, 1), lambda: self.market_order(self.spx_option, -1))
-
- def on_data(self, data: Slice):
- # Assert delistings, so that we can make sure that we receive the delisting warnings at
- # the expected time. These assertions detect bug #4872
- for delisting in data.delistings.values():
- if delisting.type == DelistingType.WARNING:
- if delisting.time != datetime(2021, 1, 15):
- raise Exception(f"Delisting warning issued at unexpected date: {delisting.time}")
-
- if delisting.type == DelistingType.DELISTED:
- if delisting.time != datetime(2021, 1, 16):
- raise Exception(f"Delisting happened at unexpected date: {delisting.time}")
-
- def on_order_event(self, order_event: OrderEvent):
- if order_event.status != OrderStatus.FILLED:
- # There's lots of noise with OnOrderEvent, but we're only interested in fills.
- return
-
- if order_event.symbol not in self.securities:
- raise Exception(f"Order event Symbol not found in Securities collection: {order_event.symbol}")
-
- security = self.securities[order_event.symbol]
- if security.symbol == self.spx:
- raise Exception(f"Expected no order events for underlying Symbol {security.symbol}")
-
- if security.symbol == self.expected_contract:
- self.assert_index_option_contract_order(order_event, security)
- else:
- raise Exception(f"Received order event for unknown Symbol: {order_event.symbol}")
-
- def assert_index_option_contract_order(self, order_event: OrderEvent, option_contract: Security):
- if order_event.direction == OrderDirection.SELL and option_contract.holdings.quantity != -1:
- raise Exception(f"No holdings were created for option contract {option_contract.symbol}")
- if order_event.direction == OrderDirection.BUY and option_contract.holdings.quantity != 0:
- raise Exception("Expected no options holdings after closing position")
- if order_event.is_assignment:
- raise Exception(f"Assignment was not expected for {order_event.symbol}")
-
- ### <summary>
- ### Ran at the end of the algorithm to ensure the algorithm has no holdings
- ### </summary>
- ### <exception cref="Exception">The algorithm has holdings</exception>
- def on_end_of_algorithm(self):
- if self.portfolio.invested:
- raise Exception(f"Expected no holdings at end of algorithm, but are invested in: {', '.join(self.portfolio.keys())}")
diff --git a/fincept-qt/scripts/strategies/IndexOptionShortPutITMExpiryRegressionAlgorithm.py b/fincept-qt/scripts/strategies/IndexOptionShortPutITMExpiryRegressionAlgorithm.py
deleted file mode 100644
index bf3d151c1..000000000
--- a/fincept-qt/scripts/strategies/IndexOptionShortPutITMExpiryRegressionAlgorithm.py
+++ /dev/null
@@ -1,106 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-D0643727
-# Category: Options
-# Description: This regression algorithm tests In The Money (ITM) index option expiry for short calls. We expect 2 orders from the a...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### This regression algorithm tests In The Money (ITM) index option expiry for short calls.
-### We expect 2 orders from the algorithm, which are:
-###
-### * Initial entry, sell SPX Call Option (expiring ITM)
-### * Option assignment
-###
-### Additionally, we test delistings for index options and assert that our
-### portfolio holdings reflect the orders the algorithm has submitted.
-### </summary>
-class IndexOptionShortCallITMExpiryRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2021, 1, 4)
- self.set_end_date(2021, 1, 31)
- self.set_cash(1000000)
-
- self.portfolio.set_margin_call_model(MarginCallModel.NULL);
-
- # avoid getting assigned
- self.set_security_initializer(CompositeSecurityInitializer(self.security_initializer, FuncSecurityInitializer(self.custom_security_initializer)))
-
- self.spx = self.add_index("SPX", Resolution.MINUTE).symbol
-
- # Select a index option expiring ITM, and adds it to the algorithm.
- self.spx_option = list(self.option_chain(self.spx))
- self.spx_option = [i for i in self.spx_option if i.id.strike_price <= 4200 and i.id.option_right == OptionRight.PUT and i.id.date.year == 2021 and i.id.date.month == 1]
- self.spx_option = list(sorted(self.spx_option, key=lambda x: x.id.strike_price, reverse=True))[0]
- self.spx_option = self.add_index_option_contract(self.spx_option, Resolution.MINUTE).symbol
-
- self.expected_contract = Symbol.create_option(self.spx, Market.USA, OptionStyle.EUROPEAN, OptionRight.PUT, 4200, datetime(2021, 1, 15))
- if self.spx_option != self.expected_contract:
- raise Exception(f"Contract self.expected_contract was not found in the chain")
-
- self.schedule.on(self.date_rules.tomorrow, self.time_rules.after_market_open(self.spx, 1), lambda: self.market_order(self.spx_option, -1))
-
- def on_data(self, data: Slice):
- # Assert delistings, so that we can make sure that we receive the delisting warnings at
- # the expected time. These assertions detect bug #4872
- for delisting in data.delistings.values():
- if delisting.type == DelistingType.WARNING:
- if delisting.time != datetime(2021, 1, 15):
- raise Exception(f"Delisting warning issued at unexpected date: {delisting.time}")
-
- if delisting.type == DelistingType.DELISTED:
- if delisting.time != datetime(2021, 1, 16):
- raise Exception(f"Delisting happened at unexpected date: {delisting.time}")
-
- def on_order_event(self, order_event: OrderEvent):
- if order_event.status != OrderStatus.FILLED:
- # There's lots of noise with OnOrderEvent, but we're only interested in fills.
- return
-
- if order_event.symbol not in self.securities:
- raise Exception(f"Order event Symbol not found in Securities collection: {order_event.symbol}")
-
- security = self.securities[order_event.symbol]
- if security.symbol == self.spx:
- self.assert_index_option_order_exercise(order_event, security, self.securities[self.expected_contract])
- elif security.symbol == self.expected_contract:
- self.assert_index_option_contract_order(order_event, security)
- else:
- raise Exception(f"Received order event for unknown Symbol: {order_event.symbol}")
-
- def assert_index_option_order_exercise(self, order_event: OrderEvent, index: Security, option_contract: Security):
- if "Assignment" in order_event.message:
- if order_event.fill_price != 4200:
- raise Exception("Option was not assigned at expected strike price (4200)")
-
- if order_event.direction != OrderDirection.SELL or index.holdings.quantity != 0:
- raise Exception(f"Expected Qty: 0 index holdings for assigned index option {index.symbol}, found {index.holdings.quantity}")
-
- elif index.holdings.quantity != 0:
- raise Exception(f"Expected no holdings in index: {index.symbol}")
-
- def assert_index_option_contract_order(self, order_event: OrderEvent, option: Security):
- if order_event.direction == OrderDirection.SELL and option.holdings.quantity != -1:
- raise Exception(f"No holdings were created for option contract {option.symbol}")
-
- if order_event.is_assignment and option.holdings.quantity != 0:
- raise Exception(f"Holdings were found after option contract was assigned: {option.symbol}")
-
- ### <summary>
- ### Ran at the end of the algorithm to ensure the algorithm has no holdings
- ### </summary>
- ### <exception cref="Exception">The algorithm has holdings</exception>
- def on_end_of_algorithm(self):
- if self.portfolio.invested:
- raise Exception(f"Expected no holdings at end of algorithm, but are invested in: {', '.join(self.portfolio.keys())}")
-
- def custom_security_initializer(self, security):
- if Extensions.is_option(security.symbol.security_type):
- security.set_option_assignment_model(NullOptionAssignmentModel())
diff --git a/fincept-qt/scripts/strategies/IndexOptionShortPutOTMExpiryRegressionAlgorithm.py b/fincept-qt/scripts/strategies/IndexOptionShortPutOTMExpiryRegressionAlgorithm.py
deleted file mode 100644
index 350e06056..000000000
--- a/fincept-qt/scripts/strategies/IndexOptionShortPutOTMExpiryRegressionAlgorithm.py
+++ /dev/null
@@ -1,89 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-905BC971
-# Category: Options
-# Description: This regression algorithm tests Out of The Money (OTM) index option expiry for short calls. We expect 2 orders from t...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### This regression algorithm tests Out of The Money (OTM) index option expiry for short calls.
-### We expect 2 orders from the algorithm, which are:
-###
-### * Initial entry, sell SPX Call Option (expiring OTM)
-### - Profit the option premium, since the option was not assigned.
-###
-### * Liquidation of SPX call OTM contract on the last trade date
-###
-### Additionally, we test delistings for index options and assert that our
-### portfolio holdings reflect the orders the algorithm has submitted.
-### </summary>
-class IndexOptionShortCallOTMExpiryRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2021, 1, 4)
- self.set_end_date(2021, 1, 31)
-
- self.spx = self.add_index("SPX", Resolution.MINUTE).symbol
-
- # Select a index option expiring ITM, and adds it to the algorithm.
- self.spx_option = list(self.option_chain(self.spx))
- self.spx_option = [i for i in self.spx_option if i.id.strike_price <= 3200 and i.id.option_right == OptionRight.PUT and i.id.date.year == 2021 and i.id.date.month == 1]
- self.spx_option = list(sorted(self.spx_option, key=lambda x: x.id.strike_price, reverse=True))[0]
- self.spx_option = self.add_index_option_contract(self.spx_option, Resolution.MINUTE).symbol
-
- self.expected_contract = Symbol.create_option(self.spx, Market.USA, OptionStyle.EUROPEAN, OptionRight.PUT, 3200, datetime(2021, 1, 15))
- if self.spx_option != self.expected_contract:
- raise Exception(f"Contract {self.expected_contract} was not found in the chain")
-
- self.schedule.on(self.date_rules.tomorrow, self.time_rules.after_market_open(self.spx, 1), lambda: self.market_order(self.spx_option, -1))
-
- def on_data(self, data: Slice):
- # Assert delistings, so that we can make sure that we receive the delisting warnings at
- # the expected time. These assertions detect bug #4872
- for delisting in data.delistings.values():
- if delisting.type == DelistingType.WARNING:
- if delisting.time != datetime(2021, 1, 15):
- raise Exception(f"Delisting warning issued at unexpected date: {delisting.time}")
-
- if delisting.type == DelistingType.DELISTED:
- if delisting.time != datetime(2021, 1, 16):
- raise Exception(f"Delisting happened at unexpected date: {delisting.time}")
-
- def on_order_event(self, order_event: OrderEvent):
- if order_event.status != OrderStatus.FILLED:
- # There's lots of noise with OnOrderEvent, but we're only interested in fills.
- return
-
- if order_event.symbol not in self.securities:
- raise Exception(f"Order event Symbol not found in Securities collection: {order_event.symbol}")
-
- security = self.securities[order_event.symbol]
- if security.symbol == self.spx:
- raise Exception(f"Expected no order events for underlying Symbol {security.symbol}")
-
- if security.symbol == self.expected_contract:
- self.assert_index_option_contract_order(order_event, security)
- else:
- raise Exception(f"Received order event for unknown Symbol: {order_event.symbol}")
-
- def assert_index_option_contract_order(self, order_event: OrderEvent, option_contract: Security):
- if order_event.direction == OrderDirection.SELL and option_contract.holdings.quantity != -1:
- raise Exception(f"No holdings were created for option contract {option_contract.symbol}")
- if order_event.direction == OrderDirection.BUY and option_contract.holdings.quantity != 0:
- raise Exception("Expected no options holdings after closing position")
- if order_event.is_assignment:
- raise Exception(f"Assignment was not expected for {order_event.symbol}")
-
- ### <summary>
- ### Ran at the end of the algorithm to ensure the algorithm has no holdings
- ### </summary>
- ### <exception cref="Exception">The algorithm has holdings</exception>
- def on_end_of_algorithm(self):
- if self.portfolio.invested:
- raise Exception(f"Expected no holdings at end of algorithm, but are invested in: {', '.join(self.portfolio.keys())}")
diff --git a/fincept-qt/scripts/strategies/IndiaDataRegressionAlgorithm.py b/fincept-qt/scripts/strategies/IndiaDataRegressionAlgorithm.py
deleted file mode 100644
index 5160c52f6..000000000
--- a/fincept-qt/scripts/strategies/IndiaDataRegressionAlgorithm.py
+++ /dev/null
@@ -1,74 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-EB8CE077
-# Category: Regression Test
-# Description: Basic template framework algorithm uses framework components to define the algorithm
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Basic template framework algorithm uses framework components to define the algorithm.
-### </summary>
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="using quantconnect" />
-### <meta name="tag" content="trading and orders" />
-class IndiaDataRegressionAlgorithm(QCAlgorithm):
- '''Basic template framework algorithm uses framework components to define the algorithm.'''
-
- def initialize(self):
- '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
-
- self.set_account_currency("INR")
- self.set_start_date(2004, 5, 20)
- self.set_end_date(2016, 7, 26)
- self._mapping_symbol = self.add_equity("3MINDIA", Resolution.DAILY, Market.INDIA).symbol
- self._split_and_dividend_symbol = self.add_equity("CCCL", Resolution.DAILY, Market.INDIA).symbol
- self._received_warning_event = False
- self._received_occurred_event = False
- self._initial_mapping = False
- self._execution_mapping = False
- self.debug("numpy test >>> print numpy.pi: " + str(np.pi))
-
- def on_dividends(self, dividends: Dividends):
- if dividends.contains_key(self._split_and_dividend_symbol):
- dividend = dividends[self._split_and_dividend_symbol]
- if ((self.time.year == 2010 and self.time.month == 6 and self.time.day == 15) and
- (dividend.price != 0.5 or dividend.reference_price != 88.8 or dividend.distribution != 0.5)):
- raise Exception("Did not receive expected dividend values")
-
- def on_splits(self, splits: Splits):
- if splits.contains_key(self._split_and_dividend_symbol):
- split = splits[self._split_and_dividend_symbol]
- if split.type == SplitType.WARNING:
- self._received_warning_event = True
- elif split.type == SplitType.SPLIT_OCCURRED:
- self._received_occurred_event = True
- if split.price != 421.0 or split.reference_price != 421.0 or split.split_factor != 0.2:
- raise Exception("Did not receive expected price values")
-
- def on_symbol_changed_events(self, symbols_changed: SymbolChangedEvents):
- if symbols_changed.contains_key(self._mapping_symbol):
- mapping_event = [x.value for x in symbols_changed if x.key.security_type == 1][0]
- if self.time.year == 1999 and self.time.month == 1 and self.time.day == 1:
- self._initial_mapping = True
- elif self.time.year == 2004 and self.time.month == 6 and self.time.day == 15:
- if mapping_event.new_symbol == "3MINDIA" and mapping_event.old_symbol == "BIRLA3M":
- self._execution_mapping = True
-
- def on_end_of_algorithm(self):
- if self._initial_mapping:
- raise Exception("The ticker generated the initial rename event")
-
- if not self._execution_mapping:
- raise Exception("The ticker did not rename throughout the course of its life even though it should have")
-
- if not self._received_occurred_event:
- raise Exception("Did not receive expected split event")
-
- if not self._received_warning_event:
- raise Exception("Did not receive expected split warning event")
diff --git a/fincept-qt/scripts/strategies/IndicatorExtensionsSMAWithCustomIndicatorsRegressionAlgorithm.py b/fincept-qt/scripts/strategies/IndicatorExtensionsSMAWithCustomIndicatorsRegressionAlgorithm.py
deleted file mode 100644
index 0068e5b04..000000000
--- a/fincept-qt/scripts/strategies/IndicatorExtensionsSMAWithCustomIndicatorsRegressionAlgorithm.py
+++ /dev/null
@@ -1,87 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-31D18328
-# Category: Indicators
-# Description: Indicator Extensions S M A With Custom Indicators Regression Algorithm
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-class IndicatorExtensionsSMAWithCustomIndicatorsRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2020, 2, 20)
- self.set_end_date(2020, 4, 20)
- self.qqq = self.add_equity("QQQ", Resolution.DAILY).symbol
- self.range_indicator = RangeIndicator("range1")
- self.range_sma = IndicatorExtensions.sma(self.range_indicator, 5)
-
- self.range_indicator_2 = RangeIndicator2("range2")
- self.range_sma_2 = IndicatorExtensions.sma(self.range_indicator_2, 5)
-
- def on_data(self, data):
- self.range_indicator.update(data.bars.get(self.qqq))
- self.range_indicator_2.update(data.bars.get(self.qqq))
-
- self.debug(f"{self.range_indicator.name} {self.range_indicator.value}")
- self.debug(f"{self.range_sma.name} {self.range_sma.current.value}")
-
- self.debug(f"{self.range_indicator_2.name} {self.range_indicator_2.value}")
- self.debug(f"{self.range_sma_2.name} {self.range_sma_2.current.value}")
-
- def on_end_of_algorithm(self):
- if not self.range_sma.is_ready:
- raise Exception(f"{self.range_sma.name} should have been ready at the end of the algorithm, but it wasn't. The indicator received {self.range_sma.samples} samples.")
-
- if not self.range_sma_2.is_ready:
- raise Exception(f"{self.range_sma_2.name} should have been ready at the end of the algorithm, but it wasn't. The indicator received {self.range_sma_2.samples} samples.")
-
-class RangeIndicator(PythonIndicator):
- def __init__(self, name):
- self.name = name
- self.time = datetime.min
- self.value = 0
- self.is_ready = False;
-
- @property
- def is_ready(self):
- return self._is_ready
-
- @is_ready.setter
- def is_ready(self, value):
- self._is_ready = value
-
- def update(self, bar: TradeBar):
- if bar is None:
- return False
-
- self.value = bar.high - bar.low
- self.time = bar.time
- self.is_ready = True
- self.on_updated(IndicatorDataPoint(bar.end_time, self.value))
- return True
-
-class RangeIndicator2(PythonIndicator):
- def __init__(self, name):
- self.name = name
- self.time = datetime.min
- self.value = 0
- self._is_ready = False;
-
- @property
- def is_ready(self):
- return self._is_ready
-
- def update(self, bar: TradeBar):
- if bar is None:
- return False
-
- self.value = bar.high - bar.low
- self.time = bar.time
- self._is_ready = True
- self.on_updated(IndicatorDataPoint(bar.end_time, self.value))
- return True
diff --git a/fincept-qt/scripts/strategies/IndicatorHistoryAlgorithm.py b/fincept-qt/scripts/strategies/IndicatorHistoryAlgorithm.py
deleted file mode 100644
index 6d4fbde0e..000000000
--- a/fincept-qt/scripts/strategies/IndicatorHistoryAlgorithm.py
+++ /dev/null
@@ -1,56 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-2BC353A9
-# Category: Indicators
-# Description: Demonstration algorithm of indicators history window usage
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Demonstration algorithm of indicators history window usage
-### </summary>
-class IndicatorHistoryAlgorithm(QCAlgorithm):
- '''Demonstration algorithm of indicators history window usage.'''
-
- def initialize(self):
- '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
- self.set_start_date(2013, 1, 1)
- self.set_end_date(2014, 12, 31)
- self.set_cash(25000)
-
- self._symbol = self.add_equity("SPY", Resolution.DAILY).symbol
-
- self.bollinger_bands = self.bb(self._symbol, 20, 2.0, resolution=Resolution.DAILY)
- # Let's keep BB values for a 20 day period
- self.bollinger_bands.window.size = 20
- # Also keep the same period of data for the middle band
- self.bollinger_bands.middle_band.window.size = 20;
-
- def on_data(self, slice: Slice):
- # Let's wait for our indicator to fully initialize and have a full window of history data
- if not self.bollinger_bands.window.is_ready: return
-
- # We can access the current and oldest (in our period) values of the indicator
- self.log(f"Current BB value: {self.bollinger_bands[0].end_time} - {self.bollinger_bands[0].value}")
- self.log(f"Oldest BB value: {self.bollinger_bands[self.bollinger_bands.window.count - 1].end_time} - "
- f"{self.bollinger_bands[self.bollinger_bands.window.count - 1].value}")
-
- # Let's log the BB values for the last 20 days, for demonstration purposes on how it can be enumerated
- for data_point in self.bollinger_bands:
- self.log(f"BB @{data_point.end_time}: {data_point.value}")
-
- # We can also do the same for internal indicators:
- middle_band = self.bollinger_bands.middle_band
- self.log(f"Current BB Middle Band value: {middle_band[0].end_time} - {middle_band[0].value}")
- self.log(f"Oldest BB Middle Band value: {middle_band[middle_band.window.count - 1].end_time} - "
- f"{middle_band[middle_band.window.count - 1].value}")
- for data_point in middle_band:
- self.log(f"BB Middle Band @{data_point.end_time}: {data_point.value}")
-
- # We are done now!
- self.quit()
diff --git a/fincept-qt/scripts/strategies/IndicatorHistoryRegressionAlgorithm.py b/fincept-qt/scripts/strategies/IndicatorHistoryRegressionAlgorithm.py
deleted file mode 100644
index b44e45d68..000000000
--- a/fincept-qt/scripts/strategies/IndicatorHistoryRegressionAlgorithm.py
+++ /dev/null
@@ -1,60 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-B3C67AEA
-# Category: Indicators
-# Description: Regression algorithm asserting the behavior of the indicator history api
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Regression algorithm asserting the behavior of the indicator history api
-### </summary>
-class IndicatorHistoryRegressionAlgorithm(QCAlgorithm):
- '''Regression algorithm asserting the behavior of the indicator history api'''
-
- def initialize(self):
- '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
- self.set_start_date(2013, 1, 1)
- self.set_end_date(2014, 12, 31)
-
- self._symbol = self.add_equity("SPY", Resolution.DAILY).symbol
-
- def on_data(self, slice: Slice):
- self.bollinger_bands = BollingerBands("BB", 20, 2.0, MovingAverageType.SIMPLE)
-
- if self.bollinger_bands.window.is_ready:
- raise ValueError("Unexpected ready bollinger bands state")
-
- indicatorHistory = self.indicator_history(self.bollinger_bands, self._symbol, 50)
-
- self.debug(f"indicatorHistory: {indicatorHistory}")
-
- self.debug(f"data_frame: {indicatorHistory.data_frame}")
-
- if not self.bollinger_bands.window.is_ready:
- raise ValueError("Unexpected not ready bollinger bands state")
-
- # we ask for 50 data points
- if indicatorHistory.count != 50:
- raise ValueError(f"Unexpected indicators values {indicatorHistory.count}")
-
- for indicatorDataPoints in indicatorHistory:
- middle_band = indicatorDataPoints["middle_band"]
- self.debug(f"BB @{indicatorDataPoints.current}: middle_band: {middle_band} upper_band: {indicatorDataPoints.upper_band}")
- if indicatorDataPoints == 0:
- raise ValueError(f"Unexpected indicators point {indicatorDataPoints}")
-
- currentValues = indicatorHistory.current
- if len(currentValues) != 50 or len([x for x in currentValues if x.value == 0]) > 0:
- raise ValueError(f"Unexpected indicators current values {len(currentValues)}")
- upperBandPoints = indicatorHistory["upper_band"]
- if len(upperBandPoints) != 50 or len([x for x in upperBandPoints if x.value == 0]) > 0:
- raise ValueError(f"Unexpected indicators upperBandPoints values {len(upperBandPoints)}")
-
- # We are done now!
- self.quit()
diff --git a/fincept-qt/scripts/strategies/IndicatorSelectorsWorkWithDifferentOptions.py b/fincept-qt/scripts/strategies/IndicatorSelectorsWorkWithDifferentOptions.py
deleted file mode 100644
index db21a508d..000000000
--- a/fincept-qt/scripts/strategies/IndicatorSelectorsWorkWithDifferentOptions.py
+++ /dev/null
@@ -1,142 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-9EF0798B
-# Category: Options
-# Description: This regression algorithm tests that we can use selectors in the indicators that need quote data
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### This regression algorithm tests that we can use selectors in the indicators
-### that need quote data
-### </summary>
-class IndicatorSelectorWorksWithDifferentOptions(QCAlgorithm):
- def initialize(self):
- self.set_start_date(2013, 6, 7)
- self.set_end_date(2013, 11, 8)
-
- self.equity = self.add_equity("SPY", Resolution.MINUTE).symbol
- self.option = self.add_option("NWSA", Resolution.MINUTE).symbol
- self.aapl = self.add_equity("AAPL", Resolution.DAILY).symbol
- self.aapl_points = []
- self.aapl_last_date = datetime(1,1,1)
- self.eurusd = self.add_forex("EURUSD", Resolution.DAILY).symbol
- self.eurusd_points = []
- self.eurusd_last_date = datetime(1,1,1)
- future = self.add_future("GC", Resolution.DAILY, Market.COMEX)
- self.future = future.symbol
- self.future_contract = None
- self.future_points = []
- future.set_filter(0, 120)
- self.option = Symbol.create_option("NWSA", Market.USA, OptionStyle.AMERICAN, OptionRight.PUT, 33, datetime(2013, 7, 20))
- self.add_option_contract(self.option, Resolution.MINUTE)
-
- self.option_indicator = self.identity(self.option, Resolution.MINUTE, Field.VOLUME, "Volume.")
-
- self.bid_close_indicator = self.identity(self.equity, Resolution.MINUTE, Field.BID_CLOSE, "Bid.Close.")
- self.bid_open_indicator = self.identity(self.equity, Resolution.MINUTE, Field.BID_OPEN, "Bid.Open.")
- self.bid_low_indicator = self.identity(self.equity, Resolution.MINUTE, Field.BID_LOW, "Bid.Low.")
- self.bid_high_indicator = self.identity(self.equity, Resolution.MINUTE, Field.BID_HIGH, "Bid.High.")
-
- self.ask_close_indicator = self.identity(self.equity, Resolution.MINUTE, Field.ASK_CLOSE, "Ask.Close.")
- self.ask_open_indicator = self.identity(self.equity, Resolution.MINUTE, Field.ASK_OPEN, "Ask.Open.")
- self.ask_low_indicator = self.identity(self.equity, Resolution.MINUTE, Field.ASK_LOW, "Ask.Low.")
- self.ask_high_indicator = self.identity(self.equity, Resolution.MINUTE, Field.ASK_HIGH, "Ask.High.")
-
- self.quotebars_found = False
- self.tradebars_found = False
-
- self.tradebar_history_indicator = self.identity(self.aapl, Resolution.DAILY)
- self.quotebar_history_indicator = self.identity(self.eurusd, Resolution.DAILY)
-
- def on_data(self, slice):
- if self.aapl_last_date != self.time.date:
- bars = slice.get(TradeBar)
- if self.aapl in bars.keys():
- datapoint = bars[self.aapl]
- if datapoint and datapoint.volume != 0:
- self.aapl_last_date = self.time.date
- self.aapl_points.append(datapoint.volume)
-
- if self.eurusd_last_date != self.time.date and (self.eurusd in slice.quote_bars.keys()):
- self.eurusd_last_date = self.time.date
- self.eurusd_points.append(slice.quote_bars[self.eurusd].bid.close)
-
- if self.equity in slice.quote_bars.keys():
- self.quotebars_found = True
- if slice.quote_bars["SPY"].bid.close != self.bid_close_indicator.current.value:
- close_value = slice.quote_bars["SPY"].bid.close
- raise Exception(f"{self.bid_close_indicator.__name__} should have been {close_value}, but was {self.bid_close_indicator.current.value}")
-
- if slice.quote_bars["SPY"].bid.open != self.bid_open_indicator.current.value:
- open_value = slice.quote_bars["SPY"].bid.open
- raise Exception(f"{self.bid_open_indicator.__name__} should have been {open_value}, but was {self.bid_open_indicator.current.value}")
-
- if slice.quote_bars["SPY"].bid.low != self.bid_low_indicator.current.value:
- low_value = slice.quote_bars["SPY"].bid.low
- raise Exception(f"{self.bid_low_indicator.__name__} should have been {low_value}, but was {self.bid_low_indicator.current.value}")
-
- if slice.quote_bars["SPY"].bid.high != self.bid_high_indicator.current.value:
- high_value = slice.quote_bars["SPY"].bid.high
- raise Exception(f"{self.bid_high_indicator.__name__} should have been {high_value}, but was {self.bid_high_indicator.current.value}")
-
- if slice.quote_bars["SPY"].ask.close != self.ask_close_indicator.current.value:
- close_value = slice.quote_bars["SPY"].ask.close
- raise Exception(f"{self.ask_close_indicator.__name__} should have been {close_value}, but was {self.ask_close_indicator.current.value}")
-
- if slice.quote_bars["SPY"].ask.open != self.ask_open_indicator.current.value:
- open_value = slice.quote_bars["SPY"].bid.open
- raise Exception(f"{self.ask_open_indicator.__name__} should have been {open_value}, but was {self.ask_open_indicator.current.value}")
-
- if slice.quote_bars["SPY"].ask.low != self.ask_low_indicator.current.value:
- low_value = slice.quote_bars["SPY"].bid.low
- raise Exception(f"{self.ask_low_indicator.__name__} should have been {low_value}, but was {self.ask_low_indicator.current.value}")
-
- if slice.quote_bars["SPY"].ask.high != self.ask_high_indicator.current.value:
- high_value = slice.quote_bars["SPY"].bid.high
- raise Exception(f"{self.ask_high_indicator.__name__} should have been {high_value}, but was {self.ask_high_indicator.current.value}")
-
- if (self.option.canonical in slice.option_chains.keys()) and (self.option in slice.option_chains[self.option.canonical].trade_bars.keys()):
- self.tradebars_found = True
- if self.option_indicator.current.value != slice.option_chains[self.option.canonical].trade_bars[self.option].volume:
- volume = slice.option_chains[self.option.canonical].trade_bars[self.option].volume
- raise Exception(f"{self.option_indicator.__name__} should have been {volume}, but was {self.option_indicator.current.value}")
-
- if (self.future in slice.futures_chains.keys()):
- if self.future_contract == None:
- self.future_contract = slice.future_chains[self.future].trade_bars.values()[0].symbol
- if self.future_contract in slice.future_chains[self.future].trade_bars:
- value = slice.future_chains[self.future].trade_bars[self.future_contract]
- if value.volume != 0:
- self.future_points.append(value.volume)
-
- def on_end_of_algorithm(self):
- if not self.quotebars_found:
- raise Exception("At least one quote bar should have been found, but none was found")
-
- if not self.tradebars_found:
- raise Exception("At least one trade bar should have been found, but none was found")
-
- future_indicator = Identity("")
- backtest_days = (self.end_date - self.start_date).days
- future_volume_history = self.indicator_history(future_indicator, self.future_contract, backtest_days, Resolution.DAILY, Field.VOLUME).current
- future_volume_history_values = list(map(lambda x: x.value, future_volume_history))
- future_volume_history_values = list(filter(lambda x: x != 0, future_volume_history_values))
- if abs(sum(future_volume_history_values)/len(future_volume_history_values) - sum(self.future_points)/len(self.future_points)) > 0.001:
- raise Exception(f"No history indicator future data point was found using Field.Volume selector! {self.future_points}")
-
- volume_history = self.indicator_history(self.tradebar_history_indicator, self.aapl, 109, Resolution.DAILY, Field.VOLUME).current
- volume_history_values = list(map(lambda x: x.value, volume_history))
-
- if abs(sum(volume_history_values)/len(volume_history_values) - sum(self.aapl_points)/len(self.aapl_points)) > 0.001:
- raise Exception("No history indicator data point was found using Field.Volume selector!")
-
- bid_close_history = self.indicator_history(self.quotebar_history_indicator, self.eurusd, 132, Resolution.DAILY, Field.BID_CLOSE).current
- bid_close_history_values = list(map(lambda x: x.value, bid_close_history))
- if abs(sum(bid_close_history_values)/len(bid_close_history_values) - sum(self.eurusd_points)/len(self.eurusd_points)) > 0.001:
- raise Exception("No history indicator data point was found using Field.BidClose selector!")
diff --git a/fincept-qt/scripts/strategies/IndicatorSuiteAlgorithm.py b/fincept-qt/scripts/strategies/IndicatorSuiteAlgorithm.py
deleted file mode 100644
index 8dd0bd2c7..000000000
--- a/fincept-qt/scripts/strategies/IndicatorSuiteAlgorithm.py
+++ /dev/null
@@ -1,180 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-71C08CCA
-# Category: Indicators
-# Description: Basic template algorithm simply initializes the date range and cash. This is a skeleton framework you can use for des...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-from QuantConnect.Algorithm.CSharp import *
-
-### <summary>
-### Basic template algorithm simply initializes the date range and cash. This is a skeleton
-### framework you can use for designing an algorithm.
-### </summary>
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="using quantconnect" />
-### <meta name="tag" content="trading and orders" />
-class IndicatorSuiteAlgorithm(QCAlgorithm):
- '''Demonstration algorithm of popular indicators and plotting them.'''
-
- def initialize(self):
- '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
-
- self._symbol = "SPY"
- self._symbol2 = "GOOG"
- self.custom_symbol = "IBM"
- self.price = None
-
- self.set_start_date(2013, 1, 1) #Set Start Date
- self.set_end_date(2014, 12, 31) #Set End Date
- self.set_cash(25000) #Set Strategy Cash
- # Fincept Terminal Strategy Engine - Symbol Configuration
-
- self.add_equity(self._symbol, Resolution.DAILY)
- self.add_equity(self._symbol2, Resolution.DAILY)
- self.add_data(CustomData, self.custom_symbol, Resolution.DAILY)
-
- # Set up default Indicators, these indicators are defined on the Value property of incoming data (except ATR and AROON which use the full TradeBar object)
- self.indicators = {
- 'BB' : self.bb(self._symbol, 20, 1, MovingAverageType.SIMPLE, Resolution.DAILY),
- 'RSI' : self.rsi(self._symbol, 14, MovingAverageType.SIMPLE, Resolution.DAILY),
- 'EMA' : self.ema(self._symbol, 14, Resolution.DAILY),
- 'SMA' : self.sma(self._symbol, 14, Resolution.DAILY),
- 'MACD' : self.macd(self._symbol, 12, 26, 9, MovingAverageType.SIMPLE, Resolution.DAILY),
- 'MOM' : self.mom(self._symbol, 20, Resolution.DAILY),
- 'MOMP' : self.momp(self._symbol, 20, Resolution.DAILY),
- 'STD' : self.std(self._symbol, 20, Resolution.DAILY),
- # by default if the symbol is a tradebar type then it will be the min of the low property
- 'MIN' : self.min(self._symbol, 14, Resolution.DAILY),
- # by default if the symbol is a tradebar type then it will be the max of the high property
- 'MAX' : self.max(self._symbol, 14, Resolution.DAILY),
- 'ATR' : self.atr(self._symbol, 14, MovingAverageType.SIMPLE, Resolution.DAILY),
- 'AROON' : self.aroon(self._symbol, 20, Resolution.DAILY),
- 'B' : self.b(self._symbol, self._symbol2, 14)
- }
-
- # Here we're going to define indicators using 'selector' functions. These 'selector' functions will define what data gets sent into the indicator
- # These functions have a signature like the following: decimal Selector(BaseData base_data), and can be defined like: base_data => base_data.value
- # We'll define these 'selector' functions to select the Low value
- #
- # For more information on 'anonymous functions' see: http:#en.wikipedia.org/wiki/Anonymous_function
- # https:#msdn.microsoft.com/en-us/library/bb397687.aspx
- #
- self.selector_indicators = {
- 'BB' : self.bb(self._symbol, 20, 1, MovingAverageType.SIMPLE, Resolution.DAILY, Field.low),
- 'RSI' :self.rsi(self._symbol, 14, MovingAverageType.SIMPLE, Resolution.DAILY, Field.low),
- 'EMA' :self.ema(self._symbol, 14, Resolution.DAILY, Field.low),
- 'SMA' :self.sma(self._symbol, 14, Resolution.DAILY, Field.low),
- 'MACD' : self.macd(self._symbol, 12, 26, 9, MovingAverageType.SIMPLE, Resolution.DAILY, Field.low),
- 'MOM' : self.mom(self._symbol, 20, Resolution.DAILY, Field.low),
- 'MOMP' : self.momp(self._symbol, 20, Resolution.DAILY, Field.low),
- 'STD' : self.std(self._symbol, 20, Resolution.DAILY, Field.low),
- 'MIN' : self.min(self._symbol, 14, Resolution.DAILY, Field.high),
- 'MAX' : self.max(self._symbol, 14, Resolution.DAILY, Field.low),
- # ATR and AROON are special in that they accept a TradeBar instance instead of a decimal, we could easily project and/or transform the input TradeBar
- # before it gets sent to the ATR/AROON indicator, here we use a function that will multiply the input trade bar by a factor of two
- 'ATR' : self.atr(self._symbol, 14, MovingAverageType.SIMPLE, Resolution.DAILY, Func[IBaseData, IBaseDataBar](self.selector_double__trade_bar)),
- 'AROON' : self.aroon(self._symbol, 20, Resolution.DAILY, Func[IBaseData, IBaseDataBar](self.selector_double__trade_bar))
- }
-
- # Custom Data Indicator:
- self.rsi_custom = self.rsi(self.custom_symbol, 14, MovingAverageType.SIMPLE, Resolution.DAILY)
- self.min_custom = self.min(self.custom_symbol, 14, Resolution.DAILY)
- self.max_custom = self.max(self.custom_symbol, 14, Resolution.DAILY)
-
- # in addition to defining indicators on a single security, you can all define 'composite' indicators.
- # these are indicators that require multiple inputs. the most common of which is a ratio.
- # suppose we seek the ratio of BTC to SPY, we could write the following:
- spy_close = Identity(self._symbol)
- ibm_close = Identity(self.custom_symbol)
-
- # this will create a new indicator whose value is IBM/SPY
- self.ratio = IndicatorExtensions.over(ibm_close, spy_close)
-
- # we can also easily plot our indicators each time they update using th PlotIndicator function
- self.plot_indicator("Ratio", self.ratio)
-
- # The following methods will add multiple charts to the algorithm output.
- # Those chatrs names will be used later to plot different series in a particular chart.
- # For more information on Lean Charting see: https://www.quantconnect.com/docs#Charting
- Chart('BB')
- Chart('STD')
- Chart('ATR')
- Chart('AROON')
- Chart('MACD')
- Chart('Averages')
- # Here we make use of the Schelude method to update the plots once per day at market close.
- self.schedule.on(self.date_rules.every_day(), self.time_rules.before_market_close(self._symbol), self.update_plots)
-
- def on_data(self, data):
- '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
-
- Arguments:
- data: Slice object keyed by symbol containing the stock data
- '''
-
- if (#not data.bars.contains_key(self._symbol) or
- not self.indicators['BB'].is_ready or
- not self.indicators['RSI'].is_ready):
- return
-
- if not data.bars.contains_key(self._symbol):
- return
-
- self.price = data[self._symbol].close
-
- if not self.portfolio.hold_stock:
- quantity = int(self.portfolio.cash / self.price)
- self.order(self._symbol, quantity)
- self.debug('Purchased SPY on ' + self.time.strftime('%Y-%m-%d'))
-
- def update_plots(self):
- if not self.indicators['BB'].is_ready or not self.indicators['STD'].is_ready:
- return
-
- # Plots can also be created just with this one line command.
- self.plot('RSI', self.indicators['RSI'])
- # Custom data indicator
- self.plot('RSI-FB', self.rsi_custom)
-
- # Here we make use of the chats decalred in the Initialize method, plotting multiple series
- # in each chart.
- self.plot('STD', 'STD', self.indicators['STD'].current.value)
-
- self.plot('BB', 'Price', self.price)
- self.plot('BB', 'BollingerUpperBand', self.indicators['BB'].upper_band.current.value)
- self.plot('BB', 'BollingerMiddleBand', self.indicators['BB'].middle_band.current.value)
- self.plot('BB', 'BollingerLowerBand', self.indicators['BB'].lower_band.current.value)
-
-
- self.plot('AROON', 'Aroon', self.indicators['AROON'].current.value)
- self.plot('AROON', 'AroonUp', self.indicators['AROON'].aroon_up.current.value)
- self.plot('AROON', 'AroonDown', self.indicators['AROON'].aroon_down.current.value)
-
- # The following Plot method calls are commented out because of the 10 series limit for backtests
- #self.plot('ATR', 'ATR', self.indicators['ATR'].current.value)
- #self.plot('ATR', 'ATRDoubleBar', self.selector_indicators['ATR'].current.value)
- #self.plot('Averages', 'SMA', self.indicators['SMA'].current.value)
- #self.plot('Averages', 'EMA', self.indicators['EMA'].current.value)
- #self.plot('MOM', self.indicators['MOM'].current.value)
- #self.plot('MOMP', self.indicators['MOMP'].current.value)
- #self.plot('MACD', 'MACD', self.indicators['MACD'].current.value)
- #self.plot('MACD', 'MACDSignal', self.indicators['MACD'].signal.current.value)
-
- def selector_double__trade_bar(self, bar):
- trade_bar = TradeBar()
- trade_bar.close = 2 * bar.close
- trade_bar.data_type = bar.data_type
- trade_bar.high = 2 * bar.high
- trade_bar.low = 2 * bar.low
- trade_bar.open = 2 * bar.open
- trade_bar.symbol = bar.symbol
- trade_bar.time = bar.time
- trade_bar.value = 2 * bar.value
- trade_bar.period = bar.period
- return trade_bar
diff --git a/fincept-qt/scripts/strategies/IndicatorWarmupAlgorithm.py b/fincept-qt/scripts/strategies/IndicatorWarmupAlgorithm.py
deleted file mode 100644
index fd6b5a714..000000000
--- a/fincept-qt/scripts/strategies/IndicatorWarmupAlgorithm.py
+++ /dev/null
@@ -1,152 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-935D3B5D
-# Category: Indicators
-# Description: Regression test for history and warm up using the data available in open source
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Regression test for history and warm up using the data available in open source.
-### </summary>
-### <meta name="tag" content="history and warm up" />
-### <meta name="tag" content="history" />
-### <meta name="tag" content="regression test" />
-### <meta name="tag" content="warm up" />
-class IndicatorWarmupAlgorithm(QCAlgorithm):
-
- def initialize(self):
- '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
-
- self.set_start_date(2013, 10, 8) #Set Start Date
- self.set_end_date(2013, 10, 11) #Set End Date
- self.set_cash(1000000) #Set Strategy Cash
- # Fincept Terminal Strategy Engine - Symbol Configuration
- self.add_equity("SPY")
- self.add_equity("IBM")
- self.add_equity("BAC")
- self.add_equity("GOOG", Resolution.DAILY)
- self.add_equity("GOOGL", Resolution.DAILY)
-
- self.__sd = { }
- for security in self.securities:
- self.__sd[security.key] = self.SymbolData(security.key, self)
-
- # we want to warm up our algorithm
- self.set_warmup(self.SymbolData.REQUIRED_BARS_WARMUP)
-
- def on_data(self, data):
- '''on_data event is the primary entry point for your algorithm. Each new data point will be pumped in here.
-
- Arguments:
- data: Slice object keyed by symbol containing the stock data
- '''
- # we are only using warmup for indicator spooling, so wait for us to be warm then continue
- if self.is_warming_up: return
-
- for sd in self.__sd.values():
- last_price_time = sd.close.current.time
- if self.round_down(last_price_time, sd.security.subscription_data_config.increment):
- sd.update()
-
- def on_order_event(self, fill):
- sd = self.__sd.get(fill.symbol, None)
- if sd is not None:
- sd.on_order_event(fill)
-
- def round_down(self, time, increment):
- if increment.days != 0:
- return time.hour == 0 and time.minute == 0 and time.second == 0
- else:
- return time.second == 0
-
- class SymbolData:
- REQUIRED_BARS_WARMUP = 40
- PERCENT_TOLERANCE = 0.001
- PERCENT_GLOBAL_STOP_LOSS = 0.01
- LOT_SIZE = 10
-
- def __init__(self, symbol, algorithm):
- self.symbol = symbol
- self.__algorithm = algorithm # if we're receiving daily
-
- self.__current_stop_loss = None
-
- self.security = algorithm.securities[symbol]
- self.close = algorithm.identity(symbol)
- self._adx = algorithm.adx(symbol, 14)
- self._ema = algorithm.ema(symbol, 14)
- self._macd = algorithm.macd(symbol, 12, 26, 9)
-
- self.is_ready = self.close.is_ready and self._adx.is_ready and self._ema.is_ready and self._macd.is_ready
- self.is_uptrend = False
- self.is_downtrend = False
-
- def update(self):
- self.is_ready = self.close.is_ready and self._adx.is_ready and self._ema.is_ready and self._macd.is_ready
-
- tolerance = 1 - self.PERCENT_TOLERANCE
- self.is_uptrend = self._macd.signal.current.value > self._macd.current.value * tolerance and\
- self._ema.current.value > self.close.current.value * tolerance
-
- self.is_downtrend = self._macd.signal.current.value < self._macd.current.value * tolerance and\
- self._ema.current.value < self.close.current.value * tolerance
-
- self.try_enter()
- self.try_exit()
-
- def try_enter(self):
- # can't enter if we're already in
- if self.security.invested: return False
-
- qty = 0
- limit = 0.0
-
- if self.is_uptrend:
- # 100 order lots
- qty = self.LOT_SIZE
- limit = self.security.low
- elif self.is_downtrend:
- qty = -self.LOT_SIZE
- limit = self.security.high
-
- if qty != 0:
- ticket = self.__algorithm.limit_order(self.symbol, qty, limit, "TryEnter at: {0}".format(limit))
-
- def try_exit(self):
- # can't exit if we haven't entered
- if not self.security.invested: return
-
- limit = 0
- qty = self.security.holdings.quantity
- exit_tolerance = 1 + 2 * self.PERCENT_TOLERANCE
- if self.security.holdings.is_long and self.close.current.value * exit_tolerance < self._ema.current.value:
- limit = self.security.high
- elif self.security.holdings.is_short and self.close.current.value > self._ema.current.value * exit_tolerance:
- limit = self.security.low
-
- if limit != 0:
- ticket = self.__algorithm.limit_order(self.symbol, -qty, limit, "TryExit at: {0}".format(limit))
-
- def on_order_event(self, fill):
- if fill.status != OrderStatus.FILLED: return
-
- qty = self.security.holdings.quantity
-
- # if we just finished entering, place a stop loss as well
- if self.security.invested:
- stop = fill.fill_price*(1 - self.PERCENT_GLOBAL_STOP_LOSS) if self.security.holdings.is_long \
- else fill.fill_price*(1 + self.PERCENT_GLOBAL_STOP_LOSS)
-
- self.__current_stop_loss = self.__algorithm.stop_market_order(self.symbol, -qty, stop, "StopLoss at: {0}".format(stop))
-
- # check for an exit, cancel the stop loss
- elif (self.__current_stop_loss is not None and self.__current_stop_loss.status is not OrderStatus.FILLED):
- # cancel our current stop loss
- self.__current_stop_loss.cancel("Exited position")
- self.__current_stop_loss = None
diff --git a/fincept-qt/scripts/strategies/IndicatorWithRenkoBarsRegressionAlgorithm.py b/fincept-qt/scripts/strategies/IndicatorWithRenkoBarsRegressionAlgorithm.py
deleted file mode 100644
index 49dc7de44..000000000
--- a/fincept-qt/scripts/strategies/IndicatorWithRenkoBarsRegressionAlgorithm.py
+++ /dev/null
@@ -1,59 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-B8EB6886
-# Category: Indicators
-# Description: Regrssion algorithm to assert we can update indicators that inherit from IndicatorBase<TradeBar> with RenkoBar's
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Regrssion algorithm to assert we can update indicators that inherit from IndicatorBase<TradeBar> with RenkoBar's
-### </summary>
-### <meta name="tag" content="renko" />
-### <meta name="tag" content="indicators" />
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="consolidating data" />
-class IndicatorWithRenkoBarsRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2013, 10, 7)
- self.set_end_date(2013, 10, 9)
-
- self.add_equity("SPY")
- self.add_equity("AIG")
-
- spy_renko_consolidator = RenkoConsolidator(0.1)
- spy_renko_consolidator.data_consolidated += self.on_s_p_y_data_consolidated
-
- aig_renko_consolidator = RenkoConsolidator(0.05)
- aig_renko_consolidator.data_consolidated += self.on_a_i_g_data_consolidated
-
- self.subscription_manager.add_consolidator("SPY", spy_renko_consolidator)
- self.subscription_manager.add_consolidator("AIG", aig_renko_consolidator)
-
- self._mi = MassIndex("MassIndex", 9, 25)
- self._wasi = WilderAccumulativeSwingIndex("WilderAccumulativeSwingIndex", 8)
- self._wsi = WilderSwingIndex("WilderSwingIndex", 8)
- self._b = Beta("Beta", 3, "AIG", "SPY")
- self._indicators = [self._mi, self._wasi, self._wsi, self._b]
-
- def on_s_p_y_data_consolidated(self, sender, renko_bar):
- self._mi.update(renko_bar)
- self._wasi.update(renko_bar)
- self._wsi.update(renko_bar)
- self._b.update(renko_bar)
-
- def on_a_i_g_data_consolidated(self, sender, renko_bar):
- self._b.update(renko_bar)
-
- def on_end_of_algorithm(self):
- for indicator in self._indicators:
- if not indicator.is_ready:
- raise Exception(f"{indicator.name} indicator should be ready")
- elif indicator.current.value == 0:
- raise Exception(f"The current value of the {indicator.name} indicator should be different than zero")
diff --git a/fincept-qt/scripts/strategies/IndustryStandardSecurityIdentifiersRegressionAlgorithm.py b/fincept-qt/scripts/strategies/IndustryStandardSecurityIdentifiersRegressionAlgorithm.py
deleted file mode 100644
index 05b4905e5..000000000
--- a/fincept-qt/scripts/strategies/IndustryStandardSecurityIdentifiersRegressionAlgorithm.py
+++ /dev/null
@@ -1,57 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-77C48AE3
-# Category: Regression Test
-# Description: Algorithm illustrating how to get a security's industry-standard identifier from its `Symbol`
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Algorithm illustrating how to get a security's industry-standard identifier from its `Symbol`
-### </summary>
-class IndustryStandardSecurityIdentifiersRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2014, 6, 5)
- self.set_end_date(2014, 6, 5)
-
- equity = self.add_equity("AAPL").symbol
-
- cusip = equity.cusip
- composite_figi = equity.composite_figi
- sedol = equity.sedol
- isin = equity.isin
- cik = equity.cik
-
- self.check_symbol_representation(cusip, "CUSIP")
- self.check_symbol_representation(composite_figi, "Composite FIGI")
- self.check_symbol_representation(sedol, "SEDOL")
- self.check_symbol_representation(isin, "ISIN")
- self.check_symbol_representation(f"{cik}", "CIK")
-
- # Check Symbol API vs QCAlgorithm API
- self.check_ap_is_symbol_representations(cusip, self.cusip(equity), "CUSIP")
- self.check_ap_is_symbol_representations(composite_figi, self.composite_figi(equity), "Composite FIGI")
- self.check_ap_is_symbol_representations(sedol, self.sedol(equity), "SEDOL")
- self.check_ap_is_symbol_representations(isin, self.isin(equity), "ISIN")
- self.check_ap_is_symbol_representations(f"{cik}", f"{self.cik(equity)}", "CIK")
-
- self.log(f"\n_aapl CUSIP: {cusip}"
- f"\n_aapl Composite FIGI: {composite_figi}"
- f"\n_aapl SEDOL: {sedol}"
- f"\n_aapl ISIN: {isin}"
- f"\n_aapl CIK: {cik}")
-
- def check_symbol_representation(self, symbol: str, standard: str) -> None:
- if not symbol:
- raise Exception(f"{standard} symbol representation is null or empty")
-
- def check_ap_is_symbol_representations(self, symbol_api_symbol: str, algorithm_api_symbol: str, standard: str) -> None:
- if symbol_api_symbol != algorithm_api_symbol:
- raise Exception(f"Symbol API {standard} symbol representation ({symbol_api_symbol}) does not match "
- f"QCAlgorithm API {standard} symbol representation ({algorithm_api_symbol})")
diff --git a/fincept-qt/scripts/strategies/InsightScoringRegressionAlgorithm.py b/fincept-qt/scripts/strategies/InsightScoringRegressionAlgorithm.py
deleted file mode 100644
index 39173d111..000000000
--- a/fincept-qt/scripts/strategies/InsightScoringRegressionAlgorithm.py
+++ /dev/null
@@ -1,76 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-E8E10658
-# Category: Regression Test
-# Description: Regression algorithm showing how to define a custom insight scoring function and using the insight manager
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Regression algorithm showing how to define a custom insight scoring function and using the insight manager
-### </summary>
-class InsightScoringRegressionAlgorithm(QCAlgorithm):
- '''Regression algorithm showing how to define a custom insight evaluator'''
-
- def initialize(self):
- ''' Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
- self.set_start_date(2013,10,7)
- self.set_end_date(2013,10,11)
-
- symbols = [ Symbol.create("SPY", SecurityType.EQUITY, Market.USA) ]
-
- self.set_universe_selection(ManualUniverseSelectionModel(symbols))
- self.set_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(minutes = 20), 0.025, None))
- self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel(Resolution.DAILY))
- self.set_execution(ImmediateExecutionModel())
- self.set_risk_management(MaximumDrawdownPercentPerSecurity(0.01))
-
- # we specify a custom insight evaluator
- self.insights.set_insight_score_function(CustomInsightScoreFunction(self.securities))
-
- def on_end_of_algorithm(self):
- all_insights = self.insights.get_insights(lambda insight: True)
-
- if len(all_insights) != 100 or len(self.insights.get_insights()) != 100:
- raise ValueError(f'Unexpected insight count found {all_insights.count}')
-
- if sum(1 for insight in all_insights if insight.score.magnitude == 0 or insight.score.direction == 0) < 5:
- raise ValueError(f'Insights not scored!')
-
- if sum(1 for insight in all_insights if insight.score.is_final_score) < 99:
- raise ValueError(f'Insights not finalized!')
-
-class CustomInsightScoreFunction():
-
- def __init__(self, securities):
- self._securities = securities
- self._open_insights = {}
-
- def score(self, insight_manager, utc_time):
- open_insights = insight_manager.get_active_insights(utc_time)
-
- for insight in open_insights:
- self._open_insights[insight.id] = insight
-
- to_remove = []
- for open_insight in self._open_insights.values():
- security = self._securities[open_insight.symbol]
- open_insight.reference_value_final = security.price
-
- score = open_insight.reference_value_final - open_insight.reference_value
- open_insight.score.set_score(InsightScoreType.DIRECTION, score, utc_time)
- open_insight.score.set_score(InsightScoreType.MAGNITUDE, score * 2, utc_time)
- open_insight.estimated_value = score * 100
-
- if open_insight.is_expired(utc_time):
- open_insight.score.finalize(utc_time)
- to_remove.append(open_insight)
-
- # clean up
- for insight_to_remove in to_remove:
- self._open_insights.pop(insight_to_remove.id)
diff --git a/fincept-qt/scripts/strategies/InsightTagAlphaRegressionAlgorithm.py b/fincept-qt/scripts/strategies/InsightTagAlphaRegressionAlgorithm.py
deleted file mode 100644
index c731c51be..000000000
--- a/fincept-qt/scripts/strategies/InsightTagAlphaRegressionAlgorithm.py
+++ /dev/null
@@ -1,46 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-15D6B08D
-# Category: Alpha Model
-# Description: Multi-signal alpha strategy combining RSI and EMA crossover.
-# Generates buy signal when RSI < 40 AND fast EMA > slow EMA. Sells when
-# RSI > 70 OR fast EMA crosses below slow EMA.
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-class InsightTagAlphaRegressionAlgorithm(QCAlgorithm):
- """Combined RSI + EMA crossover alpha strategy."""
-
- def initialize(self):
- self.set_start_date(2023, 1, 1)
- self.set_end_date(2024, 1, 1)
- self.set_cash(100000)
-
- self.symbol = "SPY"
- self.add_equity(self.symbol, Resolution.DAILY)
-
- self._rsi = self.rsi(self.symbol, 14, Resolution.DAILY)
- self._fast_ema = self.ema(self.symbol, 10, Resolution.DAILY)
- self._slow_ema = self.ema(self.symbol, 30, Resolution.DAILY)
-
- def on_data(self, data):
- if not self._rsi.is_ready or not self._slow_ema.is_ready:
- return
- if self.symbol not in data:
- return
-
- rsi_val = self._rsi.current.value
- fast = self._fast_ema.current.value
- slow = self._slow_ema.current.value
-
- if not self.portfolio.invested:
- if rsi_val < 40 and fast > slow:
- self.set_holdings(self.symbol, 1)
- else:
- if rsi_val > 70 or fast < slow:
- self.liquidate()
diff --git a/fincept-qt/scripts/strategies/InsightWeightingFrameworkAlgorithm.py b/fincept-qt/scripts/strategies/InsightWeightingFrameworkAlgorithm.py
deleted file mode 100644
index 997d13dd6..000000000
--- a/fincept-qt/scripts/strategies/InsightWeightingFrameworkAlgorithm.py
+++ /dev/null
@@ -1,51 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-955EB562
-# Category: General Strategy
-# Description: Test algorithm using 'InsightWeightingPortfolioConstructionModel' and 'ConstantAlphaModel' generating a constant 'Ins...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-from Selection.ManualUniverseSelectionModel import ManualUniverseSelectionModel
-from Alphas.ConstantAlphaModel import ConstantAlphaModel
-from Portfolio.InsightWeightingPortfolioConstructionModel import InsightWeightingPortfolioConstructionModel
-from Execution.ImmediateExecutionModel import ImmediateExecutionModel
-
-### <summary>
-### Test algorithm using 'InsightWeightingPortfolioConstructionModel' and 'ConstantAlphaModel'
-### generating a constant 'Insight' with a 0.25 weight
-### </summary>
-class InsightWeightingFrameworkAlgorithm(QCAlgorithm):
-
- def initialize(self):
- ''' Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
-
- # Set requested data resolution
- self.universe_settings.resolution = Resolution.MINUTE
-
- # Order margin value has to have a minimum of 0.5% of Portfolio value, allows filtering out small trades and reduce fees.
- # Commented so regression algorithm is more sensitive
- #self.settings.minimum_order_margin_portfolio_percentage = 0.005
-
- self.set_start_date(2013,10,7) #Set Start Date
- self.set_end_date(2013,10,11) #Set End Date
- self.set_cash(100000) #Set Strategy Cash
-
- symbols = [ Symbol.create("SPY", SecurityType.EQUITY, Market.USA) ]
-
- # set algorithm framework models
- self.set_universe_selection(ManualUniverseSelectionModel(symbols))
- self.set_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(minutes = 20), 0.025, None, 0.25))
- self.set_portfolio_construction(InsightWeightingPortfolioConstructionModel())
- self.set_execution(ImmediateExecutionModel())
-
- def on_end_of_algorithm(self):
- # holdings value should be 0.25 - to avoid price fluctuation issue we compare with 0.28 and 0.23
- if (self.portfolio.total_holdings_value > self.portfolio.total_portfolio_value * 0.28
- or self.portfolio.total_holdings_value < self.portfolio.total_portfolio_value * 0.23):
- raise ValueError("Unexpected Total Holdings Value: " + str(self.portfolio.total_holdings_value))
diff --git a/fincept-qt/scripts/strategies/IronCondorStrategyAlgorithm.py b/fincept-qt/scripts/strategies/IronCondorStrategyAlgorithm.py
deleted file mode 100644
index 92d35bf85..000000000
--- a/fincept-qt/scripts/strategies/IronCondorStrategyAlgorithm.py
+++ /dev/null
@@ -1,83 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-FD19D095
-# Category: General Strategy
-# Description: This algorithm demonstrate how to use OptionStrategies helper class to batch send orders for common strategies. In th...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-import itertools
-
-from OptionStrategyFactoryMethodsBaseAlgorithm import *
-
-### <summary>
-### This algorithm demonstrate how to use OptionStrategies helper class to batch send orders for common strategies.
-### In this case, the algorithm tests the Iron Condor strategy.
-### </summary>
-class IronCondorStrategyAlgorithm(OptionStrategyFactoryMethodsBaseAlgorithm):
-
- def expected_orders_count(self) -> int:
- return 8
-
- def trade_strategy(self, chain: OptionChain, option_symbol: Symbol):
- for expiry, group in itertools.groupby(chain, lambda x: x.expiry):
- contracts = sorted(group, key=lambda x: x.strike)
- if len(contracts) < 4:continue
-
- put_contracts = [x for x in contracts if x.right == OptionRight.PUT]
- if len(put_contracts) < 2: continue
- long_put_strike = put_contracts[0].strike
- short_put_strike = put_contracts[1].strike
-
- call_contracts = [x for x in contracts if x.right == OptionRight.CALL and x.strike > short_put_strike]
- if len(call_contracts) < 2: continue
- short_call_strike = call_contracts[0].strike
- long_call_strike = call_contracts[1].strike
-
- self._iron_condor = OptionStrategies.iron_condor(option_symbol, long_put_strike, short_put_strike, short_call_strike, long_call_strike, expiry)
- self.buy(self._iron_condor, 2)
- return
-
- def assert_strategy_position_group(self, position_group: IPositionGroup, option_symbol: Symbol):
- positions = list(position_group.positions)
- if len(positions) != 4:
- raise Exception(f"Expected position group to have 4 positions. Actual: {len(positions)}")
-
- ordered_strikes = sorted((leg.strike for leg in self._iron_condor.option_legs))
-
- long_put_strike = ordered_strikes[0]
- long_put_position = next((x for x in position_group.positions
- if x.symbol.id.option_right == OptionRight.PUT and x.symbol.id.strike_price == long_put_strike),
- None)
- if long_put_position is None or long_put_position.quantity != 2:
- raise Exception(f"Expected long put position quantity to be 2. Actual: {long_put_position.quantity}")
-
- short_put_strike = ordered_strikes[1]
- short_put_position = next((x for x in position_group.positions
- if x.symbol.id.option_right == OptionRight.PUT and x.symbol.id.strike_price == short_put_strike),
- None)
- if short_put_position is None or short_put_position.quantity != -2:
- raise Exception(f"Expected short put position quantity to be -2. Actual: {short_put_position.quantity}")
-
- short_call_strike = ordered_strikes[2]
- short_call_position = next((x for x in position_group.positions
- if x.symbol.id.option_right == OptionRight.CALL and x.symbol.id.strike_price == short_call_strike),
- None)
- if short_call_position is None or short_call_position.quantity != -2:
- raise Exception(f"Expected short call position quantity to be -2. Actual: {short_call_position.quantity}")
-
- long_call_strike = ordered_strikes[3]
- long_call_position = next((x for x in position_group.positions
- if x.symbol.id.option_right == OptionRight.CALL and x.symbol.id.strike_price == long_call_strike),
- None)
- if long_call_position is None or long_call_position.quantity != 2:
- raise Exception(f"Expected long call position quantity to be 2. Actual: {long_call_position.quantity}")
-
- def liquidate_strategy(self):
- # We should be able to close the position by selling the strategy
- self.sell(self._iron_condor, 2)
diff --git a/fincept-qt/scripts/strategies/KerasNeuralNetworkAlgorithm.py b/fincept-qt/scripts/strategies/KerasNeuralNetworkAlgorithm.py
deleted file mode 100644
index 77492960d..000000000
--- a/fincept-qt/scripts/strategies/KerasNeuralNetworkAlgorithm.py
+++ /dev/null
@@ -1,127 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-8863BE2D
-# Category: Machine Learning
-# Description: Save the data and the mode using the ObjectStore
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-from keras.models import *
-from tensorflow import keras
-from keras.layers import Dense, Activation
-from keras.optimizers import SGD
-
-class KerasNeuralNetworkAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2019, 1, 1) # Set Start Date
- self.set_end_date(2020, 4, 1) # Set End Date
- self.set_cash(100000) # Set Strategy Cash
-
- self.model_by_symbol = {}
-
- for ticker in ["SPY", "QQQ", "TLT"]:
- symbol = self.add_equity(ticker).symbol
-
- # Read the model saved in the ObjectStore
- for kvp in self.object_store:
- key = f'{symbol}_model'
- if not key == kvp.key or kvp.value is None:
- continue
- file_path = self.object_store.get_file_path(kvp.key)
- self.model_by_symbol[symbol] = keras.models.load_model(file_path)
- self.debug(f'Model for {symbol} sucessfully retrieved. File {file_path}. Size {kvp.value.length}. Weights {self.model_by_symbol[symbol].get_weights()}')
-
- # Look-back period for training set
- self.lookback = 30
-
- # Train Neural Network every monday
- self.train(
- self.date_rules.every(DayOfWeek.MONDAY),
- self.time_rules.after_market_open("SPY"),
- self.neural_network_training)
-
- # Place trades on Monday, 30 minutes after the market is open
- self.schedule.on(
- self.date_rules.every_day("SPY"),
- self.time_rules.after_market_open("SPY", 30),
- self.trade)
-
-
- def on_end_of_algorithm(self):
- ''' Save the data and the mode using the ObjectStore '''
- for symbol, model in self.model_by_symbol.items():
- key = f'{symbol}_model'
- file = self.object_store.get_file_path(key)
- model.save(file)
- self.object_store.save(key)
- self.debug(f'Model for {symbol} sucessfully saved in the ObjectStore')
-
-
- def neural_network_training(self):
- '''Train the Neural Network and save the model in the ObjectStore'''
- symbols = self.securities.keys()
-
- # Daily historical data is used to train the machine learning model
- history = self.history(symbols, self.lookback + 1, Resolution.DAILY)
- history = history.open.unstack(0)
-
- for symbol in symbols:
- if symbol not in history:
- continue
-
- predictor = history[symbol][:-1]
- predictand = history[symbol][1:]
-
- # build a neural network from the 1st layer to the last layer
- model = Sequential()
-
- model.add(Dense(10, input_dim = 1))
- model.add(Activation('relu'))
- model.add(Dense(1))
-
- sgd = SGD(learning_rate = 0.01) # learning rate = 0.01
-
- # choose loss function and optimizing method
- model.compile(loss='mse', optimizer=sgd)
-
- # pick an iteration number large enough for convergence
- for step in range(200):
- # training the model
- cost = model.train_on_batch(predictor, predictand)
-
- self.model_by_symbol[symbol] = model
-
- def trade(self):
- '''
- Predict the price using the trained model and out-of-sample data
- Enter or exit positions based on relationship of the open price of the current bar and the prices defined by the machine learning model.
- Liquidate if the open price is below the sell price and buy if the open price is above the buy price
- '''
- target = 1 / len(self.securities)
-
- for symbol, model in self.model_by_symbol.items():
-
- # Get the out-of-sample history
- history = self.history(symbol, self.lookback, Resolution.DAILY)
- history = history.open.unstack(0)[symbol]
-
- # Get the final predicted price
- prediction = model.predict(history)[0][-1]
- history_std = np.std(history)
-
- holding = self.portfolio[symbol]
- open_price = self.current_slice[symbol].open
-
- # Follow the trend
- if holding.invested:
- if open_price < prediction - history_std:
- self.liquidate(symbol)
- else:
- if open_price > prediction + history_std:
- self.set_holdings(symbol, target)
diff --git a/fincept-qt/scripts/strategies/LimitFillRegressionAlgorithm.py b/fincept-qt/scripts/strategies/LimitFillRegressionAlgorithm.py
deleted file mode 100644
index 211314820..000000000
--- a/fincept-qt/scripts/strategies/LimitFillRegressionAlgorithm.py
+++ /dev/null
@@ -1,45 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-C37858CB
-# Category: Regression Test
-# Description: Basic template algorithm simply initializes the date range and cash
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Basic template algorithm simply initializes the date range and cash
-### </summary>
-### <meta name="tag" content="trading and orders" />
-### <meta name="tag" content="limit orders" />
-### <meta name="tag" content="placing orders" />
-### <meta name="tag" content="updating orders" />
-### <meta name="tag" content="regression test" />
-class LimitFillRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self):
- '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
-
- self.set_start_date(2013,10,7) #Set Start Date
- self.set_end_date(2013,10,11) #Set End Date
- self.set_cash(100000) #Set Strategy Cash
- # Fincept Terminal Strategy Engine - Symbol Configuration
- self.add_equity("SPY", Resolution.SECOND)
-
- def on_data(self, data):
- '''on_data event is the primary entry point for your algorithm. Each new data point will be pumped in here.'''
- if data.contains_key("SPY"):
- if self.is_round_hour(self.time):
- negative = 1 if self.time < (self.start_date + timedelta(days=2)) else -1
- self.limit_order("SPY", negative*10, data["SPY"].price)
-
- def is_round_hour(self, date_time):
- '''Verify whether datetime is round hour'''
- return date_time.minute == 0 and date_time.second == 0
-
- def on_order_event(self, order_event):
- self.debug(str(order_event))
diff --git a/fincept-qt/scripts/strategies/LimitIfTouchedRegressionAlgorithm.py b/fincept-qt/scripts/strategies/LimitIfTouchedRegressionAlgorithm.py
deleted file mode 100644
index 65df65244..000000000
--- a/fincept-qt/scripts/strategies/LimitIfTouchedRegressionAlgorithm.py
+++ /dev/null
@@ -1,59 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-78D0ECA0
-# Category: Regression Test
-# Description: Basic algorithm demonstrating how to place LimitIfTouched orders
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-from collections import deque
-
-### <summary>
-### Basic algorithm demonstrating how to place LimitIfTouched orders.
-### </summary>
-### <meta name="tag" content="trading and orders" />
-### <meta name="tag" content="placing orders" />`
-### <meta name="tag" content="limit if touched order"/>
-class LimitIfTouchedRegressionAlgorithm(QCAlgorithm):
- _expected_events = deque([
- "Time: 10/10/2013 13:31:00 OrderID: 72 EventID: 399 Symbol: SPY Status: Filled Quantity: -1 FillQuantity: -1 FillPrice: $144.6434 LimitPrice: $144.3551 TriggerPrice: $143.61 OrderFee: 1 USD",
- "Time: 10/10/2013 15:57:00 OrderID: 73 EventID: 156 Symbol: SPY Status: Filled Quantity: -1 FillQuantity: -1 FillPrice: $145.6636 LimitPrice: $145.6434 TriggerPrice: $144.89 OrderFee: 1 USD",
- "Time: 10/11/2013 15:37:00 OrderID: 74 EventID: 380 Symbol: SPY Status: Filled Quantity: -1 FillQuantity: -1 FillPrice: $146.7185 LimitPrice: $146.6723 TriggerPrice: $145.92 OrderFee: 1 USD" ])
-
- def initialize(self):
- self.set_start_date(2013, 10, 7)
- self.set_end_date(2013, 10, 11)
- self.set_cash(100000)
- self.add_equity("SPY")
-
- def on_data(self, data):
- if data.contains_key("SPY"):
- if len(self.transactions.get_open_orders()) == 0:
- self._negative = 1 if self.time.day < 9 else -1
- order_request = SubmitOrderRequest(OrderType.LIMIT_IF_TOUCHED, SecurityType.EQUITY, "SPY",
- self._negative * 10, 0,
- data["SPY"].price - self._negative,
- data["SPY"].price - 0.25 * self._negative, self.utc_time,
- f"LIT - Quantity: {self._negative * 10}")
- self._request = self.transactions.add_order(order_request)
- return
-
- if self._request is not None:
- if self._request.quantity == 1:
- self.transactions.cancel_open_orders()
- self._request = None
- return
-
- new_quantity = int(self._request.quantity - self._negative)
- self._request.update_quantity(new_quantity, f"LIT - Quantity: {new_quantity}")
- self._request.update_trigger_price(Extensions.round_to_significant_digits(self._request.get(OrderField.TRIGGER_PRICE), 5))
-
- def on_order_event(self, order_event):
- if order_event.status == OrderStatus.FILLED:
- expected = self._expected_events.popleft()
- if str(order_event) != expected:
- raise Exception(f"order_event {order_event.id} differed from {expected}. Actual {order_event}")
diff --git a/fincept-qt/scripts/strategies/LiquidETFUniverseFrameworkAlgorithm.py b/fincept-qt/scripts/strategies/LiquidETFUniverseFrameworkAlgorithm.py
deleted file mode 100644
index c2558dd16..000000000
--- a/fincept-qt/scripts/strategies/LiquidETFUniverseFrameworkAlgorithm.py
+++ /dev/null
@@ -1,80 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-1E792B32
-# Category: ETF
-# Description: Basic template framework algorithm uses framework components to define the algorithm. Liquid ETF Competition template
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-from Portfolio.EqualWeightingPortfolioConstructionModel import EqualWeightingPortfolioConstructionModel
-from Execution.ImmediateExecutionModel import ImmediateExecutionModel
-
-### <summary>
-### Basic template framework algorithm uses framework components to define the algorithm.
-### Liquid ETF Competition template
-### </summary>
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="using quantconnect" />
-### <meta name="tag" content="trading and orders" />
-class LiquidETFUniverseFrameworkAlgorithm(QCAlgorithm):
- '''Basic template framework algorithm uses framework components to define the algorithm.'''
-
- def initialize(self):
- # Set Start Date so that backtest has 5+ years of data
- self.set_start_date(2014, 11, 1)
- # No need to set End Date as the final submission will be tested
- # up until the review date
-
- # Set $1m Strategy Cash to trade significant AUM
- self.set_cash(1000000)
-
- # Add a relevant benchmark, with the default being SPY
- self.set_benchmark('SPY')
-
- # Use the Alpha Streams Brokerage Model, developed in conjunction with
- # funds to model their actual fees, costs, etc.
- # Please do not add any additional reality modelling, such as Slippage, Fees, Buying Power, etc.
- self.set_brokerage_model(AlphaStreamsBrokerageModel())
-
- # Use the LiquidETFUniverse with minute-resolution data
- self.universe_settings.resolution = Resolution.MINUTE
- self.set_universe_selection(LiquidETFUniverse())
-
- # Optional
- self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())
- self.set_execution(ImmediateExecutionModel())
-
- # List of symbols we want to trade. Set it in OnSecuritiesChanged
- self._symbols = []
-
- def on_data(self, slice):
-
- if all([self.portfolio[x].invested for x in self._symbols]):
- return
-
- # Emit insights
- insights = [Insight.price(x, timedelta(1), InsightDirection.UP)
- for x in self._symbols if self.securities[x].price > 0]
-
- if len(insights) > 0:
- self.emit_insights(insights)
-
- def on_securities_changed(self, changes):
-
- # Set symbols as the Inverse Energy ETFs
- for security in changes.added_securities:
- if security.symbol in LiquidETFUniverse.ENERGY.inverse:
- self._symbols.append(security.symbol)
-
- # Print out the information about the groups
- self.log(f'Energy: {LiquidETFUniverse.ENERGY}')
- self.log(f'Metals: {LiquidETFUniverse.METALS}')
- self.log(f'Technology: {LiquidETFUniverse.TECHNOLOGY}')
- self.log(f'Treasuries: {LiquidETFUniverse.TREASURIES}')
- self.log(f'Volatility: {LiquidETFUniverse.VOLATILITY}')
- self.log(f'SP500Sectors: {LiquidETFUniverse.SP_500_SECTORS}')
diff --git a/fincept-qt/scripts/strategies/LiveFeaturesAlgorithm.py b/fincept-qt/scripts/strategies/LiveFeaturesAlgorithm.py
deleted file mode 100644
index 53f5d2d5f..000000000
--- a/fincept-qt/scripts/strategies/LiveFeaturesAlgorithm.py
+++ /dev/null
@@ -1,147 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-C5F5B3E0
-# Category: General Strategy
-# Description: Live Trading Functionality Demonstration algorithm including SMS, Email and Web hook notifications
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-from System.Globalization import *
-
-### <summary>
-### Live Trading Functionality Demonstration algorithm including SMS, Email and Web hook notifications.
-### </summary>
-### <meta name="tag" content="live trading" />
-### <meta name="tag" content="alerts" />
-### <meta name="tag" content="sms alerts" />
-### <meta name="tag" content="web hooks" />
-### <meta name="tag" content="email alerts" />
-### <meta name="tag" content="runtime statistics" />
-
-class LiveTradingFeaturesAlgorithm(QCAlgorithm):
-
- ### Initialize the Algorithm and Prepare Required Data
- def initialize(self):
-
- self.set_start_date(2013, 10, 7)
- self.set_end_date(2013, 10, 11)
- self.set_cash(25000)
-
- ##Equity Data for US Markets
- self.add_security(SecurityType.EQUITY, 'IBM', Resolution.SECOND)
-
- ##FOREX Data for Weekends: 24/6
- self.add_security(SecurityType.FOREX, 'EURUSD', Resolution.MINUTE)
-
- ##Custom/Bitcoin Live Data: 24/7
- self.add_data(Bitcoin, 'BTC', Resolution.SECOND, TimeZones.UTC)
-
- ##if the algorithm is connected to the brokerage
- self.is_connected = True
-
-
- ### New Bitcoin Data Event
- def on_data(Bitcoin, data):
- if self.live_mode:
- self.set_runtime_statistic('BTC', str(data.close))
-
- if not self.portfolio.hold_stock:
- self.market_order('BTC', 100)
-
- ##Send a notification email/SMS/web request on events:
- self.notify.email("[email protected]", "Test", "Test Body", "test attachment")
- self.notify.sms("+11233456789", str(data.time) + ">> Test message from live BTC server.")
- self.notify.web("http://api.quantconnect.com", str(data.time) + ">> Test data packet posted from live BTC server.")
- self.notify.ftp("ftp.quantconnect.com", "username", "password", "path/to/file.txt",
- str(data.time) + ">> Test file from live BTC server.")
- self.notify.sftp("ftp.quantconnect.com", "username", "password", "path/to/file.txt",
- str(data.time) + ">> Test file from live BTC server.")
- self.notify.sftp("ftp.quantconnect.com", "username", "privatekey", "optionalprivatekeypassphrase", "path/to/file.txt",
- str(data.time) + ">> Test file from live BTC server.")
-
- ### Raises the data event
- def on_data(self, data):
- if (not self.portfolio['IBM'].hold_stock) and data.contains_key('IBM'):
- quantity = int(np.floor(self.portfolio.margin_remaining / data['IBM'].close))
- self.market_order('IBM',quantity)
- self.debug('Purchased IBM on ' + str(self.time.strftime("%m/%d/%Y")))
- self.notify.email("[email protected]", "Test", "Test Body", "test attachment")
-
- # Brokerage message event handler. This method is called for all types of brokerage messages.
- def on_brokerage_message(self, message_event):
- self.debug(f"Brokerage meesage received - {message_event.to_string()}")
-
- # Brokerage disconnected event handler. This method is called when the brokerage connection is lost.
- def on_brokerage_disconnect(self):
- self.is_connected = False
- self.debug(f"Brokerage disconnected!")
-
- # Brokerage reconnected event handler. This method is called when the brokerage connection is restored after a disconnection.
- def on_brokerage_reconnect(self):
- self.is_connected = True
- self.debug(f"Brokerage reconnected!")
-
-###Custom Data Type: Bitcoin data from Quandl - http://www.quandl.com/help/api-for-bitcoin-data
-class Bitcoin(PythonData):
-
- def get_source(self, config, date, is_live_mode):
- if is_live_mode:
- return SubscriptionDataSource("https://www.bitstamp.net/api/ticker/", SubscriptionTransportMedium.REST)
-
- return SubscriptionDataSource("https://www.quandl.com/api/v3/datasets/BCHARTS/BITSTAMPUSD.csv?order=asc", SubscriptionTransportMedium.REMOTE_FILE)
-
-
- def reader(self, config, line, date, is_live_mode):
- coin = Bitcoin()
- coin.symbol = config.symbol
-
- if is_live_mode:
- # Example Line Format:
- # {"high": "441.00", "last": "421.86", "timestamp": "1411606877", "bid": "421.96", "vwap": "428.58", "volume": "14120.40683975", "low": "418.83", "ask": "421.99"}
- try:
- live_btc = json.loads(line)
-
- # If value is zero, return None
- value = live_btc["last"]
- if value == 0: return None
-
- coin.time = datetime.now()
- coin.value = value
- coin["Open"] = float(live_btc["open"])
- coin["High"] = float(live_btc["high"])
- coin["Low"] = float(live_btc["low"])
- coin["Close"] = float(live_btc["last"])
- coin["Ask"] = float(live_btc["ask"])
- coin["Bid"] = float(live_btc["bid"])
- coin["VolumeBTC"] = float(live_btc["volume"])
- coin["WeightedPrice"] = float(live_btc["vwap"])
- return coin
- except ValueError:
- # Do nothing, possible error in json decoding
- return None
-
- # Example Line Format:
- # Date Open High Low Close Volume (BTC) Volume (Currency) Weighted Price
- # 2011-09-13 5.8 6.0 5.65 5.97 58.37138238, 346.0973893944 5.929230648356
- if not (line.strip() and line[0].isdigit()): return None
-
- try:
- data = line.split(',')
- coin.time = datetime.strptime(data[0], "%Y-%m-%d")
- coin.value = float(data[4])
- coin["Open"] = float(data[1])
- coin["High"] = float(data[2])
- coin["Low"] = float(data[3])
- coin["Close"] = float(data[4])
- coin["VolumeBTC"] = float(data[5])
- coin["VolumeUSD"] = float(data[6])
- coin["WeightedPrice"] = float(data[7])
- return coin
-
- except ValueError:
- # Do nothing, possible error in json decoding
- return None
diff --git a/fincept-qt/scripts/strategies/LongAndShortButterflyCallStrategiesAlgorithm.py b/fincept-qt/scripts/strategies/LongAndShortButterflyCallStrategiesAlgorithm.py
deleted file mode 100644
index 19b3ba1f9..000000000
--- a/fincept-qt/scripts/strategies/LongAndShortButterflyCallStrategiesAlgorithm.py
+++ /dev/null
@@ -1,79 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-EC39F086
-# Category: General Strategy
-# Description: This algorithm demonstrate how to use OptionStrategies helper class to batch send orders for common strategies. In th...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-import itertools
-
-from OptionStrategyFactoryMethodsBaseAlgorithm import *
-
-### <summary>
-### This algorithm demonstrate how to use OptionStrategies helper class to batch send orders for common strategies.
-### In this case, the algorithm tests the Butterfly Call and Short Butterfly Call strategies.
-### </summary>
-class LongAndShortButterflyCallStrategiesAlgorithm(OptionStrategyFactoryMethodsBaseAlgorithm):
-
- def expected_orders_count(self) -> int:
- return 6
-
- def trade_strategy(self, chain: OptionChain, option_symbol: Symbol):
- call_contracts = (contract for contract in chain if contract.right == OptionRight.CALL)
-
- for expiry, group in itertools.groupby(call_contracts, lambda x: x.expiry):
- contracts = list(group)
- if len(contracts) < 3:
- continue
-
- strikes = sorted([contract.strike for contract in contracts])
- atm_strike = min(strikes, key=lambda strike: abs(strike - chain.underlying.price))
- spread = min(atm_strike - strikes[0], strikes[-1] - atm_strike)
- itm_strike = atm_strike - spread
- otm_strike = atm_strike + spread
-
- if otm_strike in strikes and itm_strike in strikes:
- # Ready to trade
- self._butterfly_call = OptionStrategies.butterfly_call(option_symbol, otm_strike, atm_strike, itm_strike, expiry)
- self._short_butterfly_call = OptionStrategies.short_butterfly_call(option_symbol, otm_strike, atm_strike, itm_strike, expiry)
- self.buy(self._butterfly_call, 2)
- return
-
- def assert_strategy_position_group(self, position_group: IPositionGroup, option_symbol: Symbol):
- positions = list(position_group.positions)
- if len(positions) != 3:
- raise Exception(f"Expected position group to have 3 positions. Actual: {len(positions)}")
-
- higher_strike = max(leg.strike for leg in self._butterfly_call.option_legs)
- higher_strike_position = next((position for position in positions
- if position.symbol.id.option_right == OptionRight.CALL and position.symbol.id.strike_price == higher_strike),
- None)
-
- if higher_strike_position.quantity != 2:
- raise Exception(f"Expected higher strike position quantity to be 2. Actual: {higher_strike_position.quantity}")
-
- lower_strike = min(leg.strike for leg in self._butterfly_call.option_legs)
- lower_strike_position = next((position for position in positions
- if position.symbol.id.option_right == OptionRight.CALL and position.symbol.id.strike_price == lower_strike),
- None)
-
- if lower_strike_position.quantity != 2:
- raise Exception(f"Expected lower strike position quantity to be 2. Actual: {lower_strike_position.quantity}")
-
- middle_strike = [leg.strike for leg in self._butterfly_call.option_legs if leg.strike < higher_strike and leg.strike > lower_strike][0]
- middle_strike_position = next((position for position in positions
- if position.symbol.id.option_right == OptionRight.CALL and position.symbol.id.strike_price == middle_strike),
- None)
-
- if middle_strike_position.quantity != -4:
- raise Exception(f"Expected middle strike position quantity to be -4. Actual: {middle_strike_position.quantity}")
-
- def liquidate_strategy(self):
- # We should be able to close the position using the inverse strategy (a short butterfly call)
- self.buy(self._short_butterfly_call, 2)
diff --git a/fincept-qt/scripts/strategies/LongAndShortButterflyPutStrategiesAlgorithm.py b/fincept-qt/scripts/strategies/LongAndShortButterflyPutStrategiesAlgorithm.py
deleted file mode 100644
index 5562d964c..000000000
--- a/fincept-qt/scripts/strategies/LongAndShortButterflyPutStrategiesAlgorithm.py
+++ /dev/null
@@ -1,79 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-812F2B68
-# Category: General Strategy
-# Description: This algorithm demonstrate how to use OptionStrategies helper class to batch send orders for common strategies. In th...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-import itertools
-
-from OptionStrategyFactoryMethodsBaseAlgorithm import *
-
-### <summary>
-### This algorithm demonstrate how to use OptionStrategies helper class to batch send orders for common strategies.
-### In this case, the algorithm tests the Butterfly Put and Short Butterfly Put strategies.
-### </summary>
-class LongAndShortButterflyPutStrategiesAlgorithm(OptionStrategyFactoryMethodsBaseAlgorithm):
-
- def expected_orders_count(self) -> int:
- return 6
-
- def trade_strategy(self, chain: OptionChain, option_symbol: Symbol):
- put_contracts = (contract for contract in chain if contract.right == OptionRight.PUT)
-
- for expiry, group in itertools.groupby(put_contracts, lambda x: x.expiry):
- contracts = list(group)
- if len(contracts) < 3:
- continue
-
- strikes = sorted([contract.strike for contract in contracts])
- atm_strike = min(strikes, key=lambda strike: abs(strike - chain.underlying.price))
- spread = min(atm_strike - strikes[0], strikes[-1] - atm_strike)
- itm_strike = atm_strike + spread
- otm_strike = atm_strike - spread
-
- if otm_strike in strikes and itm_strike in strikes:
- # Ready to trade
- self._butterfly_put = OptionStrategies.butterfly_put(option_symbol, itm_strike, atm_strike, otm_strike, expiry)
- self._short_butterfly_put = OptionStrategies.short_butterfly_put(option_symbol, itm_strike, atm_strike, otm_strike, expiry)
- self.buy(self._butterfly_put, 2)
- return
-
- def assert_strategy_position_group(self, position_group: IPositionGroup, option_symbol: Symbol):
- positions = list(position_group.positions)
- if len(positions) != 3:
- raise Exception(f"Expected position group to have 3 positions. Actual: {len(positions)}")
-
- higher_strike = max(leg.strike for leg in self._butterfly_put.option_legs)
- higher_strike_position = next((position for position in positions
- if position.symbol.id.option_right == OptionRight.PUT and position.symbol.id.strike_price == higher_strike),
- None)
-
- if higher_strike_position.quantity != 2:
- raise Exception(f"Expected higher strike position quantity to be 2. Actual: {higher_strike_position.quantity}")
-
- lower_strike = min(leg.strike for leg in self._butterfly_put.option_legs)
- lower_strike_position = next((position for position in positions
- if position.symbol.id.option_right == OptionRight.PUT and position.symbol.id.strike_price == lower_strike),
- None)
-
- if lower_strike_position.quantity != 2:
- raise Exception(f"Expected lower strike position quantity to be 2. Actual: {lower_strike_position.quantity}")
-
- middle_strike = [leg.strike for leg in self._butterfly_put.option_legs if leg.strike < higher_strike and leg.strike > lower_strike][0]
- middle_strike_position = next((position for position in positions
- if position.symbol.id.option_right == OptionRight.PUT and position.symbol.id.strike_price == middle_strike),
- None)
-
- if middle_strike_position.quantity != -4:
- raise Exception(f"Expected middle strike position quantity to be -4. Actual: {middle_strike_position.quantity}")
-
- def liquidate_strategy(self):
- # We should be able to close the position using the inverse strategy (a short butterfly put)
- self.buy(self._short_butterfly_put, 2);
diff --git a/fincept-qt/scripts/strategies/LongAndShortCallCalendarSpreadStrategiesAlgorithm.py b/fincept-qt/scripts/strategies/LongAndShortCallCalendarSpreadStrategiesAlgorithm.py
deleted file mode 100644
index 109ebbd24..000000000
--- a/fincept-qt/scripts/strategies/LongAndShortCallCalendarSpreadStrategiesAlgorithm.py
+++ /dev/null
@@ -1,61 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-8F4CCF9F
-# Category: General Strategy
-# Description: This algorithm demonstrate how to use OptionStrategies helper class to batch send orders for common strategies. In th...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-import itertools
-
-from OptionStrategyFactoryMethodsBaseAlgorithm import *
-
-### <summary>
-### This algorithm demonstrate how to use OptionStrategies helper class to batch send orders for common strategies.
-### In this case, the algorithm tests the Call Calendar Spread and Short Call Calendar Spread strategies.
-### </summary>
-class LongAndShortCallCalendarSpreadStrategiesAlgorithm(OptionStrategyFactoryMethodsBaseAlgorithm):
-
- def expected_orders_count(self) -> int:
- return 4
-
- def trade_strategy(self, chain: OptionChain, option_symbol: Symbol):
- call_contracts = sorted((contract for contract in chain if contract.right == OptionRight.CALL),
- key=lambda x: abs(x.strike - chain.underlying.value))
- for strike, group in itertools.groupby(call_contracts, lambda x: x.strike):
- contracts = sorted(group, key=lambda x: x.expiry)
- if len(contracts) < 2: continue
-
- self._near_expiration = contracts[0].expiry
- self._far_expiration = contracts[1].expiry
-
- self._call_calendar_spread = OptionStrategies.call_calendar_spread(option_symbol, strike, self._near_expiration, self._far_expiration)
- self._short_call_calendar_spread = OptionStrategies.short_call_calendar_spread(option_symbol, strike, self._near_expiration, self._far_expiration)
- self.buy(self._call_calendar_spread, 2)
- return
-
- def assert_strategy_position_group(self, position_group: IPositionGroup, option_symbol: Symbol):
- positions = list(position_group.positions)
- if len(positions) != 2:
- raise Exception(f"Expected position group to have 2 positions. Actual: {len(positions)}")
-
- near_expiration_position = next((position for position in positions
- if position.symbol.id.option_right == OptionRight.CALL and position.symbol.id.date == self._near_expiration),
- None)
- if near_expiration_position is None or near_expiration_position.quantity != -2:
- raise Exception(f"Expected near expiration position to be -2. Actual: {near_expiration_position.quantity}")
-
- far_expiration_position = next((position for position in positions
- if position.symbol.id.option_right == OptionRight.CALL and position.symbol.id.date == self._far_expiration),
- None)
- if far_expiration_position is None or far_expiration_position.quantity != 2:
- raise Exception(f"Expected far expiration position to be 2. Actual: {far_expiration_position.quantity}")
-
- def liquidate_strategy(self):
- # We should be able to close the position using the inverse strategy (a short call calendar spread)
- self.buy(self._short_call_calendar_spread, 2)
diff --git a/fincept-qt/scripts/strategies/LongAndShortPutCalendarSpreadStrategiesAlgorithm.py b/fincept-qt/scripts/strategies/LongAndShortPutCalendarSpreadStrategiesAlgorithm.py
deleted file mode 100644
index 6a04c9102..000000000
--- a/fincept-qt/scripts/strategies/LongAndShortPutCalendarSpreadStrategiesAlgorithm.py
+++ /dev/null
@@ -1,61 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-27A6F4AF
-# Category: General Strategy
-# Description: This algorithm demonstrate how to use OptionStrategies helper class to batch send orders for common strategies. In th...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-import itertools
-
-from OptionStrategyFactoryMethodsBaseAlgorithm import *
-
-### <summary>
-### This algorithm demonstrate how to use OptionStrategies helper class to batch send orders for common strategies.
-### In this case, the algorithm tests the Put Calendar Spread and Short Put Calendar Spread strategies.
-### </summary>
-class LongAndShortPutCalendarSpreadStrategiesAlgorithm(OptionStrategyFactoryMethodsBaseAlgorithm):
-
- def expected_orders_count(self) -> int:
- return 4
-
- def trade_strategy(self, chain: OptionChain, option_symbol: Symbol):
- put_contracts = sorted((contract for contract in chain if contract.right == OptionRight.PUT),
- key=lambda x: abs(x.strike - chain.underlying.value))
- for strike, group in itertools.groupby(put_contracts, lambda x: x.strike):
- contracts = sorted(group, key=lambda x: x.expiry)
- if len(contracts) < 2: continue
-
- self._near_expiration = contracts[0].expiry
- self._far_expiration = contracts[1].expiry
-
- self._put_calendar_spread = OptionStrategies.put_calendar_spread(option_symbol, strike, self._near_expiration, self._far_expiration)
- self._short_put_calendar_spread = OptionStrategies.short_put_calendar_spread(option_symbol, strike, self._near_expiration, self._far_expiration)
- self.buy(self._put_calendar_spread, 2)
- return
-
- def assert_strategy_position_group(self, position_group: IPositionGroup, option_symbol: Symbol):
- positions = list(position_group.positions)
- if len(positions) != 2:
- raise Exception(f"Expected position group to have 2 positions. Actual: {len(positions)}")
-
- near_expiration_position = next((position for position in positions
- if position.symbol.id.option_right == OptionRight.PUT and position.symbol.id.date == self._near_expiration),
- None)
- if near_expiration_position is None or near_expiration_position.quantity != -2:
- raise Exception(f"Expected near expiration position to be -2. Actual: {near_expiration_position.quantity}")
-
- far_expiration_position = next((position for position in positions
- if position.symbol.id.option_right == OptionRight.PUT and position.symbol.id.date == self._far_expiration),
- None)
- if far_expiration_position is None or far_expiration_position.quantity != 2:
- raise Exception(f"Expected far expiration position to be 2. Actual: {far_expiration_position.quantity}")
-
- def liquidate_strategy(self):
- # We should be able to close the position using the inverse strategy (a short put calendar spread)
- self.buy(self._short_put_calendar_spread, 2)
diff --git a/fincept-qt/scripts/strategies/LongAndShortStraddleStrategiesAlgorithm.py b/fincept-qt/scripts/strategies/LongAndShortStraddleStrategiesAlgorithm.py
deleted file mode 100644
index 292fa781d..000000000
--- a/fincept-qt/scripts/strategies/LongAndShortStraddleStrategiesAlgorithm.py
+++ /dev/null
@@ -1,69 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-9BF2DDCB
-# Category: General Strategy
-# Description: This algorithm demonstrate how to use OptionStrategies helper class to batch send orders for common strategies. In th...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-import itertools
-from AlgorithmImports import *
-
-from OptionStrategyFactoryMethodsBaseAlgorithm import *
-
-### <summary>
-### This algorithm demonstrate how to use OptionStrategies helper class to batch send orders for common strategies.
-### In this case, the algorithm tests the Straddle and Short Straddle strategies.
-### </summary>
-class LongAndShortStraddleStrategiesAlgorithm(OptionStrategyFactoryMethodsBaseAlgorithm):
-
- def expected_orders_count(self) -> int:
- return 4
-
- def trade_strategy(self, chain: OptionChain, option_symbol: Symbol):
- contracts = sorted(sorted(chain, key=lambda x: abs(chain.underlying.price - x.strike)),
- key=lambda x: x.expiry, reverse=True)
- grouped_contracts = [list(group) for _, group in itertools.groupby(contracts, lambda x: (x.strike, x.expiry))]
- grouped_contracts = (group
- for group in grouped_contracts
- if (any(contract.right == OptionRight.CALL for contract in group) and
- any(contract.right == OptionRight.PUT for contract in group)))
- contracts = next(grouped_contracts, [])
-
- if len(contracts) == 0:
- return
-
- contract = contracts[0]
- if contract is not None:
- self._straddle = OptionStrategies.straddle(option_symbol, contract.strike, contract.expiry)
- self._short_straddle = OptionStrategies.short_straddle(option_symbol, contract.strike, contract.expiry)
- self.buy(self._straddle, 2)
-
- def assert_strategy_position_group(self, position_group: IPositionGroup, option_symbol: Symbol):
- positions = list(position_group.positions)
- if len(positions) != 2:
- raise Exception(f"Expected position group to have 2 positions. Actual: {len(positions)}")
-
- call_position = next((position for position in positions if position.symbol.id.option_right == OptionRight.CALL), None)
- if call_position is None:
- raise Exception("Expected position group to have a call position")
-
- put_position = next((position for position in positions if position.symbol.id.option_right == OptionRight.PUT), None)
- if put_position is None:
- raise Exception("Expected position group to have a put position")
-
- expected_call_position_quantity = 2
- expected_put_position_quantity = 2
-
- if call_position.quantity != expected_call_position_quantity:
- raise Exception(f"Expected call position quantity to be {expected_call_position_quantity}. Actual: {call_position.quantity}")
-
- if put_position.quantity != expected_put_position_quantity:
- raise Exception(f"Expected put position quantity to be {expected_put_position_quantity}. Actual: {put_position.quantity}")
-
- def liquidate_strategy(self):
- # We should be able to close the position using the inverse strategy (a short straddle)
- self.buy(self._short_straddle, 2)
diff --git a/fincept-qt/scripts/strategies/LongAndShortStrangleStrategiesAlgorithm.py b/fincept-qt/scripts/strategies/LongAndShortStrangleStrategiesAlgorithm.py
deleted file mode 100644
index 3092aba10..000000000
--- a/fincept-qt/scripts/strategies/LongAndShortStrangleStrategiesAlgorithm.py
+++ /dev/null
@@ -1,74 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-73CA6D31
-# Category: General Strategy
-# Description: This algorithm demonstrate how to use OptionStrategies helper class to batch send orders for common strategies. In th...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-import itertools
-from AlgorithmImports import *
-
-from OptionStrategyFactoryMethodsBaseAlgorithm import *
-
-### <summary>
-### This algorithm demonstrate how to use OptionStrategies helper class to batch send orders for common strategies.
-### In this case, the algorithm tests the Strangle and Short Strangle strategies.
-### </summary>
-class LongAndShortStrangleStrategiesAlgorithm(OptionStrategyFactoryMethodsBaseAlgorithm):
-
- def expected_orders_count(self) -> int:
- return 4
-
- def trade_strategy(self, chain: OptionChain, option_symbol: Symbol):
- contracts = sorted(sorted(chain, key=lambda x: abs(chain.underlying.price - x.strike)),
- key=lambda x: x.expiry, reverse=True)
- grouped_contracts = (list(group) for _, group in itertools.groupby(contracts, lambda x: x.expiry))
-
- call_contract = None
- put_contract = None
- for group in grouped_contracts:
- call_contracts = sorted((contract for contract in group if contract.right == OptionRight.CALL),
- key=lambda x: x.strike, reverse=True)
- put_contracts = sorted((contract for contract in group if contract.right == OptionRight.PUT),
- key=lambda x: x.strike)
-
- if len(call_contracts) > 0 and len(put_contracts) > 0 and call_contracts[0].strike > put_contracts[0].strike:
- call_contract = call_contracts[0]
- put_contract = put_contracts[0]
- break
-
- if call_contract is not None and put_contract is not None:
- self._strangle = OptionStrategies.strangle(option_symbol, call_contract.strike, put_contract.strike, call_contract.expiry)
- self._short_strangle = OptionStrategies.short_strangle(option_symbol, call_contract.strike, put_contract.strike,
- call_contract.expiry)
- self.buy(self._strangle, 2)
-
- def assert_strategy_position_group(self, position_group: IPositionGroup, option_symbol: Symbol):
- positions = list(position_group.positions)
- if len(positions) != 2:
- raise Exception(f"Expected position group to have 2 positions. Actual: {len(positions)}")
-
- call_position = next((position for position in positions if position.symbol.id.option_right == OptionRight.CALL), None)
- if call_position is None:
- raise Exception("Expected position group to have a call position")
-
- put_position = next((position for position in positions if position.symbol.id.option_right == OptionRight.PUT), None)
- if put_position is None:
- raise Exception("Expected position group to have a put position")
-
- expected_call_position_quantity = 2
- expected_put_position_quantity = 2
-
- if call_position.quantity != expected_call_position_quantity:
- raise Exception(f"Expected call position quantity to be {expected_call_position_quantity}. Actual: {call_position.quantity}")
-
- if put_position.quantity != expected_put_position_quantity:
- raise Exception(f"Expected put position quantity to be {expected_put_position_quantity}. Actual: {put_position.quantity}")
-
- def liquidate_strategy(self):
- # We should be able to close the position using the inverse strategy (a short strangle)
- self.buy(self._short_strangle, 2)
diff --git a/fincept-qt/scripts/strategies/LongOnlyAlphaStreamAlgorithm.py b/fincept-qt/scripts/strategies/LongOnlyAlphaStreamAlgorithm.py
deleted file mode 100644
index 8b18ccd1d..000000000
--- a/fincept-qt/scripts/strategies/LongOnlyAlphaStreamAlgorithm.py
+++ /dev/null
@@ -1,63 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-BEFEB617
-# Category: Alpha Model
-# Description: Basic template framework algorithm uses framework components to define the algorithm. Shows EqualWeightingPortfolioCo...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-from Portfolio.EqualWeightingPortfolioConstructionModel import EqualWeightingPortfolioConstructionModel
-from Execution.ImmediateExecutionModel import ImmediateExecutionModel
-from Selection.ManualUniverseSelectionModel import ManualUniverseSelectionModel
-
-### <summary>
-### Basic template framework algorithm uses framework components to define the algorithm.
-### Shows EqualWeightingPortfolioConstructionModel.long_only() application
-### </summary>
-### <meta name="tag" content="alpha streams" />
-### <meta name="tag" content="using quantconnect" />
-### <meta name="tag" content="algorithm framework" />
-class LongOnlyAlphaStreamAlgorithm(QCAlgorithm):
-
- def initialize(self):
- # 1. Required:
- self.set_start_date(2013, 10, 7)
- self.set_end_date(2013, 10, 11)
-
- # 2. Required: Alpha Streams Models:
- self.set_brokerage_model(BrokerageName.ALPHA_STREAMS)
-
- # 3. Required: Significant AUM Capacity
- self.set_cash(1000000)
-
- # Only SPY will be traded
- self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel(Resolution.DAILY, PortfolioBias.LONG))
- self.set_execution(ImmediateExecutionModel())
-
- # Order margin value has to have a minimum of 0.5% of Portfolio value, allows filtering out small trades and reduce fees.
- # Commented so regression algorithm is more sensitive
- #self.settings.minimum_order_margin_portfolio_percentage = 0.005
-
- # Set algorithm framework models
- self.set_universe_selection(ManualUniverseSelectionModel(
- [Symbol.create(x, SecurityType.EQUITY, Market.USA) for x in ["SPY", "IBM"]]))
-
- def on_data(self, slice):
- if self.portfolio.invested: return
-
- self.emit_insights(
- [
- Insight.price("SPY", timedelta(1), InsightDirection.UP),
- Insight.price("IBM", timedelta(1), InsightDirection.DOWN)
- ])
-
- def on_order_event(self, order_event):
- if order_event.status == OrderStatus.FILLED:
- if self.securities[order_event.symbol].holdings.is_short:
- raise ValueError("Invalid position, should not be short")
- self.debug(order_event)
diff --git a/fincept-qt/scripts/strategies/MACDTrendAlgorithm.py b/fincept-qt/scripts/strategies/MACDTrendAlgorithm.py
deleted file mode 100644
index 05896bdef..000000000
--- a/fincept-qt/scripts/strategies/MACDTrendAlgorithm.py
+++ /dev/null
@@ -1,63 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-F328066F
-# Category: Momentum
-# Description: Simple indicator demonstration algorithm of MACD
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Simple indicator demonstration algorithm of MACD
-### </summary>
-### <meta name="tag" content="indicators" />
-### <meta name="tag" content="indicator classes" />
-### <meta name="tag" content="plotting indicators" />
-class MACDTrendAlgorithm(QCAlgorithm):
-
- def initialize(self):
- '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
-
- self.set_start_date(2004, 1, 1) #Set Start Date
- self.set_end_date(2015, 1, 1) #Set End Date
- self.set_cash(100000) #Set Strategy Cash
- # Fincept Terminal Strategy Engine - Symbol Configuration
- self.add_equity("SPY", Resolution.DAILY)
-
- # define our daily macd(12,26) with a 9 day signal
- self.__macd = self.macd("SPY", 12, 26, 9, MovingAverageType.EXPONENTIAL, Resolution.DAILY)
- self.__previous = datetime.min
- self.plot_indicator("MACD", True, self.__macd, self.__macd.signal)
- self.plot_indicator("SPY", self.__macd.fast, self.__macd.slow)
-
-
- def on_data(self, data):
- '''on_data event is the primary entry point for your algorithm. Each new data point will be pumped in here.'''
- # wait for our macd to fully initialize
- if not self.__macd.is_ready: return
-
- # only once per day
- if self.__previous.date() == self.time.date(): return
-
- # define a small tolerance on our checks to avoid bouncing
- tolerance = 0.0025
-
- holdings = self.portfolio["SPY"].quantity
-
- signal_delta_percent = (self.__macd.current.value - self.__macd.signal.current.value)/self.__macd.fast.current.value
-
- # if our macd is greater than our signal, then let's go long
- if holdings <= 0 and signal_delta_percent > tolerance: # 0.01%
- # longterm says buy as well
- self.set_holdings("SPY", 1.0)
-
- # of our macd is less than our signal, then let's go short
- elif holdings >= 0 and signal_delta_percent < -tolerance:
- self.liquidate("SPY")
-
-
- self.__previous = self.time
diff --git a/fincept-qt/scripts/strategies/MacdAlphaModelFrameworkRegressionAlgorithm.py b/fincept-qt/scripts/strategies/MacdAlphaModelFrameworkRegressionAlgorithm.py
deleted file mode 100644
index 5a5ab25eb..000000000
--- a/fincept-qt/scripts/strategies/MacdAlphaModelFrameworkRegressionAlgorithm.py
+++ /dev/null
@@ -1,28 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-EABA6096
-# Category: Alpha Model
-# Description: Regression algorithm to assert the behavior of <see cref="MacdAlphaModel"/>
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-from BaseFrameworkRegressionAlgorithm import BaseFrameworkRegressionAlgorithm
-from Alphas.MacdAlphaModel import MacdAlphaModel
-
-### <summary>
-### Regression algorithm to assert the behavior of <see cref="MacdAlphaModel"/>.
-### </summary>
-class MacdAlphaModelFrameworkRegressionAlgorithm(BaseFrameworkRegressionAlgorithm):
-
- def initialize(self):
- super().initialize()
- self.set_alpha(MacdAlphaModel())
-
- def on_end_of_algorithm(self):
- expected = 4
- if self.insights.total_count != expected:
- raise Exception(f"The total number of insights should be {expected}. Actual: {self.insights.total_count}")
diff --git a/fincept-qt/scripts/strategies/ManuallyRemovedConsolidatorsAlgorithm.py b/fincept-qt/scripts/strategies/ManuallyRemovedConsolidatorsAlgorithm.py
deleted file mode 100644
index 9018cf65e..000000000
--- a/fincept-qt/scripts/strategies/ManuallyRemovedConsolidatorsAlgorithm.py
+++ /dev/null
@@ -1,108 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-C0569D9C
-# Category: Data Consolidation
-# Description: Algorithm asserting that the consolidators are removed from the SubscriptionManager. This makes sure that we don't lo...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Algorithm asserting that the consolidators are removed from the SubscriptionManager.
-### This makes sure that we don't lose references to python consolidators when
-### they are wrapped in a DataConsolidatorPythonWrapper.
-### </summary>
-class ManuallyRemovedConsolidatorsAlgorithm(QCAlgorithm):
-
- def initialize(self) -> None:
- self.set_start_date(2013, 10, 7)
- self.set_end_date(2013, 10, 11)
-
- self.consolidators = []
-
- self.spy = self.add_equity("SPY").symbol
-
- # Case 1: consolidator registered through a RegisterIndicator() call,
- # which will wrap the consolidator instance in a DataConsolidatorPythonWrapper
- consolidator = self.resolve_consolidator(self.spy, Resolution.MINUTE)
- self.consolidators.append(consolidator)
-
- indicator_name = self.create_indicator_name(self.spy, "close", Resolution.MINUTE)
- identity = Identity(indicator_name)
- self.indicator = self.register_indicator(self.spy, identity, consolidator)
-
- # Case 2: consolidator registered directly through the SubscriptionManager
- consolidator = self.resolve_consolidator(self.spy, Resolution.MINUTE)
- self.consolidators.append(consolidator)
- self.subscription_manager.add_consolidator(self.spy, consolidator)
-
- # Case 3: custom python consolidator not derived from IDataConsolidator
- consolidator = CustomQuoteBarConsolidator(timedelta(hours=1))
- self.consolidators.append(consolidator)
- self.subscription_manager.add_consolidator(self.spy, consolidator)
-
- def on_end_of_algorithm(self) -> None:
- # Remove the first consolidator
-
- for i in range(3):
- consolidator = self.consolidators[i]
- self.remove_consolidator(consolidator, expected_consolidator_count=2 - i)
-
- def remove_consolidator(self, consolidator: IDataConsolidator, expected_consolidator_count: int) -> None:
- self.subscription_manager.remove_consolidator(self.spy, consolidator)
-
- consolidator_count = sum(s.consolidators.count for s in self.subscription_manager.subscriptions)
- if consolidator_count != expected_consolidator_count:
- raise Exception(f"Unexpected number of consolidators after removal. "
- f"Expected: {expected_consolidator_count}. Actual: {consolidator_count}")
-
-class CustomQuoteBarConsolidator(PythonConsolidator):
- '''A custom quote bar consolidator that inherits from PythonConsolidator and implements
- the IDataConsolidator interface, it must implement all of IDataConsolidator. Reference
- PythonConsolidator.cs and DataConsolidatorPythonWrapper.PY for more information.
-
- This class shows how to implement a consolidator from scratch in Python, this gives us more
- freedom to determine the behavior of the consolidator but can't leverage any of the built in
- functions of an inherited class.
-
- For this example we implemented a Quotebar from scratch'''
-
- def __init__(self, period):
-
- #IDataConsolidator required vars for all consolidators
- self.consolidated = None #Most recently consolidated piece of data.
- self.working_data = None #Data being currently consolidated
- self.input_type = QuoteBar #The type consumed by this consolidator
- self.output_type = QuoteBar #The type produced by this consolidator
-
- #Consolidator Variables
- self.period = period
-
- def update(self, data):
- '''Updates this consolidator with the specified data'''
-
- #If we don't have bar yet, create one
- if self.working_data is None:
- self.working_data = QuoteBar(data.time,data.symbol,data.bid,data.last_bid_size,
- data.ask,data.last_ask_size,self.period)
-
- #Update bar using QuoteBar's update()
- self.working_data.update(data.value, data.bid.close, data.ask.close, 0,
- data.last_bid_size, data.last_ask_size)
-
- def scan(self, time):
- '''Scans this consolidator to see if it should emit a bar due to time passing'''
-
- if self.period is not None and self.working_data is not None:
- if time - self.working_data.time >= self.period:
-
- #Trigger the event handler with a copy of self and the data
- self.on_data_consolidated(self, self.working_data)
-
- #Set the most recent consolidated piece of data and then clear the working_data
- self.consolidated = self.working_data
- self.working_data = None
diff --git a/fincept-qt/scripts/strategies/ManuallySetMarketHoursAndSymbolPropertiesDatabaseEntriesAlgorithm.py b/fincept-qt/scripts/strategies/ManuallySetMarketHoursAndSymbolPropertiesDatabaseEntriesAlgorithm.py
deleted file mode 100644
index 7f4f4ff07..000000000
--- a/fincept-qt/scripts/strategies/ManuallySetMarketHoursAndSymbolPropertiesDatabaseEntriesAlgorithm.py
+++ /dev/null
@@ -1,68 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-A4B98519
-# Category: General Strategy
-# Description: Algorithm illustrating how to manually set market hours and symbol properties database entries to be picked up by the...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-import Newtonsoft.Json as json
-
-### <summary>
-### Algorithm illustrating how to manually set market hours and symbol properties database entries to be picked up by the algorithm's securities.
-### This specific case illustrates how to do it for CFDs to match InteractiveBrokers brokerage, which has different market hours
-### depending on the CFD underlying asset.
-### </summary>
-class ManuallySetMarketHoursAndSymbolPropertiesDatabaseEntriesAlgorithm(QCAlgorithm):
- '''
- Algorithm illustrating how to manually set market hours and symbol properties database entries to be picked up by the algorithm's securities.
- This specific case illustrates how to do it for CFDs to match InteractiveBrokers brokerage, which has different market hours
- depending on the CFD underlying asset.
- '''
-
- def initialize(self):
- self.set_start_date(2013,10, 7)
- self.set_end_date(2013,10,11)
- self.set_cash(100000)
-
- self.set_brokerage_model(BrokerageName.INTERACTIVE_BROKERS_BROKERAGE)
-
- # Some brokerages like InteractiveBrokers make a difference on CFDs depending on the underlying (equity, index, metal, forex).
- # Depending on this, the market hours can be different. In order to be more specific with the market hours,
- # we can set the MarketHoursDatabase entry for the CFDs.
-
- # Equity CFDs are usually traded the same hours as the equity market.
- equity_market_hours_entry = self.market_hours_database.get_entry(Market.USA, None, SecurityType.EQUITY)
- self.market_hours_database.set_entry(Market.INTERACTIVE_BROKERS, "", SecurityType.CFD, equity_market_hours_entry.exchange_hours, equity_market_hours_entry.data_time_zone)
-
- # The same can be done for the symbol properties, in case they are different depending on the underlying
- equity_symbol_properties = self.symbol_properties_database.get_symbol_properties(Market.USA, None, SecurityType.EQUITY, Currencies.USD)
- self.symbol_properties_database.set_entry(Market.INTERACTIVE_BROKERS, None, SecurityType.CFD, equity_symbol_properties)
-
- spy_cfd = self.add_cfd("SPY", market=Market.INTERACTIVE_BROKERS)
-
- if json.JsonConvert.serialize_object(spy_cfd.exchange.hours) != json.JsonConvert.serialize_object(equity_market_hours_entry.exchange_hours):
- raise Exception("Expected the SPY CFD market hours to be the same as the underlying equity market hours.")
-
- if json.JsonConvert.serialize_object(spy_cfd.symbol_properties) != json.JsonConvert.serialize_object(equity_symbol_properties):
- raise Exception("Expected the SPY CFD symbol properties to be the same as the underlying equity symbol properties.")
-
- # We can also do it for a specific ticker
- aud_usd_forex_market_hours_entry = self.market_hours_database.get_entry(Market.OANDA, None, SecurityType.FOREX)
- self.market_hours_database.set_entry(Market.INTERACTIVE_BROKERS, "AUDUSD", SecurityType.CFD, aud_usd_forex_market_hours_entry.exchange_hours, aud_usd_forex_market_hours_entry.data_time_zone)
-
- aud_usd_forex_symbol_properties = self.symbol_properties_database.get_symbol_properties(Market.OANDA, "AUDUSD", SecurityType.FOREX, Currencies.USD)
- self.symbol_properties_database.set_entry(Market.INTERACTIVE_BROKERS, "AUDUSD", SecurityType.CFD, aud_usd_forex_symbol_properties)
-
- aud_usd_cfd = self.add_cfd("AUDUSD", market=Market.INTERACTIVE_BROKERS)
-
- if json.JsonConvert.serialize_object(aud_usd_cfd.exchange.hours) != json.JsonConvert.serialize_object(aud_usd_forex_market_hours_entry.exchange_hours):
- raise Exception("Expected the AUDUSD CFD market hours to be the same as the underlying forex market hours.")
-
- if json.JsonConvert.serialize_object(aud_usd_cfd.symbol_properties) != json.JsonConvert.serialize_object(aud_usd_forex_symbol_properties):
- raise Exception("Expected the AUDUSD CFD symbol properties to be the same as the underlying forex symbol properties.")
diff --git a/fincept-qt/scripts/strategies/MarginCallEventsAlgorithm.py b/fincept-qt/scripts/strategies/MarginCallEventsAlgorithm.py
deleted file mode 100644
index 0037b691a..000000000
--- a/fincept-qt/scripts/strategies/MarginCallEventsAlgorithm.py
+++ /dev/null
@@ -1,63 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-FB2B7755
-# Category: Margin
-# Description: This algorithm showcases two margin related event handlers. OnMarginCallWarning: Fired when a portfolio's remaining m...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### This algorithm showcases two margin related event handlers.
-### OnMarginCallWarning: Fired when a portfolio's remaining margin dips below 5% of the total portfolio value
-### OnMarginCall: Fired immediately before margin call orders are execued, this gives the algorithm a change to regain margin on its own through liquidation
-### </summary>
-### <meta name="tag" content="securities and portfolio" />
-### <meta name="tag" content="margin models" />
-class MarginCallEventsAlgorithm(QCAlgorithm):
- """
- This algorithm showcases two margin related event handlers.
- on_margin_call_warning: Fired when a portfolio's remaining margin dips below 5% of the total portfolio value
- on_margin_call: Fired immediately before margin call orders are execued, this gives the algorithm a change to regain margin on its own through liquidation
- """
-
- def initialize(self):
- self.set_cash(100000)
- self.set_start_date(2013,10,1)
- self.set_end_date(2013,12,11)
- self.add_equity("SPY", Resolution.SECOND)
- # cranking up the leverage increases the odds of a margin call
- # when the security falls in value
- self.securities["SPY"].set_leverage(100)
-
- def on_data(self, data):
- if not self.portfolio.invested:
- self.set_holdings("SPY",100)
-
- def on_margin_call(self, requests):
- # Margin call event handler. This method is called right before the margin call orders are placed in the market.
- # <param name="requests">The orders to be executed to bring this algorithm within margin limits</param>
- # this code gets called BEFORE the orders are placed, so we can try to liquidate some of our positions
- # before we get the margin call orders executed. We could also modify these orders by changing their quantities
- for order in requests:
-
- # liquidate an extra 10% each time we get a margin call to give us more padding
- new_quantity = int(order.quantity * 1.1)
- requests.remove(order)
- requests.append(SubmitOrderRequest(order.order_type, order.security_type, order.symbol, new_quantity, order.stop_price, order.limit_price, self.time, "on_margin_call"))
-
- return requests
-
- def on_margin_call_warning(self):
- # Margin call warning event handler.
- # This method is called when portfolio.margin_remaining is under 5% of your portfolio.total_portfolio_value
- # a chance to prevent a margin call from occurring
-
- spy_holdings = self.securities["SPY"].holdings.quantity
- shares = int(-spy_holdings * 0.005)
- self.error("{0} - on_margin_call_warning(): Liquidating {1} shares of SPY to avoid margin call.".format(self.time, shares))
- self.market_order("SPY", shares)
diff --git a/fincept-qt/scripts/strategies/MarketImpactSlippageModelRegressionAlgorithm.py b/fincept-qt/scripts/strategies/MarketImpactSlippageModelRegressionAlgorithm.py
deleted file mode 100644
index c7331dc68..000000000
--- a/fincept-qt/scripts/strategies/MarketImpactSlippageModelRegressionAlgorithm.py
+++ /dev/null
@@ -1,33 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-26E2B07B
-# Category: Regression Test
-# Description: Market Impact Slippage Model Regression Algorithm
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-class MarketImpactSlippageModelRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2013, 10, 7)
- self.set_end_date(2013, 10, 13)
- self.set_cash(10000000)
-
- spy = self.add_equity("SPY", Resolution.DAILY)
- aapl = self.add_equity("AAPL", Resolution.DAILY)
-
- spy.set_slippage_model(MarketImpactSlippageModel(self))
- aapl.set_slippage_model(MarketImpactSlippageModel(self))
-
- def on_data(self, data):
- self.set_holdings("SPY", 0.5)
- self.set_holdings("AAPL", -0.5)
-
- def on_order_event(self, order_event):
- if order_event.status == OrderStatus.FILLED:
- self.debug(f"Price: {self.securities[order_event.symbol].price}, filled price: {order_event.fill_price}, quantity: {order_event.fill_quantity}")
diff --git a/fincept-qt/scripts/strategies/MarketOnCloseOrderBufferExtendedMarketHoursRegressionAlgorithm.py b/fincept-qt/scripts/strategies/MarketOnCloseOrderBufferExtendedMarketHoursRegressionAlgorithm.py
deleted file mode 100644
index e487efdca..000000000
--- a/fincept-qt/scripts/strategies/MarketOnCloseOrderBufferExtendedMarketHoursRegressionAlgorithm.py
+++ /dev/null
@@ -1,63 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-F8893107
-# Category: Regression Test
-# Description: This regression test is a version of "MarketOnCloseOrderBufferRegressionAlgorithm"
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-class MarketOnCloseOrderBufferExtendedMarketHoursRegressionAlgorithm(QCAlgorithm):
- '''This regression test is a version of "MarketOnCloseOrderBufferRegressionAlgorithm"
- where we test market-on-close modeling with data from the post market.'''
- valid_order_ticket = None
- invalid_order_ticket = None
- valid_order_ticket_extended_market_hours = None
-
- def initialize(self):
- self.set_start_date(2013,10,7) #Set Start Date
- self.set_end_date(2013,10,8) #Set End Date
-
- self.add_equity("SPY", Resolution.MINUTE, extended_market_hours = True)
-
- def moc_at_mid_night():
- self.valid_order_ticket_at_midnight = self.market_on_close_order("SPY", 2)
-
- self.schedule.on(self.date_rules.tomorrow, self.time_rules.midnight, moc_at_mid_night)
-
- # Modify our submission buffer time to 10 minutes
- MarketOnCloseOrder.submission_time_buffer = timedelta(minutes=10)
-
- def on_data(self, data):
- # Test our ability to submit MarketOnCloseOrders
- # Because we set our buffer to 10 minutes, any order placed
- # before 3:50PM should be accepted, any after marked invalid
-
- # Will not throw an order error and execute
- if self.time.hour == 15 and self.time.minute == 49 and not self.valid_order_ticket:
- self.valid_order_ticket = self.market_on_close_order("SPY", 2)
-
- # Will throw an order error and be marked invalid
- if self.time.hour == 15 and self.time.minute == 51 and not self.invalid_order_ticket:
- self.invalid_order_ticket = self.market_on_close_order("SPY", 2)
-
- # Will not throw an order error and execute
- if self.time.hour == 16 and self.time.minute == 48 and not self.valid_order_ticket_extended_market_hours:
- self.valid_order_ticket_extended_market_hours = self.market_on_close_order("SPY", 2)
-
- def on_end_of_algorithm(self):
- # Set it back to default for other regressions
- MarketOnCloseOrder.submission_time_buffer = MarketOnCloseOrder.DEFAULT_SUBMISSION_TIME_BUFFER
-
- if self.valid_order_ticket.status != OrderStatus.FILLED:
- raise Exception("Valid order failed to fill")
-
- if self.invalid_order_ticket.status != OrderStatus.INVALID:
- raise Exception("Invalid order was not rejected")
-
- if self.valid_order_ticket_extended_market_hours.status != OrderStatus.FILLED:
- raise Exception("Valid order during extended market hours failed to fill")
diff --git a/fincept-qt/scripts/strategies/MarketOnCloseOrderBufferRegressionAlgorithm.py b/fincept-qt/scripts/strategies/MarketOnCloseOrderBufferRegressionAlgorithm.py
deleted file mode 100644
index d6a31f8be..000000000
--- a/fincept-qt/scripts/strategies/MarketOnCloseOrderBufferRegressionAlgorithm.py
+++ /dev/null
@@ -1,56 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-74AD11AC
-# Category: Regression Test
-# Description: Market On Close Order Buffer Regression Algorithm
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-class MarketOnCloseOrderBufferRegressionAlgorithm(QCAlgorithm):
- valid_order_ticket = None
- invalid_order_ticket = None
-
- def initialize(self):
- self.set_start_date(2013,10,7) #Set Start Date
- self.set_end_date(2013,10,8) #Set End Date
-
- self.add_equity("SPY", Resolution.MINUTE)
-
- def moc_at_post_market():
- self.valid_order_ticket_extended_market_hours = self.market_on_close_order("SPY", 2)
-
- self.schedule.on(self.date_rules.today, self.time_rules.at(17,0), moc_at_post_market)
-
- # Modify our submission buffer time to 10 minutes
- MarketOnCloseOrder.submission_time_buffer = timedelta(minutes=10)
-
- def on_data(self, data):
- # Test our ability to submit MarketOnCloseOrders
- # Because we set our buffer to 10 minutes, any order placed
- # before 3:50PM should be accepted, any after marked invalid
-
- # Will not throw an order error and execute
- if self.time.hour == 15 and self.time.minute == 49 and not self.valid_order_ticket:
- self.valid_order_ticket = self.market_on_close_order("SPY", 2)
-
- # Will throw an order error and be marked invalid
- if self.time.hour == 15 and self.time.minute == 51 and not self.invalid_order_ticket:
- self.invalid_order_ticket = self.market_on_close_order("SPY", 2)
-
- def on_end_of_algorithm(self):
- # Set it back to default for other regressions
- MarketOnCloseOrder.submission_time_buffer = MarketOnCloseOrder.DEFAULT_SUBMISSION_TIME_BUFFER
-
- if self.valid_order_ticket.status != OrderStatus.FILLED:
- raise Exception("Valid order failed to fill")
-
- if self.invalid_order_ticket.status != OrderStatus.INVALID:
- raise Exception("Invalid order was not rejected")
-
- if self.valid_order_ticket_extended_market_hours.status != OrderStatus.FILLED:
- raise Exception("Valid order during extended market hours failed to fill")
diff --git a/fincept-qt/scripts/strategies/MarketOnOpenOnCloseAlgorithm.py b/fincept-qt/scripts/strategies/MarketOnOpenOnCloseAlgorithm.py
deleted file mode 100644
index 839332ed0..000000000
--- a/fincept-qt/scripts/strategies/MarketOnOpenOnCloseAlgorithm.py
+++ /dev/null
@@ -1,44 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-A5E1134A
-# Category: General Strategy
-# Description: Demonstration of the Market On Close order for US Equities
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Demonstration of the Market On Close order for US Equities.
-### </summary>
-### <meta name="tag" content="trading and orders" />
-### <meta name="tag" content="placing orders" />
-class MarketOnOpenOnCloseAlgorithm(QCAlgorithm):
-
- def initialize(self):
- '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
- self.set_start_date(2013,10,7) #Set Start Date
- self.set_end_date(2013,10,11) #Set End Date
- self.set_cash(100000) #Set Strategy Cash
- # Fincept Terminal Strategy Engine - Symbol Configuration
- self.equity = self.add_equity("SPY", Resolution.SECOND, fill_forward = True, extended_market_hours = True)
- self.__submitted_market_on_close_today = False
- self.__last = datetime.min
-
- def on_data(self, data):
- '''on_data event is the primary entry point for your algorithm. Each new data point will be pumped in here.'''
- if self.time.date() != self.__last.date(): # each morning submit a market on open order
- self.__submitted_market_on_close_today = False
- self.market_on_open_order("SPY", 100)
- self.__last = self.time
-
- if not self.__submitted_market_on_close_today and self.equity.exchange.exchange_open: # once the exchange opens submit a market on close order
- self.__submitted_market_on_close_today = True
- self.market_on_close_order("SPY", -100)
-
- def on_order_event(self, fill):
- order = self.transactions.get_order_by_id(fill.order_id)
- self.log("{0} - {1}:: {2}".format(self.time, order.type, fill))
diff --git a/fincept-qt/scripts/strategies/MaximumDrawdownPercentPerSecurityFrameworkRegressionAlgorithm.py b/fincept-qt/scripts/strategies/MaximumDrawdownPercentPerSecurityFrameworkRegressionAlgorithm.py
deleted file mode 100644
index 76be5912a..000000000
--- a/fincept-qt/scripts/strategies/MaximumDrawdownPercentPerSecurityFrameworkRegressionAlgorithm.py
+++ /dev/null
@@ -1,26 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-791ECD54
-# Category: Regression Test
-# Description: Regression algorithm to assert the behavior of <see cref="MaximumDrawdownPercentPerSecurity"/>
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-from BaseFrameworkRegressionAlgorithm import BaseFrameworkRegressionAlgorithm
-from Risk.MaximumDrawdownPercentPerSecurity import MaximumDrawdownPercentPerSecurity
-
-### <summary>
-### Regression algorithm to assert the behavior of <see cref="MaximumDrawdownPercentPerSecurity"/>.
-### </summary>
-class MaximumDrawdownPercentPerSecurityFrameworkRegressionAlgorithm(BaseFrameworkRegressionAlgorithm):
-
- def initialize(self):
- super().initialize()
- self.set_universe_selection(ManualUniverseSelectionModel(Symbol.create("AAPL", SecurityType.EQUITY, Market.USA)))
-
- self.set_risk_management(MaximumDrawdownPercentPerSecurity(0.004))
-
diff --git a/fincept-qt/scripts/strategies/MaximumDrawdownPercentPortfolioFrameworkRegressionAlgorithm.py b/fincept-qt/scripts/strategies/MaximumDrawdownPercentPortfolioFrameworkRegressionAlgorithm.py
deleted file mode 100644
index 485be06a5..000000000
--- a/fincept-qt/scripts/strategies/MaximumDrawdownPercentPortfolioFrameworkRegressionAlgorithm.py
+++ /dev/null
@@ -1,30 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-7A279BE5
-# Category: Portfolio Management
-# Description: Regression algorithm to assert the behavior of <see cref="MaximumDrawdownPercentPortfolio"/>
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-from BaseFrameworkRegressionAlgorithm import BaseFrameworkRegressionAlgorithm
-from Risk.CompositeRiskManagementModel import CompositeRiskManagementModel
-from Risk.MaximumDrawdownPercentPortfolio import MaximumDrawdownPercentPortfolio
-
-### <summary>
-### Regression algorithm to assert the behavior of <see cref="MaximumDrawdownPercentPortfolio"/>.
-### </summary>
-class MaximumDrawdownPercentPortfolioFrameworkRegressionAlgorithm(BaseFrameworkRegressionAlgorithm):
-
- def initialize(self):
- super().initialize()
- self.set_universe_selection(ManualUniverseSelectionModel(Symbol.create("AAPL", SecurityType.EQUITY, Market.USA)))
-
- # define risk management model as a composite of several risk management models
- self.set_risk_management(CompositeRiskManagementModel(
- MaximumDrawdownPercentPortfolio(0.01), # Avoid loss of initial capital
- MaximumDrawdownPercentPortfolio(0.015, True) # Avoid profit losses
- ))
diff --git a/fincept-qt/scripts/strategies/MaximumSectorExposureRiskManagementModelFrameworkRegressionAlgorithm.py b/fincept-qt/scripts/strategies/MaximumSectorExposureRiskManagementModelFrameworkRegressionAlgorithm.py
deleted file mode 100644
index 6b2b64dc5..000000000
--- a/fincept-qt/scripts/strategies/MaximumSectorExposureRiskManagementModelFrameworkRegressionAlgorithm.py
+++ /dev/null
@@ -1,41 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-C143732F
-# Category: Risk Management
-# Description: Regression algorithm to assert the behavior of <see cref="MaximumSectorExposureRiskManagementModel"/>
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-from BaseFrameworkRegressionAlgorithm import BaseFrameworkRegressionAlgorithm
-from Risk.MaximumSectorExposureRiskManagementModel import MaximumSectorExposureRiskManagementModel
-
-### <summary>
-### Regression algorithm to assert the behavior of <see cref="MaximumSectorExposureRiskManagementModel"/>.
-### </summary>
-class MaximumSectorExposureRiskManagementModelFrameworkRegressionAlgorithm(BaseFrameworkRegressionAlgorithm):
-
- def initialize(self):
- super().initialize()
- # Set requested data resolution
- self.universe_settings.resolution = Resolution.DAILY
-
- self.set_start_date(2014, 2, 1) #Set Start Date
- self.set_end_date(2014, 5, 1) #Set End Date
-
- # set algorithm framework models
- tickers = [ "AAPL", "MSFT", "GOOG", "AIG", "BAC" ]
- self.set_universe_selection(FineFundamentalUniverseSelectionModel(
- lambda coarse: [ x.symbol for x in coarse if x.symbol.value in tickers ],
- lambda fine: [ x.symbol for x in fine ]
- ))
-
- # define risk management model such that maximum weight of a single sector be 10%
- # Number of of trades changed from 34 to 30 when using the MaximumSectorExposureRiskManagementModel
- self.set_risk_management(MaximumSectorExposureRiskManagementModel(0.1))
-
- def on_end_of_algorithm(self):
- pass
diff --git a/fincept-qt/scripts/strategies/MaximumUnrealizedProfitPercentPerSecurityFrameworkRegressionAlgorithm.py b/fincept-qt/scripts/strategies/MaximumUnrealizedProfitPercentPerSecurityFrameworkRegressionAlgorithm.py
deleted file mode 100644
index 438ad1914..000000000
--- a/fincept-qt/scripts/strategies/MaximumUnrealizedProfitPercentPerSecurityFrameworkRegressionAlgorithm.py
+++ /dev/null
@@ -1,25 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-7E35ADAA
-# Category: Regression Test
-# Description: Regression algorithm to assert the behavior of <see cref="MaximumUnrealizedProfitPercentPerSecurity"/>
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-from BaseFrameworkRegressionAlgorithm import BaseFrameworkRegressionAlgorithm
-from Risk.MaximumUnrealizedProfitPercentPerSecurity import MaximumUnrealizedProfitPercentPerSecurity
-
-### <summary>
-### Regression algorithm to assert the behavior of <see cref="MaximumUnrealizedProfitPercentPerSecurity"/>.
-### </summary>
-class MaximumUnrealizedProfitPercentPerSecurityFrameworkRegressionAlgorithm(BaseFrameworkRegressionAlgorithm):
-
- def initialize(self):
- super().initialize()
- self.set_universe_selection(ManualUniverseSelectionModel(Symbol.create("AAPL", SecurityType.EQUITY, Market.USA)))
-
- self.set_risk_management(MaximumUnrealizedProfitPercentPerSecurity(0.004))
diff --git a/fincept-qt/scripts/strategies/MeanReversionPortfolioAlgorithm.py b/fincept-qt/scripts/strategies/MeanReversionPortfolioAlgorithm.py
deleted file mode 100644
index 7a67b58d8..000000000
--- a/fincept-qt/scripts/strategies/MeanReversionPortfolioAlgorithm.py
+++ /dev/null
@@ -1,30 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-98AE653C
-# Category: Portfolio Management
-# Description: Example algorithm of using MeanReversionPortfolioConstructionModel
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-from Portfolio.MeanReversionPortfolioConstructionModel import *
-
-class MeanReversionPortfolioAlgorithm(QCAlgorithm):
- '''Example algorithm of using MeanReversionPortfolioConstructionModel'''
-
- def initialize(self):
- # Set starting date, cash and ending date of the backtest
- self.set_start_date(2020, 9, 1)
- self.set_end_date(2021, 2, 28)
- self.set_cash(100000)
-
- self.set_security_initializer(lambda security: security.set_market_price(self.get_last_known_price(security)))
-
- # Subscribe to data of the selected stocks
- self._symbols = [self.add_equity(ticker, Resolution.DAILY).symbol for ticker in ["SPY", "AAPL"]]
-
- self.add_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(1)))
- self.set_portfolio_construction(MeanReversionPortfolioConstructionModel())
diff --git a/fincept-qt/scripts/strategies/MeanVarianceOptimizationFrameworkAlgorithm.py b/fincept-qt/scripts/strategies/MeanVarianceOptimizationFrameworkAlgorithm.py
deleted file mode 100644
index 870ddd3d3..000000000
--- a/fincept-qt/scripts/strategies/MeanVarianceOptimizationFrameworkAlgorithm.py
+++ /dev/null
@@ -1,54 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-C42B3790
-# Category: General Strategy
-# Description: Mean Variance Optimization algorithm Uses the HistoricalReturnsAlphaModel and the MeanVarianceOptimizationPortfolioCo...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-from Portfolio.MeanVarianceOptimizationPortfolioConstructionModel import *
-
-### <summary>
-### Mean Variance Optimization algorithm
-### Uses the HistoricalReturnsAlphaModel and the MeanVarianceOptimizationPortfolioConstructionModel
-### to create an algorithm that rebalances the portfolio according to modern portfolio theory
-### </summary>
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="using quantconnect" />
-### <meta name="tag" content="trading and orders" />
-class MeanVarianceOptimizationFrameworkAlgorithm(QCAlgorithm):
- '''Mean Variance Optimization algorithm.'''
-
- def initialize(self):
-
- # Set requested data resolution
- self.universe_settings.resolution = Resolution.MINUTE
-
- self.settings.rebalance_portfolio_on_insight_changes = False
-
- self.set_start_date(2013,10,7) #Set Start Date
- self.set_end_date(2013,10,11) #Set End Date
- self.set_cash(100000) #Set Strategy Cash
-
- self._symbols = [ Symbol.create(x, SecurityType.EQUITY, Market.USA) for x in [ 'AIG', 'BAC', 'IBM', 'SPY' ] ]
-
- # set algorithm framework models
- self.set_universe_selection(CoarseFundamentalUniverseSelectionModel(self.coarse_selector))
- self.set_alpha(HistoricalReturnsAlphaModel(resolution = Resolution.DAILY))
- self.set_portfolio_construction(MeanVarianceOptimizationPortfolioConstructionModel())
- self.set_execution(ImmediateExecutionModel())
- self.set_risk_management(NullRiskManagementModel())
-
- def coarse_selector(self, coarse):
- # Drops SPY after the 8th
- last = 3 if self.time.day > 8 else len(self._symbols)
-
- return self._symbols[0:last]
-
- def on_order_event(self, order_event):
- if order_event.status == OrderStatus.FILLED:
- self.log(str(order_event))
diff --git a/fincept-qt/scripts/strategies/MovingAverageCrossAlgorithm.py b/fincept-qt/scripts/strategies/MovingAverageCrossAlgorithm.py
deleted file mode 100644
index ac25a92b8..000000000
--- a/fincept-qt/scripts/strategies/MovingAverageCrossAlgorithm.py
+++ /dev/null
@@ -1,76 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-B8F7654B
-# Category: General Strategy
-# Description: In this example we look at the canonical 15/30 day moving average cross. This algorithm will go long when the 15 cros...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### In this example we look at the canonical 15/30 day moving average cross. This algorithm
-### will go long when the 15 crosses above the 30 and will liquidate when the 15 crosses
-### back below the 30.
-### </summary>
-### <meta name="tag" content="indicators" />
-### <meta name="tag" content="indicator classes" />
-### <meta name="tag" content="moving average cross" />
-### <meta name="tag" content="strategy example" />
-class MovingAverageCrossAlgorithm(QCAlgorithm):
-
- def initialize(self):
- '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
-
- self.set_start_date(2009, 1, 1) #Set Start Date
- self.set_end_date(2015, 1, 1) #Set End Date
- self.set_cash(100000) #Set Strategy Cash
- # Fincept Terminal Strategy Engine - Symbol Configuration
- self.add_equity("SPY")
-
- # create a 15 day exponential moving average
- self.fast = self.ema("SPY", 15, Resolution.DAILY)
-
- # create a 30 day exponential moving average
- self.slow = self.ema("SPY", 30, Resolution.DAILY)
-
- self.previous = None
-
-
- def on_data(self, data):
- '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.'''
- # a couple things to notice in this method:
- # 1. We never need to 'update' our indicators with the data, the engine takes care of this for us
- # 2. We can use indicators directly in math expressions
- # 3. We can easily plot many indicators at the same time
-
- # wait for our slow ema to fully initialize
- if not self.slow.is_ready:
- return
-
- # only once per day
- if self.previous is not None and self.previous.date() == self.time.date():
- return
-
- # define a small tolerance on our checks to avoid bouncing
- tolerance = 0.00015
-
- holdings = self.portfolio["SPY"].quantity
-
- # we only want to go long if we're currently short or flat
- if holdings <= 0:
- # if the fast is greater than the slow, we'll go long
- if self.fast.current.value > self.slow.current.value *(1 + tolerance):
- self.log("BUY >> {0}".format(self.securities["SPY"].price))
- self.set_holdings("SPY", 1.0)
-
- # we only want to liquidate if we're currently long
- # if the fast is less than the slow we'll liquidate our long
- if holdings > 0 and self.fast.current.value < self.slow.current.value:
- self.log("SELL >> {0}".format(self.securities["SPY"].price))
- self.liquidate("SPY")
-
- self.previous = self.time
diff --git a/fincept-qt/scripts/strategies/MultipleSymbolConsolidationAlgorithm.py b/fincept-qt/scripts/strategies/MultipleSymbolConsolidationAlgorithm.py
deleted file mode 100644
index 8c98f56d6..000000000
--- a/fincept-qt/scripts/strategies/MultipleSymbolConsolidationAlgorithm.py
+++ /dev/null
@@ -1,114 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-CFDE4C40
-# Category: Data Consolidation
-# Description: Example structure for structuring an algorithm with indicator and consolidator data for many tickers
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Example structure for structuring an algorithm with indicator and consolidator data for many tickers.
-### </summary>
-### <meta name="tag" content="consolidating data" />
-### <meta name="tag" content="indicators" />
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="strategy example" />
-class MultipleSymbolConsolidationAlgorithm(QCAlgorithm):
-
- # Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
- def initialize(self):
-
- # This is the period of bars we'll be creating
- bar_period = TimeSpan.from_minutes(10)
- # This is the period of our sma indicators
- sma_period = 10
- # This is the number of consolidated bars we'll hold in symbol data for reference
- rolling_window_size = 10
- # Holds all of our data keyed by each symbol
- self.data = {}
- # Contains all of our equity symbols
- equity_symbols = ["AAPL","SPY","IBM"]
- # Contains all of our forex symbols
- forex_symbols = ["EURUSD", "USDJPY", "EURGBP", "EURCHF", "USDCAD", "USDCHF", "AUDUSD","NZDUSD"]
-
- self.set_start_date(2014, 12, 1)
- self.set_end_date(2015, 2, 1)
-
- # initialize our equity data
- for symbol in equity_symbols:
- equity = self.add_equity(symbol)
- self.data[symbol] = SymbolData(equity.symbol, bar_period, rolling_window_size)
-
- # initialize our forex data
- for symbol in forex_symbols:
- forex = self.add_forex(symbol)
- self.data[symbol] = SymbolData(forex.symbol, bar_period, rolling_window_size)
-
- # loop through all our symbols and request data subscriptions and initialize indicator
- for symbol, symbol_data in self.data.items():
- # define the indicator
- symbol_data.sma = SimpleMovingAverage(self.create_indicator_name(symbol, "sma" + str(sma_period), Resolution.MINUTE), sma_period)
- # define a consolidator to consolidate data for this symbol on the requested period
- consolidator = TradeBarConsolidator(bar_period) if symbol_data.symbol.security_type == SecurityType.EQUITY else QuoteBarConsolidator(bar_period)
- # write up our consolidator to update the indicator
- consolidator.data_consolidated += self.on_data_consolidated
- # we need to add this consolidator so it gets auto updates
- self.subscription_manager.add_consolidator(symbol_data.symbol, consolidator)
-
- def on_data_consolidated(self, sender, bar):
-
- self.data[bar.symbol.value].sma.update(bar.time, bar.close)
- self.data[bar.symbol.value].bars.add(bar)
-
- # OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
- # Argument "data": Slice object, dictionary object with your stock data
- def on_data(self,data):
-
- # loop through each symbol in our structure
- for symbol in self.data.keys():
- symbol_data = self.data[symbol]
- # this check proves that this symbol was JUST updated prior to this OnData function being called
- if symbol_data.is_ready() and symbol_data.was_just_updated(self.time):
- if not self.portfolio[symbol].invested:
- self.market_order(symbol, 1)
-
- # End of a trading day event handler. This method is called at the end of the algorithm day (or multiple times if trading multiple assets).
- # Method is called 10 minutes before closing to allow user to close out position.
- def on_end_of_day(self, symbol):
-
- i = 0
- for symbol in sorted(self.data.keys()):
- symbol_data = self.data[symbol]
- # we have too many symbols to plot them all, so plot every other
- i += 1
- if symbol_data.is_ready() and i%2 == 0:
- self.plot(symbol, symbol, symbol_data.sma.current.value)
-
-
-class SymbolData(object):
-
- def __init__(self, symbol, bar_period, window_size):
- self._symbol = symbol
- self.symbol = symbol
- # The period used when population the Bars rolling window
- self.bar_period = bar_period
- # A rolling window of data, data needs to be pumped into Bars by using Bars.update( trade_bar ) and can be accessed like:
- # my_symbol_data.bars[0] - most first recent piece of data
- # my_symbol_data.bars[5] - the sixth most recent piece of data (zero based indexing)
- self.bars = RollingWindow[IBaseDataBar](window_size)
- # The simple moving average indicator for our symbol
- self.sma = None
-
- # Returns true if all the data in this instance is ready (indicators, rolling windows, ect...)
- def is_ready(self):
- return self.bars.is_ready and self.sma.is_ready
-
- # Returns true if the most recent trade bar time matches the current time minus the bar's period, this
- # indicates that update was just called on this instance
- def was_just_updated(self, current):
- return self.bars.count > 0 and self.bars[0].time == current - self.bar_period
diff --git a/fincept-qt/scripts/strategies/NLTKSentimentTradingAlgorithm.py b/fincept-qt/scripts/strategies/NLTKSentimentTradingAlgorithm.py
deleted file mode 100644
index ce4bfff1a..000000000
--- a/fincept-qt/scripts/strategies/NLTKSentimentTradingAlgorithm.py
+++ /dev/null
@@ -1,61 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-D2180B48
-# Category: General Strategy
-# Description: N L T K Sentiment Trading Algorithm
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-import nltk
-# for details of NLTK, please visit https://www.nltk.org/index.html
-
-class NLTKSentimentTradingAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2018, 1, 1) # Set Start Date
- self.set_end_date(2019, 1, 1) # Set End Date
- self.set_cash(100000) # Set Strategy Cash
-
- spy = self.add_equity("SPY", Resolution.MINUTE)
- self.text = self.get_text() # Get custom text data for creating trading signals
- self._symbols = [spy.symbol] # This can be extended to multiple symbols
-
- # for what extra models needed to download, please use code nltk.download()
- nltk.download('punkt')
- self.schedule.on(self.date_rules.every_day("SPY"), self.time_rules.after_market_open("SPY", 30), self.trade)
-
- def trade(self):
- current_time = f'{self.time.year}-{self.time.month}-{self.time.day}'
- current_text = self.text.loc[current_time][0]
- words = nltk.word_tokenize(current_text)
-
- # users should decide their own positive and negative words
- positive_word = 'Up'
- negative_word = 'Down'
-
- for holding in self.portfolio.values:
- # liquidate if it contains negative words
- if negative_word in words and holding.invested:
- self.liquidate(holding.symbol)
-
- # buy if it contains positive words
- if positive_word in words and not holding.invested:
- self.set_holdings(holding.symbol, 1 / len(self._symbols))
-
- def get_text(self):
- # import custom data
- # Note: dl must be 1, or it will not download automatically
- url = 'https://www.dropbox.com/s/7xgvkypg6uxp6xl/EconomicNews.csv?dl=1'
- data = self.download(url).split('\n')
-
- headline = [x.split(',')[1] for x in data][1:]
- date = [x.split(',')[0] for x in data][1:]
-
- # create a pd dataframe with 1st col being date and 2nd col being headline (content of the text)
- df = pd.DataFrame(headline, index = date, columns = ['headline'])
- return df
diff --git a/fincept-qt/scripts/strategies/NakedCallStrategyAlgorithm.py b/fincept-qt/scripts/strategies/NakedCallStrategyAlgorithm.py
deleted file mode 100644
index 2ed7aaaed..000000000
--- a/fincept-qt/scripts/strategies/NakedCallStrategyAlgorithm.py
+++ /dev/null
@@ -1,51 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-AE6C825A
-# Category: General Strategy
-# Description: This algorithm demonstrate how to use OptionStrategies helper class to batch send orders for common strategies. In th...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-from OptionStrategyFactoryMethodsBaseAlgorithm import *
-
-### <summary>
-### This algorithm demonstrate how to use OptionStrategies helper class to batch send orders for common strategies.
-### In this case, the algorithm tests the Naked Call strategy.
-### </summary>
-class NakedCallStrategyAlgorithm(OptionStrategyFactoryMethodsBaseAlgorithm):
-
- def expected_orders_count(self) -> int:
- return 2
-
- def trade_strategy(self, chain: OptionChain, option_symbol: Symbol):
- contracts = sorted(sorted(chain, key = lambda x: abs(chain.underlying.price - x.strike)),
- key = lambda x: x.expiry, reverse=True)
-
- if len(contracts) == 0: return
- contract = contracts[0]
- if contract != None:
- self._naked_call = OptionStrategies.naked_call(option_symbol, contract.strike, contract.expiry)
- self.buy(self._naked_call, 2)
-
- def assert_strategy_position_group(self, position_group: IPositionGroup, option_symbol: Symbol):
- positions = list(position_group.positions)
- if len(positions) != 1:
- raise Exception(f"Expected position group to have 1 positions. Actual: {len(positions)}")
-
- option_position = [position for position in positions if position.symbol.security_type == SecurityType.OPTION][0]
- if option_position.symbol.id.option_right != OptionRight.CALL:
- raise Exception(f"Expected option position to be a call. Actual: {option_position.symbol.id.option_right}")
-
- expected_option_position_quantity = -2
-
- if option_position.quantity != expected_option_position_quantity:
- raise Exception(f"Expected option position quantity to be {expected_option_position_quantity}. Actual: {option_position.quantity}")
-
- def liquidate_strategy(self):
- # We can liquidate by selling the strategy
- self.sell(self._naked_call, 2)
diff --git a/fincept-qt/scripts/strategies/NakedPutStrategyAlgorithm.py b/fincept-qt/scripts/strategies/NakedPutStrategyAlgorithm.py
deleted file mode 100644
index 4e8f69f64..000000000
--- a/fincept-qt/scripts/strategies/NakedPutStrategyAlgorithm.py
+++ /dev/null
@@ -1,51 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-82AD115E
-# Category: General Strategy
-# Description: This algorithm demonstrate how to use OptionStrategies helper class to batch send orders for common strategies. In th...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-from OptionStrategyFactoryMethodsBaseAlgorithm import *
-
-### <summary>
-### This algorithm demonstrate how to use OptionStrategies helper class to batch send orders for common strategies.
-### In this case, the algorithm tests the Naked Put strategy.
-### </summary>
-class NakedPutStrategyAlgorithm(OptionStrategyFactoryMethodsBaseAlgorithm):
-
- def expected_orders_count(self) -> int:
- return 2
-
- def trade_strategy(self, chain: OptionChain, option_symbol: Symbol):
- contracts = sorted(sorted(chain, key = lambda x: abs(chain.underlying.price - x.strike)),
- key = lambda x: x.expiry, reverse=True)
-
- if len(contracts) == 0: return
- contract = contracts[0]
- if contract != None:
- self._naked_put = OptionStrategies.naked_put(option_symbol, contract.strike, contract.expiry)
- self.buy(self._naked_put, 2)
-
- def assert_strategy_position_group(self, position_group: IPositionGroup, option_symbol: Symbol):
- positions = list(position_group.positions)
- if len(positions) != 1:
- raise Exception(f"Expected position group to have 1 positions. Actual: {len(positions)}")
-
- option_position = [position for position in positions if position.symbol.security_type == SecurityType.OPTION][0]
- if option_position.symbol.id.option_right != OptionRight.PUT:
- raise Exception(f"Expected option position to be a put. Actual: {option_position.symbol.id.option_right}")
-
- expected_option_position_quantity = -2
-
- if option_position.quantity != expected_option_position_quantity:
- raise Exception(f"Expected option position quantity to be {expected_option_position_quantity}. Actual: {option_position.quantity}")
-
- def liquidate_strategy(self):
- # Now we can liquidate by selling the strategy
- self.sell(self._naked_put, 2)
diff --git a/fincept-qt/scripts/strategies/NamedArgumentsRegression.py b/fincept-qt/scripts/strategies/NamedArgumentsRegression.py
deleted file mode 100644
index d978645ac..000000000
--- a/fincept-qt/scripts/strategies/NamedArgumentsRegression.py
+++ /dev/null
@@ -1,57 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-94DBB773
-# Category: Regression Test
-# Description: Demonstration of requesting daily resolution data for US Equities. This is a simple regression test algorithm using a...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Demonstration of requesting daily resolution data for US Equities.
-### This is a simple regression test algorithm using a skeleton algorithm and requesting daily data.
-### </summary>
-### <meta name="tag" content="using data" />
-class NamedArgumentsRegression(QCAlgorithm):
- '''Regression algorithm that makes use of PythonNet kwargs'''
-
- def initialize(self):
- '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
-
- #Use named args for setting up our algorithm
- self.set_start_date(month=10,day=8,year=2013) #Set Start Date
- self.set_end_date(month=10,day=17,year=2013) #Set End Date
- self.set_cash(starting_cash=100000) #Set Strategy Cash
-
- #Check our values
- if self.start_date.year != 2013 or self.start_date.month != 10 or self.start_date.day != 8:
- raise AssertionError(f"Start date was incorrect! Expected 10/8/2013 Recieved {self.start_date}")
-
- if self.end_date.year != 2013 or self.end_date.month != 10 or self.end_date.day != 17:
- raise AssertionError(f"End date was incorrect! Expected 10/17/2013 Recieved {self.end_date}")
-
- if self.portfolio.cash != 100000:
- raise AssertionError(f"Portfolio cash was incorrect! Expected 100000 Recieved {self.portfolio.cash}")
-
- # Use named args for addition of this security to our algorithm
- symbol = self.add_equity(resolution=Resolution.DAILY, ticker="SPY").symbol
-
- # Check our subscriptions for the symbol and check its resolution
- for config in self.subscription_manager.subscription_data_config_service.get_subscription_data_configs(symbol):
- if config.resolution != Resolution.DAILY:
- raise AssertionError(f"Resolution was not correct on security")
-
-
- def on_data(self, data):
- '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
-
- Arguments:
- data: Slice object keyed by symbol containing the stock data
- '''
- if not self.portfolio.invested:
- self.set_holdings(symbol="SPY", percentage=1)
- self.debug(message="Purchased Stock")
diff --git a/fincept-qt/scripts/strategies/NoUniverseSelectorRegressionAlgorithm.py b/fincept-qt/scripts/strategies/NoUniverseSelectorRegressionAlgorithm.py
deleted file mode 100644
index 41b065ea7..000000000
--- a/fincept-qt/scripts/strategies/NoUniverseSelectorRegressionAlgorithm.py
+++ /dev/null
@@ -1,44 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-994B4750
-# Category: Universe Selection
-# Description: Custom data universe selection regression algorithm asserting it's behavior. See GH issue #6396
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Custom data universe selection regression algorithm asserting it's behavior. See GH issue #6396
-### </summary>
-class NoUniverseSelectorRegressionAlgorithm(QCAlgorithm):
- def initialize(self):
- '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
- self.set_start_date(2014, 3, 24)
- self.set_end_date(2014, 3, 31)
-
- self.universe_settings.resolution = Resolution.DAILY;
- self.add_universe(CoarseFundamental)
- self.changes = None
-
- def on_data(self, data):
- # if we have no changes, do nothing
- if not self.changes: return
-
- # liquidate removed securities
- for security in self.changes.removed_securities:
- if security.invested:
- self.liquidate(security.symbol)
-
- active_and_with_data_securities = sum(x.value.has_data for x in self.active_securities)
- # we want 1/N allocation in each security in our universe
- for security in self.changes.added_securities:
- if security.has_data:
- self.set_holdings(security.symbol, 1 / active_and_with_data_securities)
- self.changes = None
-
- def on_securities_changed(self, changes):
- self.changes = changes
diff --git a/fincept-qt/scripts/strategies/NullBuyingPowerOptionBullCallSpreadAlgorithm.py b/fincept-qt/scripts/strategies/NullBuyingPowerOptionBullCallSpreadAlgorithm.py
deleted file mode 100644
index 2a8184e31..000000000
--- a/fincept-qt/scripts/strategies/NullBuyingPowerOptionBullCallSpreadAlgorithm.py
+++ /dev/null
@@ -1,66 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-7F8D7895
-# Category: Options
-# Description: Shows how setting to use the SecurityMarginModel.null (or BuyingPowerModel.NULL) to disable the sufficient margin cal...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Shows how setting to use the SecurityMarginModel.null (or BuyingPowerModel.NULL)
-### to disable the sufficient margin call verification.
-### See also: <see cref="OptionEquityBullCallSpreadRegressionAlgorithm"/>
-### </summary>
-### <meta name="tag" content="reality model" />
-class NullBuyingPowerOptionBullCallSpreadAlgorithm(QCAlgorithm):
- def initialize(self):
-
- self.set_start_date(2015, 12, 24)
- self.set_end_date(2015, 12, 24)
- self.set_cash(200000)
-
- self.set_security_initializer(lambda security: security.set_margin_model(SecurityMarginModel.NULL))
- self.portfolio.set_positions(SecurityPositionGroupModel.NULL);
-
- equity = self.add_equity("GOOG")
- option = self.add_option(equity.symbol)
- self.option_symbol = option.symbol
-
- option.set_filter(-2, 2, 0, 180)
-
- def on_data(self, slice):
- if self.portfolio.invested or not self.is_market_open(self.option_symbol):
- return
-
- chain = slice.option_chains.get(self.option_symbol)
- if chain:
- call_contracts = [x for x in chain if x.right == OptionRight.CALL]
-
- expiry = min(x.expiry for x in call_contracts)
-
- call_contracts = sorted([x for x in call_contracts if x.expiry == expiry],
- key = lambda x: x.strike)
-
- long_call = call_contracts[0]
- short_call = [x for x in call_contracts if x.strike > long_call.strike][0]
-
- quantity = 1000
-
- tickets = [
- self.market_order(short_call.symbol, -quantity),
- self.market_order(long_call.symbol, quantity)
- ]
-
- for ticket in tickets:
- if ticket.status != OrderStatus.FILLED:
- raise Exception(f"There should be no restriction on buying {ticket.quantity} of {ticket.symbol} with BuyingPowerModel.NULL")
-
-
- def on_end_of_algorithm(self) -> None:
- if self.portfolio.total_margin_used != 0:
- raise Exception("The TotalMarginUsed should be zero to avoid margin calls.")
diff --git a/fincept-qt/scripts/strategies/NullMarginMultipleOrdersRegressionAlgorithm.py b/fincept-qt/scripts/strategies/NullMarginMultipleOrdersRegressionAlgorithm.py
deleted file mode 100644
index 8431fdfc4..000000000
--- a/fincept-qt/scripts/strategies/NullMarginMultipleOrdersRegressionAlgorithm.py
+++ /dev/null
@@ -1,48 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-B9E54A12
-# Category: Regression Test
-# Description: Regression algorithm asserting the behavior of specifying a null position group allowing us to fill orders which woul...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Regression algorithm asserting the behavior of specifying a null position group allowing us to fill orders which would be invalid if not
-### </summary>
-class NullMarginMultipleOrdersRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2015, 12, 24)
- self.set_end_date(2015, 12, 24)
- self.set_cash(10000)
-
- # override security position group model
- self.portfolio.set_positions(SecurityPositionGroupModel.NULL)
- # override margin requirements
- self.set_security_initializer(lambda security: security.set_buying_power_model(ConstantBuyingPowerModel(1)))
-
- equity = self.add_equity("GOOG", leverage=4, fill_forward=True)
- option = self.add_option(equity.symbol, fill_forward=True)
- self._option_symbol = option.symbol
-
- option.set_filter(lambda u: u.strikes(-2, +2).expiration(0, 180))
-
- def on_data(self, data: Slice):
- if not self.portfolio.invested:
- if self.is_market_open(self._option_symbol):
- chain = data.option_chains.get_value(self._option_symbol)
- if chain is not None:
- call_contracts = [contract for contract in chain if contract.right == OptionRight.CALL]
- call_contracts.sort(key=lambda x: (x.expiry, 1/ x.strike), reverse=True)
-
- option_contract = call_contracts[0]
- self.market_order(option_contract.symbol.underlying, 1000)
- self.market_order(option_contract.symbol, -10)
-
- if self.portfolio.total_margin_used != 1010:
- raise ValueError(f"Unexpected margin used {self.portfolio.total_margin_used}")
diff --git a/fincept-qt/scripts/strategies/NullOptionAssignmentRegressionAlgorithm.py b/fincept-qt/scripts/strategies/NullOptionAssignmentRegressionAlgorithm.py
deleted file mode 100644
index b99fd6ece..000000000
--- a/fincept-qt/scripts/strategies/NullOptionAssignmentRegressionAlgorithm.py
+++ /dev/null
@@ -1,53 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-16C48497
-# Category: Options
-# Description: Volatility-adjusted position sizing strategy. Buys when ATR is
-# below its 20-day average (low volatility) with full position. Reduces to
-# half position when ATR rises above average. Exits on SMA crossdown.
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-class NullOptionAssignmentRegressionAlgorithm(QCAlgorithm):
- """Volatility-adjusted position sizing with SMA trend filter."""
-
- def initialize(self):
- self.set_start_date(2023, 1, 1)
- self.set_end_date(2024, 1, 1)
- self.set_cash(100000)
-
- self.symbol = "SPY"
- self.add_equity(self.symbol, Resolution.DAILY)
-
- self._sma = self.sma(self.symbol, 20, Resolution.DAILY)
- self._atr = self.atr(self.symbol, 14, Resolution.DAILY)
- self._atr_sma_values = []
-
- def on_data(self, data):
- if not self._sma.is_ready or not self._atr.is_ready:
- return
- if self.symbol not in data:
- return
-
- price = data[self.symbol].close
- sma_val = self._sma.current.value
- atr_val = self._atr.current.value
-
- # Track ATR average
- self._atr_sma_values.append(atr_val)
- if len(self._atr_sma_values) > 20:
- self._atr_sma_values = self._atr_sma_values[-20:]
- avg_atr = sum(self._atr_sma_values) / len(self._atr_sma_values)
-
- if price > sma_val:
- target = 1.0 if atr_val < avg_atr else 0.5
- if not self.portfolio.invested:
- self.set_holdings(self.symbol, target)
- else:
- if self.portfolio.invested:
- self.liquidate()
diff --git a/fincept-qt/scripts/strategies/NumeraiSignalExportDemonstrationAlgorithm.py b/fincept-qt/scripts/strategies/NumeraiSignalExportDemonstrationAlgorithm.py
deleted file mode 100644
index 97a0185f0..000000000
--- a/fincept-qt/scripts/strategies/NumeraiSignalExportDemonstrationAlgorithm.py
+++ /dev/null
@@ -1,88 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-F5080AAC
-# Category: General Strategy
-# Description: This algorithm sends a list of current portfolio targets to Numerai API before each trading day See (https://docs.num...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### This algorithm sends a list of current portfolio targets to Numerai API before each trading day
-### See (https://docs.numer.ai/numerai-signals/signals-overview) for more information
-### about accepted symbols, signals, etc.
-### </summary>
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="using quantconnect" />
-### <meta name="tag" content="securities and portfolio" />
-class NumeraiSignalExportDemonstrationAlgorithm(QCAlgorithm):
-
- securities = []
-
- def initialize(self):
- ''' Initialize the date and add all equity symbols present in list _symbols '''
-
- self.set_start_date(2020, 10, 7) #Set Start Date
- self.set_end_date(2020, 10, 12) #Set End Date
- self.set_cash(100000) #Set Strategy Cash
-
- self.set_security_initializer(BrokerageModelSecurityInitializer(self.brokerage_model, FuncSecuritySeeder(self.get_last_known_prices)))
-
- # Add the CRSP US Total Market Index constituents, which represents approximately 100% of the investable US Equity market
- self.etf_symbol = self.add_equity("VTI").symbol
- self.add_universe(self.universe.etf(self.etf_symbol))
-
- # Create a Scheduled Event to submit signals every trading day at 13:00 UTC
- self.schedule.on(self.date_rules.every_day(self.etf_symbol), self.time_rules.at(13, 0, TimeZones.UTC), self.submit_signals)
-
- # Set Numerai signal export provider
- # Numerai Public ID: This value is provided by Numerai Signals in their main webpage once you've logged in
- # and created a API key. See (https://signals.numer.ai/account)
- numerai_public_id = ""
-
- # Numerai Secret ID: This value is provided by Numerai Signals in their main webpage once you've logged in
- # and created a API key. See (https://signals.numer.ai/account)
- numerai_secret_id = ""
-
- # Numerai Model ID: This value is provided by Numerai Signals in their main webpage once you've logged in
- # and created a model. See (https://signals.numer.ai/models)
- numerai_model_id = ""
-
- numerai_filename = "" # (Optional) Replace this value with your submission filename
- self.signal_export.add_signal_export_providers(NumeraiSignalExport(numerai_public_id, numerai_secret_id, numerai_model_id, numerai_filename))
-
-
- def submit_signals(self):
- # Select the subset of ETF constituents we can trade
- symbols = sorted([security.symbol for security in self.securities if security.has_data])
- if len(symbols) == 0:
- return
-
- # Get historical data
- # close_prices = self.history(symbols, 22, Resolution.DAILY).close.unstack(0)
-
- # Create portfolio targets
- # Numerai requires that at least one of the signals have a unique weight
- # To ensure they are all unique, this demo gives a linear allocation to each symbol (ie. 1/55, 2/55, ..., 10/55)
- denominator = len(symbols) * (len(symbols) + 1) / 2 # sum of 1, 2, ..., len(symbols)
- targets = [PortfolioTarget(symbol, (i+1) / denominator) for i, symbol in enumerate(symbols)]
-
- # (Optional) Place trades
- self.set_holdings(targets)
-
- # Send signals to Numerai
- success = self.signal_export.set_target_portfolio(targets)
- if not success:
- self.debug(f"Couldn't send targets at {self.time}")
-
-
- def on_securities_changed(self, changes: SecurityChanges) -> None:
- for security in changes.removed_securities:
- if security in self.securities:
- self.securities.remove(security)
-
- self.securities.extend([security for security in changes.added_securities if security.symbol != self.etf_symbol])
diff --git a/fincept-qt/scripts/strategies/ObjectStoreExampleAlgorithm.py b/fincept-qt/scripts/strategies/ObjectStoreExampleAlgorithm.py
deleted file mode 100644
index ad7aecf38..000000000
--- a/fincept-qt/scripts/strategies/ObjectStoreExampleAlgorithm.py
+++ /dev/null
@@ -1,90 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-6A2A6B6A
-# Category: General Strategy
-# Description: This algorithm showcases some features of the IObjectStore feature.
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-from io import StringIO
-
-class ObjectStoreExampleAlgorithm(QCAlgorithm):
- '''This algorithm showcases some features of the IObjectStore feature.
- One use case is to make consecutive backtests run faster by caching the results of
- potentially time consuming operations. In this example, we save the results of a
- history call. This pattern can be equally applied to a machine learning model being
- trained and then saving the model weights in the object store.
- '''
- spy_close_object_store_key = "spy_close"
- spy_close_history = RollingWindow[IndicatorDataPoint](252)
- spy_close_ema10_history = RollingWindow[IndicatorDataPoint](252)
- spy_close_ema50_history = RollingWindow[IndicatorDataPoint](252)
-
- def initialize(self):
- self.set_start_date(2013, 10, 7)
- self.set_end_date(2013, 10, 11)
-
- self.SPY = self.add_equity("SPY", Resolution.MINUTE).symbol
-
- self.spy_close = self.identity(self.SPY, Resolution.DAILY)
- self.spy_close_ema10 = IndicatorExtensions.ema(self.spy_close, 10)
- self.spy_close_ema50 = IndicatorExtensions.ema(self.spy_close, 50)
-
- # track last year of close and EMA10/EMA50
- self.spy_close.updated += lambda _, args: self.spy_close_history.add(args)
- self.spy_close_ema10.updated += lambda _, args: self.spy_close_ema10_history.add(args)
- self.spy_close_ema50.updated += lambda _, args: self.spy_close_ema50_history.add(args)
-
- if self.object_store.contains_key(self.spy_close_object_store_key):
- # our object store has our historical data saved, read the data
- # and push it through the indicators to warm everything up
- values = self.object_store.read(self.spy_close_object_store_key)
- self.debug(f'{self.spy_close_object_store_key} key exists in object store.')
-
- history = pd.read_csv(StringIO(values), header=None, index_col=0, squeeze=True)
- history.index = pd.to_datetime(history.index)
- for time, close in history.items():
- self.spy_close.update(time, close)
-
- else:
- self.debug(f'{self.spy_close_object_store_key} key does not exist in object store. Fetching history...')
-
- # if our object store doesn't have our data, fetch the history to initialize
- # we're pulling the last year's worth of SPY daily trade bars to fee into our indicators
- history = self.history(self.SPY, timedelta(365), Resolution.DAILY).close.unstack(0).squeeze()
-
- for time, close in history.items():
- self.spy_close.update(time, close)
-
- # save our warm up data so next time we don't need to issue the history request
- self.object_store.save(self.spy_close_object_store_key,
- '\n'.join(reversed([f'{x.end_time},{x.value}' for x in self.spy_close_history])))
-
- # Can also use ObjectStore.save_bytes(key, byte[])
- # and to read ObjectStore.read_bytes(key) => byte[]
-
- # we can also get a file path for our data. some ML libraries require model
- # weights to be loaded directly from a file path. The object store can provide
- # a file path for any key by: ObjectStore.get_file_path(key) => string (file path)
-
- def on_data(self, slice):
-
- close = self.spy_close
- ema10 = self.spy_close_ema10
- ema50 = self.spy_close_ema50
-
- if ema10 > close and ema10 > ema50:
- self.set_holdings(self.SPY, 1)
-
- elif ema10 < close and ema10 < ema50:
- self.set_holdings(self.SPY, -1)
-
- elif ema10 < ema50 and self.portfolio[self.SPY].is_long:
- self.liquidate(self.SPY)
-
- elif ema10 > ema50 and self.portfolio[self.SPY].is_short:
- self.liquidate(self.SPY)
diff --git a/fincept-qt/scripts/strategies/OnEndOfDayRegressionAlgorithm.py b/fincept-qt/scripts/strategies/OnEndOfDayRegressionAlgorithm.py
deleted file mode 100644
index b4a478ba0..000000000
--- a/fincept-qt/scripts/strategies/OnEndOfDayRegressionAlgorithm.py
+++ /dev/null
@@ -1,67 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-5B1C96E9
-# Category: Regression Test
-# Description: Test algorithm verifying OnEndOfDay callbacks are called as expected. See GH issue 2865.
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-class OnEndOfDayRegressionAlgorithm(QCAlgorithm):
- '''Test algorithm verifying OnEndOfDay callbacks are called as expected. See GH issue 2865.'''
- def initialize(self):
- '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
-
- self.set_start_date(2013,10, 7)
- self.set_end_date(2013,10,11)
- self.set_cash(100000)
-
- self._spy_symbol = Symbol.create("SPY", SecurityType.EQUITY, Market.USA)
- self._bac_symbol = Symbol.create("BAC", SecurityType.EQUITY, Market.USA)
- self._ibm_symbol = Symbol.create("IBM", SecurityType.EQUITY, Market.USA)
- self._on_end_of_day_spy_call_count = 0
- self._on_end_of_day_bac_call_count = 0
- self._on_end_of_day_ibm_call_count = 0
-
- self.add_universe('my_universe_name', self.selection)
-
- def selection(self, time):
- if time.day == 8:
- return [self._spy_symbol.value, self._ibm_symbol.value]
- return [self._spy_symbol.value]
-
- def on_end_of_day(self, symbol):
- '''We expect it to be called on each day after the first selection process
- happens and the algorithm has a security in it
- '''
- if symbol == self._spy_symbol:
- if self._on_end_of_day_spy_call_count == 0:
- # just the first time
- self.set_holdings(self._spy_symbol, 0.5)
- self.add_equity("BAC")
- self._on_end_of_day_spy_call_count += 1
- if symbol == self._bac_symbol:
- if self._on_end_of_day_bac_call_count == 0:
- # just the first time
- self.set_holdings(self._bac_symbol, 0.5)
- self._on_end_of_day_bac_call_count += 1
- if symbol == self._ibm_symbol:
- self._on_end_of_day_ibm_call_count += 1
-
- self.log("OnEndOfDay() called: " + str(self.utc_time)
- + ". SPY count " + str(self._on_end_of_day_spy_call_count)
- + ". BAC count " + str(self._on_end_of_day_bac_call_count)
- + ". IBM count " + str(self._on_end_of_day_ibm_call_count))
-
- def on_end_of_algorithm(self):
- '''Assert expected behavior'''
- if self._on_end_of_day_spy_call_count != 5:
- raise ValueError("OnEndOfDay(SPY) unexpected count call " + str(self._on_end_of_day_spy_call_count))
- if self._on_end_of_day_bac_call_count != 4:
- raise ValueError("OnEndOfDay(BAC) unexpected count call " + str(self._on_end_of_day_bac_call_count))
- if self._on_end_of_day_ibm_call_count != 1:
- raise ValueError("OnEndOfDay(IBM) unexpected count call " + str(self._on_end_of_day_ibm_call_count))
diff --git a/fincept-qt/scripts/strategies/OnWarmupFinishedNoWarmup.py b/fincept-qt/scripts/strategies/OnWarmupFinishedNoWarmup.py
deleted file mode 100644
index 55b502904..000000000
--- a/fincept-qt/scripts/strategies/OnWarmupFinishedNoWarmup.py
+++ /dev/null
@@ -1,31 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-7E0FD2EB
-# Category: Warmup
-# Description: Regression algorithm asserting "OnWarmupFinished" is called even if no warmup period is set
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Regression algorithm asserting "OnWarmupFinished" is called even if no warmup period is set
-### </summary>
-class OnWarmupFinishedNoWarmup(QCAlgorithm):
- def initialize(self):
- '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
-
- self.set_start_date(2013,10, 7)
- self.set_end_date(2013,10,11)
- self.add_equity("SPY", Resolution.MINUTE)
- self._on_warmup_finished = 0
-
- def on_warmup_finished(self):
- self._on_warmup_finished += 1
-
- def on_end_of_algorithm(self):
- if self._on_warmup_finished != 1:
- raise Exception(f"Unexpected OnWarmupFinished call count {self._on_warmup_finished}")
diff --git a/fincept-qt/scripts/strategies/OnWarmupFinishedRegressionAlgorithm.py b/fincept-qt/scripts/strategies/OnWarmupFinishedRegressionAlgorithm.py
deleted file mode 100644
index 0c3282ed4..000000000
--- a/fincept-qt/scripts/strategies/OnWarmupFinishedRegressionAlgorithm.py
+++ /dev/null
@@ -1,34 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-BA4498F3
-# Category: Regression Test
-# Description: Regression algorithm asserting 'OnWarmupFinished' is being called
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Regression algorithm asserting 'OnWarmupFinished' is being called
-### </summary>
-class OnWarmupFinishedRegressionAlgorithm(QCAlgorithm):
- def initialize(self):
- '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
-
- self.set_start_date(2013,10, 8) #Set Start Date
- self.set_end_date(2013,10,11) #Set End Date
- self.set_cash(100000) #Set Strategy Cash
-
- self.add_equity("SPY", Resolution.MINUTE)
- self.set_warmup(timedelta(days = 1))
- self._on_warmup_finished = 0
-
- def on_warmup_finished(self):
- self._on_warmup_finished += 1
-
- def on_end_of_algorithm(self):
- if self._on_warmup_finished != 1:
- raise Exception(f"Unexpected OnWarmupFinished call count {self._on_warmup_finished}")
diff --git a/fincept-qt/scripts/strategies/OpenInterestFuturesRegressionAlgorithm.py b/fincept-qt/scripts/strategies/OpenInterestFuturesRegressionAlgorithm.py
deleted file mode 100644
index fd7aec966..000000000
--- a/fincept-qt/scripts/strategies/OpenInterestFuturesRegressionAlgorithm.py
+++ /dev/null
@@ -1,44 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-370B9F0E
-# Category: Futures
-# Description: Futures framework algorithm that uses open interest to select the active contract
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Futures framework algorithm that uses open interest to select the active contract.
-### </summary>
-### <meta name="tag" content="regression test" />
-### <meta name="tag" content="futures" />
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="filter selection" />
-class OpenInterestFuturesRegressionAlgorithm(QCAlgorithm):
-
- expected_expiry_dates = {datetime(2013, 12, 27), datetime(2014,2,26)}
-
- def initialize(self):
- self.universe_settings.resolution = Resolution.TICK
- self.set_start_date(2013,10,8)
- self.set_end_date(2013,10,11)
- self.set_cash(10000000)
-
- # set framework models
- universe = OpenInterestFutureUniverseSelectionModel(self, lambda date_time: [Symbol.create(Futures.Metals.GOLD, SecurityType.FUTURE, Market.COMEX)], None, len(self.expected_expiry_dates))
- self.set_universe_selection(universe)
-
- def on_data(self,data):
- if self.transactions.orders_count == 0 and data.has_data:
- matched = list(filter(lambda s: not (s.id.date in self.expected_expiry_dates) and not s.is_canonical(), data.keys()))
- if len(matched) != 0:
- raise Exception(f"{len(matched)}/{len(slice.keys)} were unexpected expiry date(s): " + ", ".join(list(map(lambda x: x.id.date, matched))))
-
- for symbol in data.keys():
- self.market_order(symbol, 1)
- elif any(p.value.invested for p in self.portfolio):
- self.liquidate()
diff --git a/fincept-qt/scripts/strategies/OptionChainApisConsistencyRegressionAlgorithm.py b/fincept-qt/scripts/strategies/OptionChainApisConsistencyRegressionAlgorithm.py
deleted file mode 100644
index b19aea54d..000000000
--- a/fincept-qt/scripts/strategies/OptionChainApisConsistencyRegressionAlgorithm.py
+++ /dev/null
@@ -1,55 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-A5BE1849
-# Category: Options
-# Description: Regression algorithm asserting that the option chain APIs return consistent values. See QCAlgorithm.OptionChain(Symbo...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from datetime import datetime
-from AlgorithmImports import *
-
-### <summary>
-### Regression algorithm asserting that the option chain APIs return consistent values.
-### See QCAlgorithm.OptionChain(Symbol) and QCAlgorithm.OptionChainProvider
-### </summary>
-class OptionChainApisConsistencyRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self) -> None:
- test_date = self.get_test_date()
-
- self.set_start_date(test_date)
- self.set_end_date(test_date)
-
- option = self.get_option()
-
- option_chain_from_algorithm_api = [x.symbol for x in self.option_chain(option.symbol).contracts.values()]
-
- exchange_time = Extensions.convert_from_utc(self.utc_time, option.exchange.time_zone)
- option_chain_from_provider_api = list(self.option_chain_provider.get_option_contract_list(option.symbol, exchange_time))
-
- if len(option_chain_from_algorithm_api) == 0:
- raise AssertionError("No options in chain from algorithm API")
-
- if len(option_chain_from_provider_api) == 0:
- raise AssertionError("No options in chain from provider API")
-
- if len(option_chain_from_algorithm_api) != len(option_chain_from_provider_api):
- raise AssertionError(f"Expected {len(option_chain_from_provider_api)} options in chain from provider API, "
- f"but got {len(option_chain_from_algorithm_api)}");
-
- for i in range(len(option_chain_from_algorithm_api)):
- symbol1 = option_chain_from_algorithm_api[i]
- symbol2 = option_chain_from_provider_api[i]
-
- if symbol1 != symbol2:
- raise AssertionError(f"Expected {symbol2} in chain from provider API, but got {symbol1}")
-
- def get_test_date(self) -> datetime:
- return datetime(2015, 12, 25)
-
- def get_option(self) -> Option:
- return self.add_option("GOOG")
diff --git a/fincept-qt/scripts/strategies/OptionChainConsistencyRegressionAlgorithm.py b/fincept-qt/scripts/strategies/OptionChainConsistencyRegressionAlgorithm.py
deleted file mode 100644
index 82b22e31d..000000000
--- a/fincept-qt/scripts/strategies/OptionChainConsistencyRegressionAlgorithm.py
+++ /dev/null
@@ -1,62 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-98E14661
-# Category: Options
-# Description: This regression algorithm checks if all the option chain data coming to the algo is consistent with current securitie...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### This regression algorithm checks if all the option chain data coming to the algo is consistent with current securities manager state
-### </summary>
-### <meta name="tag" content="regression test" />
-### <meta name="tag" content="options" />
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="filter selection" />
-class OptionChainConsistencyRegressionAlgorithm(QCAlgorithm):
-
- underlying_ticker = "GOOG"
-
- def initialize(self):
-
- self.set_cash(10000)
- self.set_start_date(2015,12,24)
- self.set_end_date(2015,12,24)
-
- self.equity = self.add_equity(self.underlying_ticker);
- self.option = self.add_option(self.underlying_ticker);
-
- # set our strike/expiry filter for this option chain
- self.option.set_filter(self.universe_func)
-
- self.set_benchmark(self.equity.symbol)
-
- def on_data(self, slice):
- if self.portfolio.invested: return
- for kvp in slice.option_chains:
- chain = kvp.value
- for o in chain:
- if not self.securities.contains_key(o.symbol):
- self.log("Inconsistency found: option chains contains contract {0} that is not available in securities manager and not available for trading".format(o.symbol.value))
-
- contracts = filter(lambda x: x.expiry.date() == self.time.date() and
- x.strike < chain.underlying.price and
- x.right == OptionRight.CALL, chain)
-
- sorted_contracts = sorted(contracts, key = lambda x: x.strike, reverse = True)
-
- if len(sorted_contracts) > 2:
- self.market_order(sorted_contracts[2].symbol, 1)
- self.market_on_close_order(sorted_contracts[2].symbol, -1)
-
- # set our strike/expiry filter for this option chain
- def universe_func(self, universe):
- return universe.include_weeklys().strikes(-2, 2).expiration(timedelta(0), timedelta(10))
-
- def on_order_event(self, order_event):
- self.log(str(order_event))
diff --git a/fincept-qt/scripts/strategies/OptionChainFullDataRegressionAlgorithm.py b/fincept-qt/scripts/strategies/OptionChainFullDataRegressionAlgorithm.py
deleted file mode 100644
index 45df5f6e8..000000000
--- a/fincept-qt/scripts/strategies/OptionChainFullDataRegressionAlgorithm.py
+++ /dev/null
@@ -1,47 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-A05E4856
-# Category: Options
-# Description: Regression algorithm illustrating the usage of the <see cref="QCAlgorithm.OptionChain(Symbol)"/> method to get an opt...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-from datetime import timedelta
-
-### <summary>
-### Regression algorithm illustrating the usage of the <see cref="QCAlgorithm.OptionChain(Symbol)"/> method
-### to get an option chain, which contains additional data besides the symbols, including prices, implied volatility and greeks.
-### It also shows how this data can be used to filter the contracts based on certain criteria.
-### </summary>
-class OptionChainFullDataRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2015, 12, 24)
- self.set_end_date(2015, 12, 24)
- self.set_cash(100000)
-
- goog = self.add_equity("GOOG").symbol
-
- option_chain = self.option_chain(goog, flatten=True)
-
- # Demonstration using data frame:
- df = option_chain.data_frame
- # Get contracts expiring within 10 days, with an implied volatility greater than 0.5 and a delta less than 0.5
- contracts = df.loc[(df.expiry <= self.time + timedelta(days=10)) & (df.impliedvolatility > 0.5) & (df.delta < 0.5)]
-
- # Get the contract with the latest expiration date.
- # Note: the result of df.loc[] is a series, and its name is a tuple with a single element (contract symbol)
- self._option_contract = contracts.loc[contracts.expiry.idxmax()].name
-
- self.add_option_contract(self._option_contract)
-
- def on_data(self, data):
- # Do some trading with the selected contract for sample purposes
- if not self.portfolio.invested:
- self.market_order(self._option_contract, 1)
- else:
- self.liquidate()
diff --git a/fincept-qt/scripts/strategies/OptionChainProviderAlgorithm.py b/fincept-qt/scripts/strategies/OptionChainProviderAlgorithm.py
deleted file mode 100644
index 566c1dd57..000000000
--- a/fincept-qt/scripts/strategies/OptionChainProviderAlgorithm.py
+++ /dev/null
@@ -1,69 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-662DC1F1
-# Category: Options
-# Description: Demonstration of the Option Chain Provider -- a much faster mechanism for manually specifying the option contracts yo...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Demonstration of the Option Chain Provider -- a much faster mechanism for manually specifying the option contracts you'd like to recieve
-### data for and manually subscribing to them.
-### </summary>
-### <meta name="tag" content="strategy example" />
-### <meta name="tag" content="options" />
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="selecting options" />
-### <meta name="tag" content="manual selection" />
-
-class OptionChainProviderAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2015, 12, 24)
- self.set_end_date(2015, 12, 24)
- self.set_cash(100000)
- # add the underlying asset
- self.equity = self.add_equity("GOOG", Resolution.MINUTE)
- self.equity.set_data_normalization_mode(DataNormalizationMode.RAW)
- # initialize the option contract with empty string
- self.contract = str()
- self.contracts_added = set()
-
- def on_data(self, data):
-
- if not self.portfolio[self.equity.symbol].invested:
- self.market_order(self.equity.symbol, 100)
-
- if not (self.securities.contains_key(self.contract) and self.portfolio[self.contract].invested):
- self.contract = self.options_filter(data)
-
- if self.securities.contains_key(self.contract) and not self.portfolio[self.contract].invested:
- self.market_order(self.contract, -1)
-
- def options_filter(self, data):
- ''' OptionChainProvider gets a list of option contracts for an underlying symbol at requested date.
- Then you can manually filter the contract list returned by GetOptionContractList.
- The manual filtering will be limited to the information included in the Symbol
- (strike, expiration, type, style) and/or prices from a History call '''
-
- contracts = self.option_chain_provider.get_option_contract_list(self.equity.symbol, data.time)
- self.underlying_price = self.securities[self.equity.symbol].price
- # filter the out-of-money call options from the contract list which expire in 10 to 30 days from now on
- otm_calls = [i for i in contracts if i.id.option_right == OptionRight.CALL and
- i.id.strike_price - self.underlying_price > 0 and
- 10 < (i.id.date - data.time).days < 30]
- if len(otm_calls) > 0:
- contract = sorted(sorted(otm_calls, key = lambda x: x.id.date),
- key = lambda x: x.id.strike_price - self.underlying_price)[0]
- if contract not in self.contracts_added:
- self.contracts_added.add(contract)
- # use AddOptionContract() to subscribe the data for specified contract
- self.add_option_contract(contract, Resolution.MINUTE)
- return contract
- else:
- return str()
diff --git a/fincept-qt/scripts/strategies/OptionChainedUniverseSelectionModelRegressionAlgorithm.py b/fincept-qt/scripts/strategies/OptionChainedUniverseSelectionModelRegressionAlgorithm.py
deleted file mode 100644
index bdeb91a27..000000000
--- a/fincept-qt/scripts/strategies/OptionChainedUniverseSelectionModelRegressionAlgorithm.py
+++ /dev/null
@@ -1,50 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-1D2112EA
-# Category: Options
-# Description: Regression algorithm to test the OptionChainedUniverseSelectionModel class
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Regression algorithm to test the OptionChainedUniverseSelectionModel class
-### </summary>
-class OptionChainedUniverseSelectionModelRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.universe_settings.resolution = Resolution.MINUTE
- self.set_start_date(2014, 6, 6)
- self.set_end_date(2014, 6, 6)
- self.set_cash(100000)
-
- universe = self.add_universe("my-minute-universe-name", lambda time: [ "AAPL", "TWX" ])
- self.add_universe_selection(
- OptionChainedUniverseSelectionModel(
- universe,
- lambda u: (u.strikes(-2, +2)
- # Expiration method accepts TimeSpan objects or integer for days.
- # The following statements yield the same filtering criteria
- .expiration(0, 180))
- )
- )
-
- def on_data(self, slice):
- if self.portfolio.invested or not (self.is_market_open("AAPL") and self.is_market_open("TWX")): return
- values = list(map(lambda x: x.value, filter(lambda x: x.key == "?AAPL" or x.key == "?TWX", slice.option_chains)))
- for chain in values:
- # we sort the contracts to find at the money (ATM) contract with farthest expiration
- contracts = sorted(sorted(sorted(chain, \
- key = lambda x: abs(chain.underlying.price - x.strike)), \
- key = lambda x: x.expiry, reverse=True), \
- key = lambda x: x.right, reverse=True)
-
- # if found, trade it
- if len(contracts) == 0: return
- symbol = contracts[0].symbol
- self.market_order(symbol, 1)
- self.market_on_close_order(symbol, -1)
diff --git a/fincept-qt/scripts/strategies/OptionChainsMultipleFullDataRegressionAlgorithm.py b/fincept-qt/scripts/strategies/OptionChainsMultipleFullDataRegressionAlgorithm.py
deleted file mode 100644
index 098c71edd..000000000
--- a/fincept-qt/scripts/strategies/OptionChainsMultipleFullDataRegressionAlgorithm.py
+++ /dev/null
@@ -1,60 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-90DAF80B
-# Category: Options
-# Description: Regression algorithm illustrating the usage of the <see cref="QCAlgorithm.OptionChains(IEnumerable{Symbol})"/> method...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-from datetime import timedelta
-
-### <summary>
-### Regression algorithm illustrating the usage of the <see cref="QCAlgorithm.OptionChains(IEnumerable{Symbol})"/> method
-### to get multiple option chains, which contains additional data besides the symbols, including prices, implied volatility and greeks.
-### It also shows how this data can be used to filter the contracts based on certain criteria.
-### </summary>
-class OptionChainsMultipleFullDataRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2015, 12, 24)
- self.set_end_date(2015, 12, 24)
- self.set_cash(100000)
-
- goog = self.add_equity("GOOG").symbol
- spx = self.add_index("SPX").symbol
-
- chains = self.option_chains([goog, spx], flatten=True)
-
- self._goog_option_contract = self.get_contract(chains, goog, timedelta(days=10))
- self._spx_option_contract = self.get_contract(chains, spx, timedelta(days=60))
-
- self.add_option_contract(self._goog_option_contract)
- self.add_index_option_contract(self._spx_option_contract)
-
- def get_contract(self, chains: OptionChains, underlying: Symbol, expiry_span: timedelta) -> Symbol:
- df = chains.data_frame
-
- # Index by the requested underlying, by getting all data with canonicals which underlying is the requested underlying symbol:
- canonicals = df.index.get_level_values('canonical')
- condition = [canonical for canonical in canonicals if canonical.underlying == underlying]
- df = df.loc[condition]
-
- # Get contracts expiring in the next 10 days with an implied volatility greater than 0.5 and a delta less than 0.5
- contracts = df.loc[(df.expiry <= self.time + expiry_span) & (df.impliedvolatility > 0.5) & (df.delta < 0.5)]
-
- # Select the contract with the latest expiry date
- contracts.sort_values(by='expiry', ascending=False, inplace=True)
-
- # Get the symbol: the resulting series name is a tuple (canonical symbol, contract symbol)
- return contracts.iloc[0].name[1]
-
- def on_data(self, data):
- # Do some trading with the selected contract for sample purposes
- if not self.portfolio.invested:
- self.market_order(self._goog_option_contract, 1)
- else:
- self.liquidate()
diff --git a/fincept-qt/scripts/strategies/OptionDataNullReferenceRegressionAlgorithm.py b/fincept-qt/scripts/strategies/OptionDataNullReferenceRegressionAlgorithm.py
deleted file mode 100644
index d1f3cdf25..000000000
--- a/fincept-qt/scripts/strategies/OptionDataNullReferenceRegressionAlgorithm.py
+++ /dev/null
@@ -1,31 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-4E7CF48A
-# Category: Options
-# Description: This algorithm is a regression test for issue #2018 and PR #2038
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### This algorithm is a regression test for issue #2018 and PR #2038.
-### </summary>
-class OptionDataNullReferenceRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2016, 12, 1)
- self.set_end_date(2017, 1, 1)
- self.set_cash(500000)
-
- self.add_equity("DUST")
-
- option = self.add_option("DUST")
-
- option.set_filter(self.universe_func)
-
- def universe_func(self, universe):
- return universe.include_weeklys().strikes(-1, +1).expiration(timedelta(25), timedelta(100))
diff --git a/fincept-qt/scripts/strategies/OptionExerciseAssignRegressionAlgorithm.py b/fincept-qt/scripts/strategies/OptionExerciseAssignRegressionAlgorithm.py
deleted file mode 100644
index fcca4df34..000000000
--- a/fincept-qt/scripts/strategies/OptionExerciseAssignRegressionAlgorithm.py
+++ /dev/null
@@ -1,64 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-A9A9EB72
-# Category: Options
-# Description: This regression algorithm tests option exercise and assignment functionality We open two positions and go with them i...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### This regression algorithm tests option exercise and assignment functionality
-### We open two positions and go with them into expiration. We expect to see our long position exercised and short position assigned.
-### </summary>
-### <meta name="tag" content="regression test" />
-### <meta name="tag" content="options" />
-class OptionExerciseAssignRegressionAlgorithm(QCAlgorithm):
-
- underlying_ticker = "GOOG"
-
- def initialize(self):
- self.set_cash(100000)
- self.set_start_date(2015,12,24)
- self.set_end_date(2015,12,28)
-
- self.equity = self.add_equity(self.underlying_ticker)
- self.option = self.add_option(self.underlying_ticker)
-
- # set our strike/expiry filter for this option chain
- self.option.set_filter(self.universe_func)
-
- self.set_benchmark(self.equity.symbol)
- self._assigned_option = False
-
- def on_data(self, slice):
- if self.portfolio.invested: return
- for kvp in slice.option_chains:
- chain = kvp.value
- # find the call options expiring today
- contracts = filter(lambda x:
- x.expiry.date() == self.time.date() and
- x.strike < chain.underlying.price and
- x.right == OptionRight.CALL, chain)
-
- # sorted the contracts by their strikes, find the second strike under market price
- sorted_contracts = sorted(contracts, key = lambda x: x.strike, reverse = True)[:2]
-
- if sorted_contracts:
- self.market_order(sorted_contracts[0].symbol, 1)
- self.market_order(sorted_contracts[1].symbol, -1)
-
- # set our strike/expiry filter for this option chain
- def universe_func(self, universe):
- return universe.include_weeklys().strikes(-2, 2).expiration(timedelta(0), timedelta(10))
-
- def on_order_event(self, order_event):
- self.log(str(order_event))
-
- def on_assignment_order_event(self, assignment_event):
- self.log(str(assignment_event))
- self._assigned_option = True
diff --git a/fincept-qt/scripts/strategies/OptionIndicatorsMirrorContractsRegressionAlgorithm.py b/fincept-qt/scripts/strategies/OptionIndicatorsMirrorContractsRegressionAlgorithm.py
deleted file mode 100644
index 4114cfa71..000000000
--- a/fincept-qt/scripts/strategies/OptionIndicatorsMirrorContractsRegressionAlgorithm.py
+++ /dev/null
@@ -1,82 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-CFC8C48B
-# Category: Options
-# Description: Option Indicators Mirror Contracts Regression Algorithm
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-from scipy.optimize import brentq
-
-class OptionIndicatorsMirrorContractsRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2014, 6, 5)
- self.set_end_date(2014, 6, 9)
- self.set_cash(100000)
-
- equity = self.add_equity("AAPL", Resolution.DAILY).symbol
- option = Symbol.create_option("AAPL", Market.USA, OptionStyle.AMERICAN, OptionRight.PUT, 650, datetime(2014, 6, 21))
- self.add_option_contract(option, Resolution.DAILY)
- # add the call counter side of the mirrored pair
- mirror_option = Symbol.create_option("AAPL", Market.USA, OptionStyle.AMERICAN, OptionRight.CALL, 650, datetime(2014, 6, 21))
- self.add_option_contract(mirror_option, Resolution.DAILY)
-
- self.delta = self.d(option, mirror_option, option_model = OptionPricingModelType.BINOMIAL_COX_ROSS_RUBINSTEIN, iv_model = OptionPricingModelType.BLACK_SCHOLES)
- self.gamma = self.g(option, mirror_option, option_model = OptionPricingModelType.FORWARD_TREE, iv_model = OptionPricingModelType.BLACK_SCHOLES)
- self.vega = self.v(option, mirror_option, option_model = OptionPricingModelType.FORWARD_TREE, iv_model = OptionPricingModelType.BLACK_SCHOLES)
- self.theta = self.t(option, mirror_option, option_model = OptionPricingModelType.FORWARD_TREE, iv_model = OptionPricingModelType.BLACK_SCHOLES)
- self.rho = self.r(option, mirror_option, option_model = OptionPricingModelType.FORWARD_TREE, iv_model = OptionPricingModelType.BLACK_SCHOLES)
-
- # A custom IV indicator with custom calculation of IV
- risk_free_rate_model = InterestRateProvider()
- dividend_yield_model = DividendYieldProvider(equity)
- self.implied_volatility = CustomImpliedVolatility(option, mirror_option, risk_free_rate_model, dividend_yield_model)
- self.register_indicator(option, self.implied_volatility, QuoteBarConsolidator(timedelta(1)))
- self.register_indicator(mirror_option, self.implied_volatility, QuoteBarConsolidator(timedelta(1)))
- self.register_indicator(equity, self.implied_volatility, TradeBarConsolidator(timedelta(1)))
-
- # custom IV smoothing function: assume the lower IV is more "fair"
- smoothing_func = lambda iv, mirror_iv: min(iv, mirror_iv)
- # set the smoothing function
- self.delta.implied_volatility.set_smoothing_function(smoothing_func)
- self.gamma.implied_volatility.set_smoothing_function(smoothing_func)
- self.vega.implied_volatility.set_smoothing_function(smoothing_func)
- self.theta.implied_volatility.set_smoothing_function(smoothing_func)
- self.rho.implied_volatility.set_smoothing_function(smoothing_func)
-
- def on_end_of_algorithm(self):
- if not self.implied_volatility.is_ready or not self.delta.is_ready or not self.gamma.is_ready \
- or not self.vega.is_ready or not self.theta.is_ready or not self.rho.is_ready:
- raise Exception("Expected IV/greeks calculated")
-
- self.debug(f"""Implied Volatility: {self.implied_volatility.current.value},
-Delta: {self.delta.current.value},
-Gamma: {self.gamma.current.value},
-Vega: {self.vega.current.value},
-Theta: {self.theta.current.value},
-Rho: {self.rho.current.value}""")
-
-class CustomImpliedVolatility(ImpliedVolatility):
- def __init__(self, option, mirror_option, risk_free_rate_model, dividend_yield_model):
- super().__init__(option, risk_free_rate_model, dividend_yield_model, mirror_option)
- self.set_smoothing_function(lambda iv, mirror_iv: iv)
-
- def calculate_iv(self, time_till_expiry: float) -> float:
- try:
- return brentq(self.f, 1e-7, 2.0, args=(time_till_expiry), xtol=1e-4, maxiter=100)
- except:
- print("ImpliedVolatility.calculate_i_v(): Fail to converge, returning 0.")
- return 0.0
-
- # we demonstate put-call parity calculation here, but note that it is not suitable for American options
- def f(self, vol: float, time_till_expiry: float) -> float:
- call_black_price = OptionGreekIndicatorsHelper.black_theoretical_price(
- vol, UnderlyingPrice.current.value, self.strike, time_till_expiry, RiskFreeRate.current.value, DividendYield.current.value, OptionRight.CALL)
- put_black_price = OptionGreekIndicatorsHelper.black_theoretical_price(
- vol, UnderlyingPrice.current.value, self.strike, time_till_expiry, RiskFreeRate.current.value, DividendYield.current.value, OptionRight.PUT)
- return Price.current.value + OppositePrice.current.value - call_black_price - put_black_price
diff --git a/fincept-qt/scripts/strategies/OptionIndicatorsRegressionAlgorithm.py b/fincept-qt/scripts/strategies/OptionIndicatorsRegressionAlgorithm.py
deleted file mode 100644
index 7b89c900c..000000000
--- a/fincept-qt/scripts/strategies/OptionIndicatorsRegressionAlgorithm.py
+++ /dev/null
@@ -1,42 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-707335FB
-# Category: Options
-# Description: Option Indicators Regression Algorithm
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-class OptionIndicatorsRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2014, 6, 5)
- self.set_end_date(2014, 6, 7)
- self.set_cash(100000)
-
- self.add_equity("AAPL", Resolution.MINUTE)
- option = Symbol.create_option("AAPL", Market.USA, OptionStyle.AMERICAN, OptionRight.PUT, 505, datetime(2014, 6, 27))
- self.add_option_contract(option, Resolution.MINUTE)
-
- self.implied_volatility = self.iv(option, option_model = OptionPricingModelType.BLACK_SCHOLES)
- self.delta = self.d(option, option_model = OptionPricingModelType.BINOMIAL_COX_ROSS_RUBINSTEIN, iv_model = OptionPricingModelType.BLACK_SCHOLES)
- self.gamma = self.g(option, option_model = OptionPricingModelType.FORWARD_TREE, iv_model = OptionPricingModelType.BLACK_SCHOLES)
- self.vega = self.v(option, option_model = OptionPricingModelType.FORWARD_TREE, iv_model = OptionPricingModelType.BLACK_SCHOLES)
- self.theta = self.t(option, option_model = OptionPricingModelType.FORWARD_TREE, iv_model = OptionPricingModelType.BLACK_SCHOLES)
- self.rho = self.r(option, option_model = OptionPricingModelType.FORWARD_TREE, iv_model = OptionPricingModelType.BLACK_SCHOLES)
-
- def on_end_of_algorithm(self):
- if self.implied_volatility.current.value == 0 or self.delta.current.value == 0 or self.gamma.current.value == 0 \
- or self.vega.current.value == 0 or self.theta.current.value == 0 or self.rho.current.value == 0:
- raise Exception("Expected IV/greeks calculated")
-
- self.debug(f"""Implied Volatility: {self.implied_volatility.current.value},
-Delta: {self.delta.current.value},
-Gamma: {self.gamma.current.value},
-Vega: {self.vega.current.value},
-Theta: {self.theta.current.value},
-Rho: {self.rho.current.value}""")
diff --git a/fincept-qt/scripts/strategies/OptionModelsConsistencyRegressionAlgorithm.py b/fincept-qt/scripts/strategies/OptionModelsConsistencyRegressionAlgorithm.py
deleted file mode 100644
index 79d38213c..000000000
--- a/fincept-qt/scripts/strategies/OptionModelsConsistencyRegressionAlgorithm.py
+++ /dev/null
@@ -1,70 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-62B73DDD
-# Category: Options
-# Description: Algorithm asserting that when setting custom models for canonical securities, a one-time warning is sent informing th...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-from System import Action
-
-from QuantConnect.Logging import *
-
-### <summary>
-### Algorithm asserting that when setting custom models for canonical securities, a one-time warning is sent
-### informing the user that the contracts models are different (not the custom ones).
-### </summary>
-class OptionModelsConsistencyRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self) -> None:
- security = self.initialize_algorithm()
- self.set_models(security)
-
- # Using a custom security initializer derived from BrokerageModelSecurityInitializer
- # to check that the models are correctly set in the security even when the
- # security initializer is derived from said class in Python
- self.set_security_initializer(CustomSecurityInitializer(self.brokerage_model, SecuritySeeder.NULL))
-
- self.set_benchmark(lambda x: 0)
-
- def initialize_algorithm(self) -> Security:
- self.set_start_date(2015, 12, 24)
- self.set_end_date(2015, 12, 24)
-
- equity = self.add_equity("GOOG", leverage=4)
- option = self.add_option(equity.symbol)
- option.set_filter(lambda u: u.strikes(-2, +2).expiration(0, 180))
-
- return option
-
- def set_models(self, security: Security) -> None:
- security.set_fill_model(CustomFillModel())
- security.set_fee_model(CustomFeeModel())
- security.set_buying_power_model(CustomBuyingPowerModel())
- security.set_slippage_model(CustomSlippageModel())
- security.set_volatility_model(CustomVolatilityModel())
-
-class CustomSecurityInitializer(BrokerageModelSecurityInitializer):
- def __init__(self, brokerage_model: BrokerageModel, security_seeder: SecuritySeeder):
- super().__init__(brokerage_model, security_seeder)
-
-class CustomFillModel(FillModel):
- pass
-
-class CustomFeeModel(FeeModel):
- pass
-
-class CustomBuyingPowerModel(BuyingPowerModel):
- pass
-
-class CustomSlippageModel(ConstantSlippageModel):
- def __init__(self):
- super().__init__(0)
-
-class CustomVolatilityModel(BaseVolatilityModel):
- pass
diff --git a/fincept-qt/scripts/strategies/OptionOpenInterestRegressionAlgorithm.py b/fincept-qt/scripts/strategies/OptionOpenInterestRegressionAlgorithm.py
deleted file mode 100644
index 2a6ba93cb..000000000
--- a/fincept-qt/scripts/strategies/OptionOpenInterestRegressionAlgorithm.py
+++ /dev/null
@@ -1,49 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-0FFCB469
-# Category: Options
-# Description: Price-volume divergence strategy inspired by open interest
-# analysis. Buys when price makes new 10-day high with expanding volume,
-# sells when price makes new 10-day low or volume contracts significantly.
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-class OptionOpenInterestRegressionAlgorithm(QCAlgorithm):
- """Price-volume divergence strategy inspired by open interest analysis."""
-
- def initialize(self):
- self.set_start_date(2023, 1, 1)
- self.set_end_date(2024, 1, 1)
- self.set_cash(100000)
-
- self.symbol = "SPY"
- self.add_equity(self.symbol, Resolution.DAILY)
-
- self._max = self.max(self.symbol, 10, Resolution.DAILY)
- self._min = self.min(self.symbol, 10, Resolution.DAILY)
- self._bar_count = 0
-
- def on_data(self, data):
- if not self._max.is_ready or not self._min.is_ready:
- return
- if self.symbol not in data:
- return
-
- self._bar_count += 1
- price = data[self.symbol].close
- high_10 = self._max.current.value
- low_10 = self._min.current.value
-
- if not self.portfolio.invested:
- # Buy on new 10-day high breakout
- if price >= high_10 and self._bar_count > 10:
- self.set_holdings(self.symbol, 1)
- else:
- # Sell on 10-day low breakdown
- if price <= low_10:
- self.liquidate()
diff --git a/fincept-qt/scripts/strategies/OptionPriceModelForOptionStylesBaseRegressionAlgorithm.py b/fincept-qt/scripts/strategies/OptionPriceModelForOptionStylesBaseRegressionAlgorithm.py
deleted file mode 100644
index 3708f7b29..000000000
--- a/fincept-qt/scripts/strategies/OptionPriceModelForOptionStylesBaseRegressionAlgorithm.py
+++ /dev/null
@@ -1,78 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-9520559C
-# Category: Options
-# Description: Base regression algorithm exercising different style options with option price models that might or might not support...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Base regression algorithm exercising different style options with option price models that might
-### or might not support them. Also, if the option style is supported, greeks are asserted to be accesible and have valid values.
-### </summary>
-class OptionPriceModelForOptionStylesBaseRegressionAlgorithm(QCAlgorithm):
- def __init__(self):
- super().__init__()
- self._option_style_is_supported = False
- self._check_greeks = True
- self._tried_greeks_calculation = False
- self._option = None
-
- def on_data(self, slice):
- if self.is_warming_up: return
-
- for kvp in slice.option_chains:
- if self._option is None or kvp.key != self._option.symbol: continue
-
- self.check_greeks([contract for contract in kvp.value])
-
- def on_end_of_day(self, symbol):
- self._check_greeks = True
-
- def on_end_of_algorithm(self):
- if not self._tried_greeks_calculation:
- raise Exception("Expected greeks to be accessed")
-
- def init(self, option, option_style_is_supported):
- self._option = option
- self._option_style_is_supported = option_style_is_supported
- self._check_greeks = True
- self._tried_greeks_calculation = False
-
- def check_greeks(self, contracts):
- if not self._check_greeks or len(contracts) == 0: return
-
- self._check_greeks = False
- self._tried_greeks_calculation = True
-
- for contract in contracts:
- greeks = None
- try:
- greeks = contract.greeks
-
- # Greeks should have not been successfully accessed if the option style is not supported
- option_style_str = 'American' if self._option.style == OptionStyle.AMERICAN else 'European'
- if not self._option_style_is_supported:
- raise Exception(f'Expected greeks not to be calculated for {contract.symbol.value}, an {option_style_str} style option, using {type(self._option.price_model).__name__}, which does not support them, but they were')
- except ArgumentException:
- # ArgumentException is only expected if the option style is not supported
- if self._option_style_is_supported:
- raise Exception(f'Expected greeks to be calculated for {contract.symbol.value}, an {option_style_str} style option, using {type(self._option.price_model).__name__}, which supports them, but they were not')
-
- # Greeks should be valid if they were successfuly accessed for supported option style
- # Delta can be {-1, 0, 1} if the price is too wild, rho can be 0 if risk free rate is 0
- # Vega can be 0 if the price is very off from theoretical price, Gamma = 0 if Delta belongs to {-1, 1}
- if (self._option_style_is_supported
- and (greeks is None
- or ((contract.right == OptionRight.CALL and (greeks.delta < 0.0 or greeks.delta > 1.0 or greeks.rho < 0.0))
- or (contract.right == OptionRight.PUT and (greeks.delta < -1.0 or greeks.delta > 0.0 or greeks.rho > 0.0))
- or greeks.theta == 0.0 or greeks.vega < 0.0 or greeks.gamma < 0.0))):
- raise Exception(f'Expected greeks to have valid values. Greeks were: Delta: {greeks.delta}, Rho: {greeks.rho}, Theta: {greeks.theta}, Vega: {greeks.vega}, Gamma: {greeks.gamma}')
-
-
-
diff --git a/fincept-qt/scripts/strategies/OptionPriceModelForSupportedAmericanOptionRegressionAlgorithm.py b/fincept-qt/scripts/strategies/OptionPriceModelForSupportedAmericanOptionRegressionAlgorithm.py
deleted file mode 100644
index 0797f6397..000000000
--- a/fincept-qt/scripts/strategies/OptionPriceModelForSupportedAmericanOptionRegressionAlgorithm.py
+++ /dev/null
@@ -1,30 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-9884C10F
-# Category: Options
-# Description: Regression algorithm exercising an equity covered American style option, using an option price model that supports Am...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-from OptionPriceModelForOptionStylesBaseRegressionAlgorithm import OptionPriceModelForOptionStylesBaseRegressionAlgorithm
-
-### <summary>
-### Regression algorithm exercising an equity covered American style option, using an option price model
-### that supports American style options and asserting that the option price model is used.
-### </summary>
-class OptionPriceModelForSupportedAmericanOptionRegressionAlgorithm(OptionPriceModelForOptionStylesBaseRegressionAlgorithm):
- def initialize(self):
- self.set_start_date(2014, 6, 9)
- self.set_end_date(2014, 6, 9)
-
- option = self.add_option("AAPL", Resolution.MINUTE)
- # BaroneAdesiWhaley model supports American style options
- option.price_model = OptionPriceModels.barone_adesi_whaley()
-
- self.set_warmup(2, Resolution.DAILY)
-
- self.init(option, option_style_is_supported=True)
diff --git a/fincept-qt/scripts/strategies/OptionPriceModelForSupportedAmericanOptionTimeSpanWarmupRegressionAlgorithm.py b/fincept-qt/scripts/strategies/OptionPriceModelForSupportedAmericanOptionTimeSpanWarmupRegressionAlgorithm.py
deleted file mode 100644
index ba3e36bf9..000000000
--- a/fincept-qt/scripts/strategies/OptionPriceModelForSupportedAmericanOptionTimeSpanWarmupRegressionAlgorithm.py
+++ /dev/null
@@ -1,25 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-B34DCB29
-# Category: Options
-# Description: Regression algorithm exercising an equity covered American style option, using an option price model that supports Am...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-from OptionPriceModelForSupportedAmericanOptionRegressionAlgorithm import OptionPriceModelForSupportedAmericanOptionRegressionAlgorithm
-
-### <summary>
-### Regression algorithm exercising an equity covered American style option, using an option price model
-### that supports American style options and asserting that the option price model is used.
-### </summary>
-class OptionPriceModelForSupportedAmericanOptionTimeSpanWarmupRegressionAlgorithm(OptionPriceModelForSupportedAmericanOptionRegressionAlgorithm):
- def initialize(self):
- OptionPriceModelForSupportedAmericanOptionRegressionAlgorithm.initialize(self)
-
- # We want to match the start time of the base algorithm: Base algorithm warmup is 2 bar of daily resolution.
- # So to match the same start time we go back 4 days, we need to account for a single weekend. This is calculated by 'Time.GET_START_TIME_FOR_TRADE_BARS'
- self.set_warmup(TimeSpan.from_days(4))
diff --git a/fincept-qt/scripts/strategies/OptionPriceModelForSupportedEuropeanOptionRegressionAlgorithm.py b/fincept-qt/scripts/strategies/OptionPriceModelForSupportedEuropeanOptionRegressionAlgorithm.py
deleted file mode 100644
index 5c359f41e..000000000
--- a/fincept-qt/scripts/strategies/OptionPriceModelForSupportedEuropeanOptionRegressionAlgorithm.py
+++ /dev/null
@@ -1,30 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-B6D1CB41
-# Category: Options
-# Description: Regression algorithm exercising an equity covered European style option, using an option price model that supports Eu...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-from OptionPriceModelForOptionStylesBaseRegressionAlgorithm import OptionPriceModelForOptionStylesBaseRegressionAlgorithm
-
-### <summary>
-### Regression algorithm exercising an equity covered European style option, using an option price model
-### that supports European style options and asserting that the option price model is used.
-### </summary>
-class OptionPriceModelForSupportedEuropeanOptionRegressionAlgorithm(OptionPriceModelForOptionStylesBaseRegressionAlgorithm):
- def initialize(self):
- self.set_start_date(2021, 1, 14)
- self.set_end_date(2021, 1, 14)
-
- option = self.add_index_option("SPX", Resolution.HOUR)
- # BlackScholes model supports European style options
- option.price_model = OptionPriceModels.black_scholes()
-
- self.set_warmup(7, Resolution.DAILY)
-
- self.init(option, option_style_is_supported=True)
diff --git a/fincept-qt/scripts/strategies/OptionPriceModelForSupportedEuropeanOptionTimeSpanWarmupRegressionAlgorithm.py b/fincept-qt/scripts/strategies/OptionPriceModelForSupportedEuropeanOptionTimeSpanWarmupRegressionAlgorithm.py
deleted file mode 100644
index 1e7e9d2b4..000000000
--- a/fincept-qt/scripts/strategies/OptionPriceModelForSupportedEuropeanOptionTimeSpanWarmupRegressionAlgorithm.py
+++ /dev/null
@@ -1,26 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-6812E1E8
-# Category: Options
-# Description: Regression algorithm exercising an equity covered European style option, using an option price model that supports Eu...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-from OptionPriceModelForSupportedEuropeanOptionRegressionAlgorithm import OptionPriceModelForSupportedEuropeanOptionRegressionAlgorithm
-
-### <summary>
-### Regression algorithm exercising an equity covered European style option, using an option price model
-### that supports European style options and asserting that the option price model is used.
-### </summary>
-class OptionPriceModelForSupportedEuropeanOptionTimeSpanWarmupRegressionAlgorithm(OptionPriceModelForSupportedEuropeanOptionRegressionAlgorithm):
- def initialize(self):
- OptionPriceModelForSupportedEuropeanOptionRegressionAlgorithm.initialize(self)
-
- # We want to match the start time of the base algorithm. SPX index options data time zone is chicago, algorithm time zone is new york (default).
- # Base algorithm warmup is 7 bar of daily resolution starts at 23 PM new york time of T-1. So to match the same start time
- # we go back a 9 day + 23 hours, we need to account for a single weekend. This is calculated by 'Time.GET_START_TIME_FOR_TRADE_BARS'
- self.set_warmup(TimeSpan.from_hours(24 * 9 + 23))
diff --git a/fincept-qt/scripts/strategies/OptionPriceModelForUnsupportedAmericanOptionRegressionAlgorithm.py b/fincept-qt/scripts/strategies/OptionPriceModelForUnsupportedAmericanOptionRegressionAlgorithm.py
deleted file mode 100644
index 366374165..000000000
--- a/fincept-qt/scripts/strategies/OptionPriceModelForUnsupportedAmericanOptionRegressionAlgorithm.py
+++ /dev/null
@@ -1,40 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-03E734EA
-# Category: Options
-# Description: RSI-based overbought/oversold strategy adapted from American
-# options pricing research. Buys SPY when RSI(14) drops below 30 (oversold),
-# exits when RSI rises above 70 (overbought).
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-class OptionPriceModelForUnsupportedAmericanOptionRegressionAlgorithm(QCAlgorithm):
- """RSI overbought/oversold strategy adapted from options pricing models."""
-
- def initialize(self):
- self.set_start_date(2023, 1, 1)
- self.set_end_date(2024, 1, 1)
- self.set_cash(100000)
-
- self.symbol = "SPY"
- self.add_equity(self.symbol, Resolution.DAILY)
-
- self._rsi = self.rsi(self.symbol, 14, Resolution.DAILY)
-
- def on_data(self, data):
- if not self._rsi.is_ready:
- return
- if self.symbol not in data:
- return
-
- rsi_val = self._rsi.current.value
-
- if not self.portfolio.invested and rsi_val < 30:
- self.set_holdings(self.symbol, 1)
- elif self.portfolio.invested and rsi_val > 70:
- self.liquidate()
diff --git a/fincept-qt/scripts/strategies/OptionPriceModelForUnsupportedAmericanOptionTimeSpanWarmupRegressionAlgorithm.py b/fincept-qt/scripts/strategies/OptionPriceModelForUnsupportedAmericanOptionTimeSpanWarmupRegressionAlgorithm.py
deleted file mode 100644
index 05d2ef260..000000000
--- a/fincept-qt/scripts/strategies/OptionPriceModelForUnsupportedAmericanOptionTimeSpanWarmupRegressionAlgorithm.py
+++ /dev/null
@@ -1,25 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-850F1B89
-# Category: Options
-# Description: Regression algorithm exercising an equity covered American style option, using an option price model that supports Am...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-from OptionPriceModelForUnsupportedAmericanOptionRegressionAlgorithm import OptionPriceModelForUnsupportedAmericanOptionRegressionAlgorithm
-
-### <summary>
-### Regression algorithm exercising an equity covered American style option, using an option price model
-### that supports American style options and asserting that the option price model is used.
-### </summary>
-class OptionPriceModelForUnsupportedAmericanOptionTimeSpanWarmupRegressionAlgorithm(OptionPriceModelForUnsupportedAmericanOptionRegressionAlgorithm):
- def initialize(self):
- OptionPriceModelForUnsupportedAmericanOptionRegressionAlgorithm.initialize(self)
-
- # We want to match the start time of the base algorithm: Base algorithm warmup is 2 bar of daily resolution.
- # So to match the same start time we go back 4 days, we need to account for a single weekend. This is calculated by 'Time.GET_START_TIME_FOR_TRADE_BARS'
- self.set_warmup(TimeSpan.from_days(4))
diff --git a/fincept-qt/scripts/strategies/OptionPriceModelForUnsupportedEuropeanOptionRegressionAlgorithm.py b/fincept-qt/scripts/strategies/OptionPriceModelForUnsupportedEuropeanOptionRegressionAlgorithm.py
deleted file mode 100644
index 82dd697f3..000000000
--- a/fincept-qt/scripts/strategies/OptionPriceModelForUnsupportedEuropeanOptionRegressionAlgorithm.py
+++ /dev/null
@@ -1,30 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-C99DFC04
-# Category: Options
-# Description: Regression algorithm exercising an equity covered European style option, using an option price model that does not su...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-from OptionPriceModelForOptionStylesBaseRegressionAlgorithm import OptionPriceModelForOptionStylesBaseRegressionAlgorithm
-
-### <summary>
-### Regression algorithm exercising an equity covered European style option, using an option price model
-### that does not support European style options and asserting that the option price model is not used.
-### </summary>
-class OptionPriceModelForUnsupportedEuropeanOptionRegressionAlgorithm(OptionPriceModelForOptionStylesBaseRegressionAlgorithm):
- def initialize(self):
- self.set_start_date(2021, 1, 14)
- self.set_end_date(2021, 1, 14)
-
- option = self.add_index_option("SPX", Resolution.HOUR)
- # BaroneAdesiWhaley model does not support European style options
- option.price_model = OptionPriceModels.barone_adesi_whaley()
-
- self.set_warmup(7, Resolution.DAILY)
-
- self.init(option, option_style_is_supported=False)
diff --git a/fincept-qt/scripts/strategies/OptionPriceModelForUnsupportedEuropeanOptionTimeSpanWarmupRegressionAlgorithm.py b/fincept-qt/scripts/strategies/OptionPriceModelForUnsupportedEuropeanOptionTimeSpanWarmupRegressionAlgorithm.py
deleted file mode 100644
index ede08ad28..000000000
--- a/fincept-qt/scripts/strategies/OptionPriceModelForUnsupportedEuropeanOptionTimeSpanWarmupRegressionAlgorithm.py
+++ /dev/null
@@ -1,26 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-6FBD513A
-# Category: Options
-# Description: Regression algorithm exercising an equity covered European style option, using an option price model that does not su...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-from OptionPriceModelForUnsupportedEuropeanOptionRegressionAlgorithm import OptionPriceModelForUnsupportedEuropeanOptionRegressionAlgorithm
-
-### <summary>
-### Regression algorithm exercising an equity covered European style option, using an option price model
-### that does not support European style options and asserting that the option price model is not used.
-### </summary>
-class OptionPriceModelForUnsupportedEuropeanOptionTimeSpanWarmupRegressionAlgorithm(OptionPriceModelForUnsupportedEuropeanOptionRegressionAlgorithm):
- def initialize(self):
- OptionPriceModelForUnsupportedEuropeanOptionRegressionAlgorithm.initialize(self)
-
- # We want to match the start time of the base algorithm. SPX index options data time zone is chicago, algorithm time zone is new york (default).
- # Base algorithm warmup is 7 bar of daily resolution starts at 23 PM new york time of T-1. So to match the same start time
- # we go back a 9 day + 23 hours, we need to account for a single weekend. This is calculated by 'Time.GET_START_TIME_FOR_TRADE_BARS'
- self.set_warmup(TimeSpan.from_hours(24 * 9 + 23))
diff --git a/fincept-qt/scripts/strategies/OptionRenameRegressionAlgorithm.py b/fincept-qt/scripts/strategies/OptionRenameRegressionAlgorithm.py
deleted file mode 100644
index b25cd8ef4..000000000
--- a/fincept-qt/scripts/strategies/OptionRenameRegressionAlgorithm.py
+++ /dev/null
@@ -1,70 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-8E5F0BE5
-# Category: Options
-# Description: This is an option split regression algorithm
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### This is an option split regression algorithm
-### </summary>
-### <meta name="tag" content="options" />
-### <meta name="tag" content="regression test" />
-class OptionRenameRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self):
-
- self.set_cash(1000000)
- self.set_start_date(2013,6,28)
- self.set_end_date(2013,7,2)
- option = self.add_option("TFCFA")
-
- # set our strike/expiry filter for this option chain
- option.set_filter(-1, 1, timedelta(0), timedelta(3650))
- # use the underlying equity as the benchmark
- self.set_benchmark("TFCFA")
-
- def on_data(self, slice):
- ''' Event - v3.0 DATA EVENT HANDLER: (Pattern) Basic template for user to override for receiving all subscription data in a single event
- <param name="slice">The current slice of data keyed by symbol string</param> '''
- if not self.portfolio.invested:
- for kvp in slice.option_chains:
- chain = kvp.value
- if self.time.day == 28 and self.time.hour > 9 and self.time.minute > 0:
-
- contracts = [i for i in sorted(chain, key=lambda x:x.expiry)
- if i.right == OptionRight.CALL and
- i.strike == 33 and
- i.expiry.date() == datetime(2013,8,17).date()]
- if contracts:
- # Buying option
- contract = contracts[0]
- self.buy(contract.symbol, 1)
- # Buy the undelying stock
- underlying_symbol = contract.symbol.underlying
- self.buy (underlying_symbol, 100)
- # check
- if float(contract.ask_price) != 1.1:
- raise ValueError("Regression test failed: current ask price was not loaded from NWSA backtest file and is not $1.1")
- elif self.time.day == 2 and self.time.hour > 14 and self.time.minute > 0:
- for kvp in slice.option_chains:
- chain = kvp.value
- self.liquidate()
- contracts = [i for i in sorted(chain, key=lambda x:x.expiry)
- if i.right == OptionRight.CALL and
- i.strike == 33 and
- i.expiry.date() == datetime(2013,8,17).date()]
- if contracts:
- contract = contracts[0]
- self.log("Bid Price" + str(contract.bid_price))
- if float(contract.bid_price) != 0.05:
- raise ValueError("Regression test failed: current bid price was not loaded from FOXA file and is not $0.05")
-
- def on_order_event(self, order_event):
- self.log(str(order_event))
diff --git a/fincept-qt/scripts/strategies/OptionSplitRegressionAlgorithm.py b/fincept-qt/scripts/strategies/OptionSplitRegressionAlgorithm.py
deleted file mode 100644
index 2133c3cc4..000000000
--- a/fincept-qt/scripts/strategies/OptionSplitRegressionAlgorithm.py
+++ /dev/null
@@ -1,67 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-D07A1F27
-# Category: Options
-# Description: This regression algorithm tests option exercise and assignment functionality We open two positions and go with them i...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### This regression algorithm tests option exercise and assignment functionality
-### We open two positions and go with them into expiration. We expect to see our long position exercised and short position assigned.
-### </summary>
-### <meta name="tag" content="regression test" />
-### <meta name="tag" content="options" />
-class OptionSplitRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self):
-
- # this test opens position in the first day of trading, lives through stock split (7 for 1),
- # and closes adjusted position on the second day
-
- self.set_cash(1000000)
- self.set_start_date(2014,6,6)
- self.set_end_date(2014,6,9)
-
- option = self.add_option("AAPL")
-
- # set our strike/expiry filter for this option chain
- option.set_filter(self.universe_func)
-
- self.set_benchmark("AAPL")
- self.contract = None
-
- def on_data(self, slice):
- if not self.portfolio.invested:
- if self.time.hour > 9 and self.time.minute > 0:
- for kvp in slice.option_chains:
- chain = kvp.value
- contracts = filter(lambda x: x.strike == 650 and x.right == OptionRight.CALL, chain)
- sorted_contracts = sorted(contracts, key = lambda x: x.expiry)
-
- if len(sorted_contracts) > 1:
- self.contract = sorted_contracts[1]
- self.buy(self.contract.symbol, 1)
-
- elif self.time.day > 6 and self.time.hour > 14 and self.time.minute > 0:
- self.liquidate()
-
- if self.portfolio.invested:
- options_hold = [x for x in self.portfolio.securities if x.value.holdings.absolute_quantity != 0]
- holdings = options_hold[0].value.holdings.absolute_quantity
- if self.time.day == 6 and holdings != 1:
- self.log("Expected position quantity of 1 but was {0}".format(holdings))
- if self.time.day == 9 and holdings != 7:
- self.log("Expected position quantity of 7 but was {0}".format(holdings))
-
- # set our strike/expiry filter for this option chain
- def universe_func(self, universe):
- return universe.include_weeklys().strikes(-2, 2).expiration(timedelta(0), timedelta(365*2))
-
- def on_order_event(self, order_event):
- self.log(str(order_event))
diff --git a/fincept-qt/scripts/strategies/OptionStrategyFactoryMethodsBaseAlgorithm.py b/fincept-qt/scripts/strategies/OptionStrategyFactoryMethodsBaseAlgorithm.py
deleted file mode 100644
index 65e2da806..000000000
--- a/fincept-qt/scripts/strategies/OptionStrategyFactoryMethodsBaseAlgorithm.py
+++ /dev/null
@@ -1,73 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-CB64E8E9
-# Category: Options
-# Description: This base algorithm demonstrates how to use OptionStrategies helper class to batch send orders for common strategies
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-from QuantConnect.Securities.Positions import IPositionGroup
-
-### <summary>
-### This base algorithm demonstrates how to use OptionStrategies helper class to batch send orders for common strategies.
-### </summary>
-class OptionStrategyFactoryMethodsBaseAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2015, 12, 24)
- self.set_end_date(2015, 12, 24)
- self.set_cash(1000000)
-
- option = self.add_option("GOOG")
- self._option_symbol = option.symbol
-
- option.set_filter(-2, +2, 0, 180)
-
- self.set_benchmark("GOOG")
-
- def on_data(self, slice):
- if not self.portfolio.invested:
- chain = slice.option_chains.get(self._option_symbol)
- if chain is not None:
- self.trade_strategy(chain, self._option_symbol)
- else:
- # Verify that the strategy was traded
- position_group = list(self.portfolio.positions.groups)[0]
-
- buying_power_model = position_group.buying_power_model
- if not isinstance(buying_power_model, OptionStrategyPositionGroupBuyingPowerModel):
- raise Exception("Expected position group buying power model type: OptionStrategyPositionGroupBuyingPowerModel. "
- f"Actual: {type(position_group.buying_power_model).__name__}")
-
- self.assert_strategy_position_group(position_group, self._option_symbol)
-
- # Now we should be able to close the position
- self.liquidate_strategy()
-
- # We can quit now, no more testing required
- self.quit()
-
- def on_end_of_algorithm(self):
- if self.portfolio.invested:
- raise Exception("Expected no holdings at end of algorithm")
-
- orders_count = len(list(self.transactions.get_orders(lambda order: order.status == OrderStatus.FILLED)))
- if orders_count != self.expected_orders_count():
- raise Exception(f"Expected {self.expected_orders_count()} orders to have been submitted and filled, "
- f"half for buying the strategy and the other half for the liquidation. Actual {orders_count}")
-
- def expected_orders_count(self) -> int:
- raise NotImplementedError("ExpectedOrdersCount method is not implemented")
-
- def trade_strategy(self, chain: OptionChain, option_symbol: Symbol) -> None:
- raise NotImplementedError("TradeStrategy method is not implemented")
-
- def assert_strategy_position_group(self, position_group: IPositionGroup, option_symbol: Symbol) -> None:
- raise NotImplementedError("AssertStrategyPositionGroup method is not implemented")
-
- def liquidate_strategy(self) -> None:
- raise NotImplementedError("LiquidateStrategy method is not implemented")
diff --git a/fincept-qt/scripts/strategies/OptionUniverseFilterGreeksRegressionAlgorithm.py b/fincept-qt/scripts/strategies/OptionUniverseFilterGreeksRegressionAlgorithm.py
deleted file mode 100644
index 79308ccc1..000000000
--- a/fincept-qt/scripts/strategies/OptionUniverseFilterGreeksRegressionAlgorithm.py
+++ /dev/null
@@ -1,89 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-876722D3
-# Category: Options
-# Description: Regression algorithm demonstrating the option universe filter by greeks and other options data feature
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Regression algorithm demonstrating the option universe filter by greeks and other options data feature
-### </summary>
-class OptionUniverseFilterGreeksRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2015, 12, 24)
- self.set_end_date(2015, 12, 24)
- self.set_cash(100000)
-
- underlying_ticker = "GOOG"
- self.add_equity(underlying_ticker)
- option = self.add_option(underlying_ticker)
- self.option_symbol = option.symbol
-
- self._min_delta = 0.5
- self._max_delta = 1.5
- self._min_gamma = 0.0001
- self._max_gamma = 0.0006
- self._min_vega = 0.01
- self._max_vega = 1.5
- self._min_theta = -2.0
- self._max_theta = -0.5
- self._min_rho = 0.5
- self._max_rho = 3.0
- self._min_iv = 1.0
- self._max_iv = 3.0
- self._min_open_interest = 100
- self._max_open_interest = 500
-
- option.set_filter(self.main_filter)
- self.option_chain_received = False
-
- def main_filter(self, universe: OptionFilterUniverse) -> OptionFilterUniverse:
- total_contracts = len(list(universe))
-
- filtered_universe = self.option_filter(universe)
- filtered_contracts = len(list(filtered_universe))
-
- if filtered_contracts == total_contracts:
- raise RegressionTestException(f"Expected filtered universe to have less contracts than original universe. "
- f"Filtered contracts count ({filtered_contracts}) is equal to total contracts count ({total_contracts})")
-
- return filtered_universe
-
- def option_filter(self, universe: OptionFilterUniverse) -> OptionFilterUniverse:
- # Contracts can be filtered by greeks, implied volatility, open interest:
- return universe \
- .delta(self._min_delta, self._max_delta) \
- .gamma(self._min_gamma, self._max_gamma) \
- .vega(self._min_vega, self._max_vega) \
- .theta(self._min_theta, self._max_theta) \
- .rho(self._min_rho, self._max_rho) \
- .implied_volatility(self._min_iv, self._max_iv) \
- .open_interest(self._min_open_interest, self._max_open_interest)
-
- # Note: there are also shortcuts for these filter methods:
- '''
- return universe \
- .d(self._min_delta, self._max_delta) \
- .g(self._min_gamma, self._max_gamma) \
- .v(self._min_vega, self._max_vega) \
- .t(self._min_theta, self._max_theta) \
- .r(self._min_rho, self._max_rho) \
- .iv(self._min_iv, self._max_iv) \
- .oi(self._min_open_interest, self._max_open_interest)
- '''
-
- def on_data(self, slice: Slice) -> None:
- chain = slice.option_chains.get(self.option_symbol)
- if chain and len(chain.contracts) > 0:
- self.option_chain_received = True
-
- def on_end_of_algorithm(self) -> None:
- if not self.option_chain_received:
- raise RegressionTestException("Option chain was not received.")
diff --git a/fincept-qt/scripts/strategies/OptionUniverseFilterGreeksShortcutsRegressionAlgorithm.py b/fincept-qt/scripts/strategies/OptionUniverseFilterGreeksShortcutsRegressionAlgorithm.py
deleted file mode 100644
index 848053e79..000000000
--- a/fincept-qt/scripts/strategies/OptionUniverseFilterGreeksShortcutsRegressionAlgorithm.py
+++ /dev/null
@@ -1,30 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-AED01B14
-# Category: Options
-# Description: Regression algorithm demonstrating the option universe filter by greeks and other options data feature
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-from OptionUniverseFilterGreeksRegressionAlgorithm import OptionUniverseFilterGreeksRegressionAlgorithm
-
-### <summary>
-### Regression algorithm demonstrating the option universe filter by greeks and other options data feature
-### </summary>
-class OptionUniverseFilterGreeksShortcutsRegressionAlgorithm(OptionUniverseFilterGreeksRegressionAlgorithm):
-
- def option_filter(self, universe: OptionFilterUniverse) -> OptionFilterUniverse:
- # Contracts can be filtered by greeks, implied volatility, open interest:
- return universe \
- .d(self._min_delta, self._max_delta) \
- .g(self._min_gamma, self._max_gamma) \
- .v(self._min_vega, self._max_vega) \
- .t(self._min_theta, self._max_theta) \
- .r(self._min_rho, self._max_rho) \
- .iv(self._min_iv, self._max_iv) \
- .oi(self._min_open_interest, self._max_open_interest)
diff --git a/fincept-qt/scripts/strategies/OptionUniverseFilterOptionsDataRegressionAlgorithm.py b/fincept-qt/scripts/strategies/OptionUniverseFilterOptionsDataRegressionAlgorithm.py
deleted file mode 100644
index 569414844..000000000
--- a/fincept-qt/scripts/strategies/OptionUniverseFilterOptionsDataRegressionAlgorithm.py
+++ /dev/null
@@ -1,51 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-62274EA6
-# Category: Options
-# Description: Regression algorithm demonstrating the option universe filter feature that allows accessing the option universe data,...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-from OptionUniverseFilterGreeksRegressionAlgorithm import OptionUniverseFilterGreeksRegressionAlgorithm
-
-### <summary>
-### Regression algorithm demonstrating the option universe filter feature that allows accessing the option universe data,
-### including greeks, open interest and implied volatility, and filtering the contracts based on this data.
-### </summary>
-class OptionUniverseFilterOptionsDataRegressionAlgorithm(OptionUniverseFilterGreeksRegressionAlgorithm):
-
- def option_filter(self, universe: OptionFilterUniverse) -> OptionFilterUniverse:
- # The filter used for the option security will be equivalent to the following commented one below,
- # but it is more flexible and allows for more complex filtering:
-
- '''
- return universe \
- .delta(self._min_delta, self._max_delta) \
- .gamma(self._min_gamma, self._max_gamma) \
- .vega(self._min_vega, self._max_vega) \
- .theta(self._min_theta, self._max_theta) \
- .rho(self._min_rho, self._max_rho) \
- .implied_volatility(self._min_iv, self._max_iv) \
- .open_interest(self._min_open_interest, self._max_open_interest)
- '''
-
- # These contracts list will already be filtered by the strikes and expirations,
- # since those filters where applied before this one.
- return universe \
- .contracts(lambda contracts: [
- contract for contract in contracts
- # Can access the contract data here and do some filtering based on it is needed.
- # More complex math can be done here for filtering, but will be simple here for demonstration sake:
- if (contract.Greeks.Delta > self._min_delta and contract.Greeks.Delta < self._max_delta and
- contract.Greeks.Gamma > self._min_gamma and contract.Greeks.Gamma < self._max_gamma and
- contract.Greeks.Vega > self._min_vega and contract.Greeks.Vega < self._max_vega and
- contract.Greeks.Theta > self._min_theta and contract.Greeks.Theta < self._max_theta and
- contract.Greeks.Rho > self._min_rho and contract.Greeks.Rho < self._max_rho and
- contract.ImpliedVolatility > self._min_iv and contract.ImpliedVolatility < self._max_iv and
- contract.OpenInterest > self._min_open_interest and contract.OpenInterest < self._max_open_interest)
- ])
diff --git a/fincept-qt/scripts/strategies/OptionUniverseHistoryRegressionAlgorithm.py b/fincept-qt/scripts/strategies/OptionUniverseHistoryRegressionAlgorithm.py
deleted file mode 100644
index fb60576e7..000000000
--- a/fincept-qt/scripts/strategies/OptionUniverseHistoryRegressionAlgorithm.py
+++ /dev/null
@@ -1,45 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-61D659F8
-# Category: Options
-# Description: Regression algorithm testing history requests for <see cref="OptionUniverse"/> type work as expected and return the s...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Regression algorithm testing history requests for <see cref="OptionUniverse"/> type work as expected
-### and return the same data as the option chain provider.
-### </summary>
-class OptionUniverseHistoryRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2015, 12, 25)
- self.set_end_date(2015, 12, 25)
-
- option = self.add_option("GOOG").symbol
-
- historical_options_data_df = self.history(option, 3, flatten=True)
-
- # Level 0 of the multi-index is the date, we expect 3 dates, 3 option chains
- if historical_options_data_df.index.levshape[0] != 3:
- raise RegressionTestException(f"Expected 3 option chains from history request, but got {historical_options_data_df.index.levshape[1]}")
-
- for date in historical_options_data_df.index.levels[0]:
- expected_chain = list(self.option_chain_provider.get_option_contract_list(option, date))
- expected_chain_count = len(expected_chain)
-
- actual_chain = historical_options_data_df.loc[date]
- actual_chain_count = len(actual_chain)
-
- if expected_chain_count != actual_chain_count:
- raise RegressionTestException(f"Expected {expected_chain_count} options in chain on {date}, but got {actual_chain_count}")
-
- for i, symbol in enumerate(actual_chain.index):
- expected_symbol = expected_chain[i]
- if symbol != expected_symbol:
- raise RegressionTestException(f"Expected symbol {expected_symbol} at index {i} on {date}, but got {symbol}")
diff --git a/fincept-qt/scripts/strategies/OrderTicketAssignmentDemoAlgorithm.py b/fincept-qt/scripts/strategies/OrderTicketAssignmentDemoAlgorithm.py
deleted file mode 100644
index 29a1db6f1..000000000
--- a/fincept-qt/scripts/strategies/OrderTicketAssignmentDemoAlgorithm.py
+++ /dev/null
@@ -1,51 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-D1943028
-# Category: General Strategy
-# Description: Demonstration on how to access order tickets right after placing an order
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from datetime import timedelta
-from AlgorithmImports import *
-
-### <summary>
-### Demonstration on how to access order tickets right after placing an order.
-### </summary>
-class OrderTicketAssignmentDemoAlgorithm(QCAlgorithm):
- '''Demonstration on how to access order tickets right after placing an order.'''
- def initialize(self):
- self.set_start_date(2013, 10, 7)
- self.set_end_date(2013, 10, 11)
- self.set_cash(100000)
-
- self._symbol = self.add_equity("SPY").symbol
-
- self.trade_count = 0
- self.consolidate(self._symbol, timedelta(hours=1), self.hour_consolidator)
-
- def hour_consolidator(self, bar: TradeBar):
- # Reset self.ticket to None on each new bar
- self.ticket = None
- self.ticket = self.market_order(self._symbol, 1, asynchronous=True)
- self.debug(f"{self.time}: Buy: Price {bar.price}, order_id: {self.ticket.order_id}")
- self.trade_count += 1
-
- def on_order_event(self, order_event: OrderEvent):
- # We cannot access self.ticket directly because it is assigned asynchronously:
- # this order event could be triggered before self.ticket is assigned.
- ticket = order_event.ticket
- if ticket is None:
- raise Exception("Expected order ticket in order event to not be null")
- if order_event.status == OrderStatus.SUBMITTED and self.ticket is not None:
- raise Exception("Field self.ticket not expected no be assigned on the first order event")
-
- self.debug(ticket.to_string())
-
- def on_end_of_algorithm(self):
- # Just checking that orders were placed
- if not self.portfolio.invested or self.trade_count != self.transactions.orders_count:
- raise Exception(f"Expected the portfolio to have holdings and to have {self.trade_count} trades, but had {self.transactions.orders_count}")
diff --git a/fincept-qt/scripts/strategies/OrderTicketDemoAlgorithm.py b/fincept-qt/scripts/strategies/OrderTicketDemoAlgorithm.py
deleted file mode 100644
index a8fdbe293..000000000
--- a/fincept-qt/scripts/strategies/OrderTicketDemoAlgorithm.py
+++ /dev/null
@@ -1,464 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-4AD7FFC0
-# Category: General Strategy
-# Description: In this algorithm we submit/update/cancel each order type
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### In this algorithm we submit/update/cancel each order type
-### </summary>
-### <meta name="tag" content="trading and orders" />
-### <meta name="tag" content="placing orders" />
-### <meta name="tag" content="managing orders" />
-### <meta name="tag" content="order tickets" />
-### <meta name="tag" content="updating orders" />
-class OrderTicketDemoAlgorithm(QCAlgorithm):
- '''In this algorithm we submit/update/cancel each order type'''
- def initialize(self):
- '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
-
- self.set_start_date(2013,10,7) #Set Start Date
- self.set_end_date(2013,10,11) #Set End Date
- self.set_cash(100000) #Set Strategy Cash
- # Fincept Terminal Strategy Engine - Symbol Configuration
- equity = self.add_equity("SPY")
- self.spy = equity.symbol
-
- self.__open_market_on_open_orders = []
- self.__open_market_on_close_orders = []
- self.__open_limit_orders = []
- self.__open_stop_market_orders = []
- self.__open_stop_limit_orders = []
- self.__open_trailing_stop_orders = []
-
-
- def on_data(self, data):
- '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.'''
- # MARKET ORDERS
- self.market_orders()
-
- # LIMIT ORDERS
- self.limit_orders()
-
- # STOP MARKET ORDERS
- self.stop_market_orders()
-
- # STOP LIMIT ORDERS
- self.stop_limit_orders()
-
- # TRAILING STOP ORDERS
- self.trailing_stop_orders()
-
- # MARKET ON OPEN ORDERS
- self.market_on_open_orders()
-
- # MARKET ON CLOSE ORDERS
- self.market_on_close_orders()
-
-
- def market_orders(self):
- ''' MarketOrders are the only orders that are processed synchronously by default, so
- they'll fill by the next line of code. This behavior equally applies to live mode.
- You can opt out of this behavior by specifying the 'asynchronous' parameter as True.'''
- if self.time_is(7, 9, 31):
- self.log("Submitting MarketOrder")
-
- # submit a market order to buy 10 shares, this function returns an OrderTicket object
- # we submit the order with asynchronous = False, so it block until it is filled
- new_ticket = self.market_order(self.spy, 10, asynchronous = False)
- if new_ticket.status != OrderStatus.FILLED:
- self.log("Synchronous market order was not filled synchronously!")
- self.quit()
-
- # we can also submit the ticket asynchronously. In a backtest, we'll still perform the fill
- # before the next time events for your algorithm. here we'll submit the order asynchronously
- # and try to cancel it, sometimes it will, sometimes it will be filled first.
- new_ticket = self.market_order(self.spy, 10, asynchronous = True)
- response = new_ticket.cancel("Attempt to cancel async order")
- if response.is_success:
- self.log("Successfully canceled async market order: {0}".format(new_ticket.order_id))
- else:
- self.log("Unable to cancel async market order: {0}".format(response.error_code))
-
-
- def limit_orders(self):
- '''LimitOrders are always processed asynchronously. Limit orders are used to
- set 'good' entry points for an order. For example, you may wish to go
- long a stock, but want a good price, so can place a LimitOrder to buy with
- a limit price below the current market price. Likewise the opposite is True
- when selling, you can place a LimitOrder to sell with a limit price above the
- current market price to get a better sale price.
- You can submit requests to update or cancel the LimitOrder at any time.
- The 'LimitPrice' for an order can be retrieved from the ticket using the
- OrderTicket.get(OrderField) method, for example:
- Code:
- current_limit_price = order_ticket.get(OrderField.LIMIT_PRICE)'''
- if self.time_is(7, 12, 0):
- self.log("Submitting LimitOrder")
-
- # submit a limit order to buy 10 shares at .1% below the bar's close
- close = self.securities[self.spy.value].close
- new_ticket = self.limit_order(self.spy, 10, close * .999)
- self.__open_limit_orders.append(new_ticket)
-
- # submit another limit order to sell 10 shares at .1% above the bar's close
- new_ticket = self.limit_order(self.spy, -10, close * 1.001)
- self.__open_limit_orders.append(new_ticket)
-
- # when we submitted new limit orders we placed them into this list,
- # so while there's two entries they're still open and need processing
- if len(self.__open_limit_orders) == 2:
- open_orders = self.__open_limit_orders
-
- # check if either is filled and cancel the other
- long_order = open_orders[0]
- short_order = open_orders[1]
- if self.check_pair_orders_for_fills(long_order, short_order):
- self.__open_limit_orders = []
- return
-
- # if neither order has filled, bring in the limits by a penny
- new_long_limit = long_order.get(OrderField.LIMIT_PRICE) + 0.01
- new_short_limit = short_order.get(OrderField.LIMIT_PRICE) - 0.01
- self.log("Updating limits - Long: {0:.2f} Short: {1:.2f}".format(new_long_limit, new_short_limit))
-
- update_order_fields = UpdateOrderFields()
- update_order_fields.limit_price = new_long_limit
- update_order_fields.tag = "Update #{0}".format(len(long_order.update_requests) + 1)
- long_order.update(update_order_fields)
-
- update_order_fields = UpdateOrderFields()
- update_order_fields.limit_price = new_short_limit
- update_order_fields.tag = "Update #{0}".format(len(short_order.update_requests) + 1)
- short_order.update(update_order_fields)
-
-
- def stop_market_orders(self):
- '''StopMarketOrders work in the opposite way that limit orders do.
- When placing a long trade, the stop price must be above current
- market price. In this way it's a 'stop loss' for a short trade.
- When placing a short trade, the stop price must be below current
- market price. In this way it's a 'stop loss' for a long trade.
- You can submit requests to update or cancel the StopMarketOrder at any time.
- The 'StopPrice' for an order can be retrieved from the ticket using the
- OrderTicket.get(OrderField) method, for example:
- Code:
- current_stop_price = order_ticket.get(OrderField.STOP_PRICE)'''
- if self.time_is(7, 12 + 4, 0):
- self.log("Submitting StopMarketOrder")
-
- # a long stop is triggered when the price rises above the value
- # so we'll set a long stop .25% above the current bar's close
- close = self.securities[self.spy.value].close
- new_ticket = self.stop_market_order(self.spy, 10, close * 1.0025)
- self.__open_stop_market_orders.append(new_ticket)
-
- # a short stop is triggered when the price falls below the value
- # so we'll set a short stop .25% below the current bar's close
- new_ticket = self.stop_market_order(self.spy, -10, close * .9975)
- self.__open_stop_market_orders.append(new_ticket)
-
- # when we submitted new stop market orders we placed them into this list,
- # so while there's two entries they're still open and need processing
- if len(self.__open_stop_market_orders) == 2:
- # check if either is filled and cancel the other
- long_order = self.__open_stop_market_orders[0]
- short_order = self.__open_stop_market_orders[1]
- if self.check_pair_orders_for_fills(long_order, short_order):
- self.__open_stop_market_orders = []
- return
-
- # if neither order has filled, bring in the stops by a penny
- new_long_stop = long_order.get(OrderField.STOP_PRICE) - 0.01
- new_short_stop = short_order.get(OrderField.STOP_PRICE) + 0.01
- self.log("Updating stops - Long: {0:.2f} Short: {1:.2f}".format(new_long_stop, new_short_stop))
-
- update_order_fields = UpdateOrderFields()
- update_order_fields.stop_price = new_long_stop
- update_order_fields.tag = "Update #{0}".format(len(long_order.update_requests) + 1)
- long_order.update(update_order_fields)
-
- update_order_fields = UpdateOrderFields()
- update_order_fields.stop_price = new_short_stop
- update_order_fields.tag = "Update #{0}".format(len(short_order.update_requests) + 1)
- short_order.update(update_order_fields)
- self.log("Updated price - Long: {0} Short: {1}".format(long_order.get(OrderField.STOP_PRICE), short_order.get(OrderField.STOP_PRICE)))
-
-
- def stop_limit_orders(self):
- '''StopLimitOrders work as a combined stop and limit order. First, the
- price must pass the stop price in the same way a StopMarketOrder works,
- but then we're also guaranteed a fill price at least as good as the
- limit price. This order type can be beneficial in gap down scenarios
- where a StopMarketOrder would have triggered and given the not as beneficial
- gapped down price, whereas the StopLimitOrder could protect you from
- getting the gapped down price through prudent placement of the limit price.
- You can submit requests to update or cancel the StopLimitOrder at any time.
- The 'StopPrice' or 'LimitPrice' for an order can be retrieved from the ticket
- using the OrderTicket.get(OrderField) method, for example:
- Code:
- current_stop_price = order_ticket.get(OrderField.STOP_PRICE)
- current_limit_price = order_ticket.get(OrderField.LIMIT_PRICE)'''
- if self.time_is(8, 12, 1):
- self.log("Submitting StopLimitOrder")
-
- # a long stop is triggered when the price rises above the
- # value so we'll set a long stop .25% above the current bar's
- # close now we'll also be setting a limit, this means we are
- # guaranteed to get at least the limit price for our fills,
- # so make the limit price a little higher than the stop price
-
- close = self.securities[self.spy.value].close
- new_ticket = self.stop_limit_order(self.spy, 10, close * 1.001, close - 0.03)
- self.__open_stop_limit_orders.append(new_ticket)
-
- # a short stop is triggered when the price falls below the
- # value so we'll set a short stop .25% below the current bar's
- # close now we'll also be setting a limit, this means we are
- # guaranteed to get at least the limit price for our fills,
- # so make the limit price a little softer than the stop price
-
- new_ticket = self.stop_limit_order(self.spy, -10, close * .999, close + 0.03)
- self.__open_stop_limit_orders.append(new_ticket)
-
- # when we submitted new stop limit orders we placed them into this list,
- # so while there's two entries they're still open and need processing
- if len(self.__open_stop_limit_orders) == 2:
- long_order = self.__open_stop_limit_orders[0]
- short_order = self.__open_stop_limit_orders[1]
- if self.check_pair_orders_for_fills(long_order, short_order):
- self.__open_stop_limit_orders = []
- return
-
- # if neither order has filled, bring in the stops/limits in by a penny
-
- new_long_stop = long_order.get(OrderField.STOP_PRICE) - 0.01
- new_long_limit = long_order.get(OrderField.LIMIT_PRICE) + 0.01
- new_short_stop = short_order.get(OrderField.STOP_PRICE) + 0.01
- new_short_limit = short_order.get(OrderField.LIMIT_PRICE) - 0.01
- self.log("Updating stops - Long: {0:.2f} Short: {1:.2f}".format(new_long_stop, new_short_stop))
- self.log("Updating limits - Long: {0:.2f} Short: {1:.2f}".format(new_long_limit, new_short_limit))
-
- update_order_fields = UpdateOrderFields()
- update_order_fields.stop_price = new_long_stop
- update_order_fields.limit_price = new_long_limit
- update_order_fields.tag = "Update #{0}".format(len(long_order.update_requests) + 1)
- long_order.update(update_order_fields)
-
- update_order_fields = UpdateOrderFields()
- update_order_fields.stop_price = new_short_stop
- update_order_fields.limit_price = new_short_limit
- update_order_fields.tag = "Update #{0}".format(len(short_order.update_requests) + 1)
- short_order.update(update_order_fields)
-
-
- def trailing_stop_orders(self):
- '''TrailingStopOrders work the same way as StopMarketOrders, except
- their stop price is adjusted to a certain amount, keeping it a certain
- fixed distance from/to the market price, depending on the order direction,
- which allows to preserve profits and protecting against losses.
- The stop price can be accessed just as with StopMarketOrders, and
- the trailing amount can be accessed with the OrderTicket.get(OrderField), for example:
- Code:
- current_trailing_amount = order_ticket.get(OrderField.STOP_PRICE)
- trailing_as_percentage = order_ticket.get[bool](OrderField.TRAILING_AS_PERCENTAGE)'''
- if self.time_is(7, 12, 0):
- self.log("Submitting TrailingStopOrder")
-
- # a long stop is triggered when the price rises above the
- # value so we'll set a long stop .25% above the current bar's
-
- close = self.securities[self.spy.value].close
- stop_price = close * 1.0025
- new_ticket = self.trailing_stop_order(self.spy, 10, stop_price, trailing_amount=0.0025, trailing_as_percentage=True)
- self.__open_trailing_stop_orders.append(new_ticket)
-
- # a short stop is triggered when the price falls below the
- # value so we'll set a short stop .25% below the current bar's
-
- stop_price = close * .9975
- new_ticket = self.trailing_stop_order(self.spy, -10, stop_price, trailing_amount=0.0025, trailing_as_percentage=True)
- self.__open_trailing_stop_orders.append(new_ticket)
-
- # when we submitted new stop market orders we placed them into this list,
- # so while there's two entries they're still open and need processing
- elif len(self.__open_trailing_stop_orders) == 2:
- long_order = self.__open_trailing_stop_orders[0]
- short_order = self.__open_trailing_stop_orders[1]
- if self.check_pair_orders_for_fills(long_order, short_order):
- self.__open_trailing_stop_orders = []
- return
-
- # if neither order has filled in the last 5 minutes, bring in the trailing percentage by 0.01%
- if ((self.utc_time - long_order.time).total_seconds() / 60) % 5 != 0:
- return
-
- long_trailing_percentage = long_order.get(OrderField.TRAILING_AMOUNT)
- new_long_trailing_percentage = max(long_trailing_percentage - 0.0001, 0.0001)
- short_trailing_percentage = short_order.get(OrderField.TRAILING_AMOUNT)
- new_short_trailing_percentage = max(short_trailing_percentage - 0.0001, 0.0001)
- self.log("Updating trailing percentages - Long: {0:.3f} Short: {1:.3f}".format(new_long_trailing_percentage, new_short_trailing_percentage))
-
- update_order_fields = UpdateOrderFields()
- # we could change the quantity, but need to specify it
- #Quantity =
- update_order_fields.trailing_amount = new_long_trailing_percentage
- update_order_fields.tag = "Update #{0}".format(len(long_order.update_requests) + 1)
- long_order.update(update_order_fields)
-
- update_order_fields = UpdateOrderFields()
- update_order_fields.trailing_amount = new_short_trailing_percentage
- update_order_fields.tag = "Update #{0}".format(len(short_order.update_requests) + 1)
- short_order.update(update_order_fields)
-
-
- def market_on_close_orders(self):
- '''MarketOnCloseOrders are always executed at the next market's closing price.
- The only properties that can be updated are the quantity and order tag properties.'''
- if self.time_is(9, 12, 0):
- self.log("Submitting MarketOnCloseOrder")
-
- # open a new position or triple our existing position
- qty = self.portfolio[self.spy.value].quantity
- qty = 100 if qty == 0 else 2*qty
-
- new_ticket = self.market_on_close_order(self.spy, qty)
- self.__open_market_on_close_orders.append(new_ticket)
-
- if len(self.__open_market_on_close_orders) == 1 and self.time.minute == 59:
- ticket = self.__open_market_on_close_orders[0]
- # check for fills
- if ticket.status == OrderStatus.FILLED:
- self.__open_market_on_close_orders = []
- return
-
- quantity = ticket.quantity + 1
- self.log("Updating quantity - New Quantity: {0}".format(quantity))
-
- # we can update the quantity and tag
- update_order_fields = UpdateOrderFields()
- update_order_fields.quantity = quantity
- update_order_fields.tag = "Update #{0}".format(len(ticket.update_requests) + 1)
- ticket.update(update_order_fields)
-
- if self.time_is(self.end_date.day, 12 + 3, 45):
- self.log("Submitting MarketOnCloseOrder to liquidate end of algorithm")
- self.market_on_close_order(self.spy, -self.portfolio[self.spy.value].quantity, "Liquidate end of algorithm")
-
-
- def market_on_open_orders(self):
- '''MarketOnOpenOrders are always executed at the next
- market's opening price. The only properties that can
- be updated are the quantity and order tag properties.'''
- if self.time_is(8, 12 + 2, 0):
- self.log("Submitting MarketOnOpenOrder")
-
- # its EOD, let's submit a market on open order to short even more!
- new_ticket = self.market_on_open_order(self.spy, 50)
- self.__open_market_on_open_orders.append(new_ticket)
-
- if len(self.__open_market_on_open_orders) == 1 and self.time.minute == 59:
- ticket = self.__open_market_on_open_orders[0]
-
- # check for fills
- if ticket.status == OrderStatus.FILLED:
- self.__open_market_on_open_orders = []
- return
-
- quantity = ticket.quantity + 1
- self.log("Updating quantity - New Quantity: {0}".format(quantity))
-
- # we can update the quantity and tag
- update_order_fields = UpdateOrderFields()
- update_order_fields.quantity = quantity
- update_order_fields.tag = "Update #{0}".format(len(ticket.update_requests) + 1)
- ticket.update(update_order_fields)
-
-
- def on_order_event(self, order_event):
- order = self.transactions.get_order_by_id(order_event.order_id)
- self.log("{0}: {1}: {2}".format(self.time, order.type, order_event))
-
- if order_event.quantity == 0:
- raise Exception("OrderEvent quantity is Not expected to be 0, it should hold the current order Quantity")
-
- if order_event.quantity != order.quantity:
- raise Exception("OrderEvent quantity should hold the current order Quantity")
-
- if (type(order) is LimitOrder and order_event.limit_price == 0 or
- type(order) is StopLimitOrder and order_event.limit_price == 0):
- raise Exception("OrderEvent LimitPrice is Not expected to be 0 for LimitOrder and StopLimitOrder")
-
- if type(order) is StopMarketOrder and order_event.stop_price == 0:
- raise Exception("OrderEvent StopPrice is Not expected to be 0 for StopMarketOrder")
-
- # We can access the order ticket from the order event
- if order_event.ticket is None:
- raise Exception("OrderEvent Ticket was not set")
- if order_event.order_id != order_event.ticket.order_id:
- raise Exception("OrderEvent.ORDER_ID and order_event.ticket.order_id do not match")
-
- def check_pair_orders_for_fills(self, long_order, short_order):
- if long_order.status == OrderStatus.FILLED:
- self.log("{0}: Cancelling short order, long order is filled.".format(short_order.order_type))
- short_order.cancel("Long filled.")
- return True
-
- if short_order.status == OrderStatus.FILLED:
- self.log("{0}: Cancelling long order, short order is filled.".format(long_order.order_type))
- long_order.cancel("Short filled")
- return True
-
- return False
-
-
- def time_is(self, day, hour, minute):
- return self.time.day == day and self.time.hour == hour and self.time.minute == minute
-
- def on_end_of_algorithm(self):
- basic_order_ticket_filter = lambda x: x.symbol == self.spy
-
- filled_orders = self.transactions.get_orders(lambda x: x.status == OrderStatus.FILLED)
- order_tickets = self.transactions.get_order_tickets(basic_order_ticket_filter)
- open_orders = self.transactions.get_open_orders(lambda x: x.symbol == self.spy)
- open_order_tickets = self.transactions.get_open_order_tickets(basic_order_ticket_filter)
- remaining_open_orders = self.transactions.get_open_orders_remaining_quantity(basic_order_ticket_filter)
-
- # The type returned by self.transactions.get_orders() is iterable and not a list
- # that's why we use sum() to get the size of the iterable object type
- filled_orders_size = sum(1 for order in filled_orders)
- order_tickets_size = sum(1 for ticket in order_tickets)
- open_order_tickets_size = sum(1 for ticket in open_order_tickets)
-
- assert(filled_orders_size == 9 and order_tickets_size == 12), "There were expected 9 filled orders and 12 order tickets"
- assert(not (len(open_orders) or open_order_tickets_size)), "No open orders or tickets were expected"
- assert(not remaining_open_orders), "No remaining quantity to be filled from open orders was expected"
-
- spy_open_orders = self.transactions.get_open_orders(self.spy)
- spy_open_order_tickets = self.transactions.get_open_order_tickets(self.spy)
- spy_open_order_tickets_size = sum(1 for tickets in spy_open_order_tickets)
- spy_open_orders_remaining_quantity = self.transactions.get_open_orders_remaining_quantity(self.spy)
-
- assert(not (len(spy_open_orders) or spy_open_order_tickets_size)), "No open orders or tickets were expected"
- assert(not spy_open_orders_remaining_quantity), "No remaining quantity to be filled from open orders was expected"
-
- default_orders = self.transactions.get_orders()
- default_order_tickets = self.transactions.get_order_tickets()
- default_open_orders = self.transactions.get_open_orders()
- default_open_order_tickets = self.transactions.get_open_order_tickets()
- default_open_orders_remaining = self.transactions.get_open_orders_remaining_quantity()
-
- default_orders_size = sum(1 for order in default_orders)
- default_order_tickets_size = sum(1 for ticket in default_order_tickets)
- default_open_order_tickets_size = sum(1 for ticket in default_open_order_tickets)
-
- assert(default_orders_size == 12 and default_order_tickets_size == 12), "There were expected 12 orders and 12 order tickets"
- assert(not (len(default_open_orders) or default_open_order_tickets_size)), "No open orders or tickets were expected"
- assert(not default_open_orders_remaining), "No remaining quantity to be filled from open orders was expected"
diff --git a/fincept-qt/scripts/strategies/PEP8StyleBasicAlgorithm.py b/fincept-qt/scripts/strategies/PEP8StyleBasicAlgorithm.py
deleted file mode 100644
index c6ba011b2..000000000
--- a/fincept-qt/scripts/strategies/PEP8StyleBasicAlgorithm.py
+++ /dev/null
@@ -1,46 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-73AEBCB1
-# Category: General Strategy
-# Description: P E P8 Style Basic Algorithm
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-class PEP8StyleBasicAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2013,10, 7)
- self.set_end_date(2013,10,11)
- self.set_cash(100000)
-
- self.spy = self.add_equity("SPY", Resolution.MINUTE, extended_market_hours=False, fill_forward=True).symbol
-
- # Test accessing a constant (QCAlgorithm.MaxTagsCount)
- self.debug("MaxTagsCount: " + str(self.MAX_TAGS_COUNT))
-
- def on_data(self, slice):
- if not self.portfolio.invested:
- self.set_holdings(self.spy, 1)
- self.debug("Purchased Stock")
-
- def on_order_event(self, order_event):
- self.log(f"{self.time} :: {order_event}")
-
- def on_end_of_algorithm(self):
- self.log("Algorithm ended!")
-
- if not self.portfolio.invested:
- raise Exception("Algorithm should have been invested at the end of the algorithm")
-
- # let's do some logging to do more pep8 style testing
- self.log("-----------------------------------------------------------------------------------------")
- self.log(f"{self.spy.value} last price: {self.securities[self.spy].price}")
- self.log(f"{self.spy.value} holdings: "
- f"{self.securities[self.spy].holdings.quantity}@{self.securities[self.spy].holdings.price}="
- f"{self.securities[self.spy].holdings.holdings_value}")
- self.log("-----------------------------------------------------------------------------------------")
diff --git a/fincept-qt/scripts/strategies/PandasDataFrameFromMultipleTickTypeTickHistoryRegressionAlgorithm.py b/fincept-qt/scripts/strategies/PandasDataFrameFromMultipleTickTypeTickHistoryRegressionAlgorithm.py
deleted file mode 100644
index 99b526822..000000000
--- a/fincept-qt/scripts/strategies/PandasDataFrameFromMultipleTickTypeTickHistoryRegressionAlgorithm.py
+++ /dev/null
@@ -1,42 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-69B21AF4
-# Category: Regression Test
-# Description: Regression algorithm for asserting that tick history that includes multiple tick types (trade, quote) is correctly co...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Regression algorithm for asserting that tick history that includes multiple tick types (trade, quote) is correctly converted to a pandas
-### dataframe without raising exceptions. The main exception in this case was a "non-unique multi-index" error due to trades adn quote ticks with
-### duplicated timestamps.
-### </summary>
-class PandasDataFrameFromMultipleTickTypeTickHistoryRegressionAlgorithm(QCAlgorithm):
- def initialize(self):
- self.set_start_date(2013, 10, 8)
- self.set_end_date(2013, 10, 8)
-
- spy = self.add_equity("SPY", Resolution.MINUTE).symbol
-
- subscriptions = [x for x in self.subscription_manager.subscriptions if x.symbol == spy]
- if len(subscriptions) != 2:
- raise Exception(f"Expected 2 subscriptions, but found {len(subscriptions)}")
-
- history = pd.DataFrame()
- try:
- history = self.history(Tick, spy, timedelta(days=1), Resolution.TICK)
- except Exception as e:
- raise Exception(f"History call failed: {e}")
-
- if history.shape[0] == 0:
- raise Exception("SPY tick history is empty")
-
- if not np.array_equal(history.columns.to_numpy(), ['askprice', 'asksize', 'bidprice', 'bidsize', 'exchange', 'lastprice', 'quantity']):
- raise Exception("Unexpected columns in SPY tick history")
-
- self.quit()
diff --git a/fincept-qt/scripts/strategies/PandasDataFrameHistoryAlgorithm.py b/fincept-qt/scripts/strategies/PandasDataFrameHistoryAlgorithm.py
deleted file mode 100644
index a72d02494..000000000
--- a/fincept-qt/scripts/strategies/PandasDataFrameHistoryAlgorithm.py
+++ /dev/null
@@ -1,149 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-C16FBA05
-# Category: Historical Data
-# Description: This algorithm demonstrates the various ways to handle History pandas DataFrame
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### This algorithm demonstrates the various ways to handle History pandas DataFrame
-### </summary>
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="history and warm up" />
-### <meta name="tag" content="history" />
-### <meta name="tag" content="warm up" />
-class PandasDataFrameHistoryAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2014, 6, 9) # Set Start Date
- self.set_end_date(2014, 6, 9) # Set End Date
-
- self.spy = self.add_equity("SPY", Resolution.DAILY).symbol
- self.eur = self.add_forex("EURUSD", Resolution.DAILY).symbol
-
- aapl = self.add_equity("AAPL", Resolution.MINUTE).symbol
- self.option = Symbol.create_option(aapl, Market.USA, OptionStyle.AMERICAN, OptionRight.CALL, 750, datetime(2014, 10, 18))
- self.add_option_contract(self.option)
-
- sp1 = self.add_data(QuandlFuture,"CHRIS/CME_SP1", Resolution.DAILY)
- sp1.exchange = EquityExchange()
- self.sp1 = sp1.symbol
-
- self.add_universe(self.coarse_selection)
-
- def coarse_selection(self, coarse):
- if self.portfolio.invested:
- return Universe.UNCHANGED
-
- selected = [x.symbol for x in coarse if x.symbol.value in ["AAA", "AIG", "BAC"]]
- if len(selected) == 0:
- return Universe.UNCHANGED
-
- universe_history = self.history(selected, 10, Resolution.DAILY)
- for symbol in selected:
- self.assert_history_index(universe_history, "close", 10, "", symbol)
-
- return selected
-
-
- def on_data(self, data):
- if self.portfolio.invested:
- return
-
- # we can get history in initialize to set up indicators and such
- self.spy_daily_sma = SimpleMovingAverage(14)
-
- # get the last calendar year's worth of SPY data at the configured resolution (daily)
- trade_bar_history = self.history(["SPY"], timedelta(365))
- self.assert_history_index(trade_bar_history, "close", 251, "SPY", self.spy)
-
- # get the last calendar year's worth of EURUSD data at the configured resolution (daily)
- quote_bar_history = self.history(["EURUSD"], timedelta(298))
- self.assert_history_index(quote_bar_history, "bidclose", 251, "EURUSD", self.eur)
-
- option_history = self.history([self.option], timedelta(3))
- option_history.index = option_history.index.droplevel(level=[0,1,2])
- self.assert_history_index(option_history, "bidclose", 390, "", self.option)
-
- # get the last calendar year's worth of quandl data at the configured resolution (daily)
- quandl_history = self.history(QuandlFuture, "CHRIS/CME_SP1", timedelta(365))
- self.assert_history_index(quandl_history, "settle", 251, "CHRIS/CME_SP1", self.sp1)
-
- # we can loop over the return value from these functions and we get TradeBars
- # we can use these TradeBars to initialize indicators or perform other math
- self.spy_daily_sma.reset()
- for index, trade_bar in trade_bar_history.loc["SPY"].iterrows():
- self.spy_daily_sma.update(index, trade_bar["close"])
-
- # we can loop over the return values from these functions and we'll get Quandl data
- # this can be used in much the same way as the trade_bar_history above
- self.spy_daily_sma.reset()
- for index, quandl in quandl_history.loc["CHRIS/CME_SP1"].iterrows():
- self.spy_daily_sma.update(index, quandl["settle"])
-
- self.set_holdings(self.eur, 1)
-
- def assert_history_index(self, df, column, expected, ticker, symbol):
-
- if df.empty:
- raise Exception(f"Empty history data frame for {symbol}")
- if column not in df:
- raise Exception(f"Could not unstack df. Columns: {', '.join(df.columns)} | {column}")
-
- value = df.iat[0,0]
- df2 = df.xs(df.index.get_level_values('time')[0], level='time')
- df3 = df[column].unstack(level=0)
-
- try:
-
- # str(Symbol.ID)
- self.assert_history_count(f"df.iloc[0]", df.iloc[0], len(df.columns))
- self.assert_history_count(f"df.loc[str({symbol.id})]", df.loc[str(symbol.id)], expected)
- self.assert_history_count(f"df.xs(str({symbol.id}))", df.xs(str(symbol.id)), expected)
- self.assert_history_count(f"df.at[(str({symbol.id}),), '{column}']", list(df.at[(str(symbol.id),), column]), expected)
- self.assert_history_count(f"df2.loc[str({symbol.id})]", df2.loc[str(symbol.id)], len(df2.columns))
- self.assert_history_count(f"df3[str({symbol.id})]", df3[str(symbol.id)], expected)
- self.assert_history_count(f"df3.get(str({symbol.id}))", df3.get(str(symbol.id)), expected)
-
- # str(Symbol)
- self.assert_history_count(f"df.loc[str({symbol})]", df.loc[str(symbol)], expected)
- self.assert_history_count(f"df.xs(str({symbol}))", df.xs(str(symbol)), expected)
- self.assert_history_count(f"df.at[(str({symbol}),), '{column}']", list(df.at[(str(symbol),), column]), expected)
- self.assert_history_count(f"df2.loc[str({symbol})]", df2.loc[str(symbol)], len(df2.columns))
- self.assert_history_count(f"df3[str({symbol})]", df3[str(symbol)], expected)
- self.assert_history_count(f"df3.get(str({symbol}))", df3.get(str(symbol)), expected)
-
- # str : Symbol.VALUE
- if len(ticker) == 0:
- return
- self.assert_history_count(f"df.loc[{ticker}]", df.loc[ticker], expected)
- self.assert_history_count(f"df.xs({ticker})", df.xs(ticker), expected)
- self.assert_history_count(f"df.at[(ticker,), '{column}']", list(df.at[(ticker,), column]), expected)
- self.assert_history_count(f"df2.loc[{ticker}]", df2.loc[ticker], len(df2.columns))
- self.assert_history_count(f"df3[{ticker}]", df3[ticker], expected)
- self.assert_history_count(f"df3.get({ticker})", df3.get(ticker), expected)
-
- except Exception as e:
- symbols = set(df.index.get_level_values(level='symbol'))
- raise Exception(f"{symbols}, {symbol.id}, {symbol}, {ticker}. {e}")
-
-
- def assert_history_count(self, method_call, trade_bar_history, expected):
- if isinstance(trade_bar_history, list):
- count = len(trade_bar_history)
- else:
- count = len(trade_bar_history.index)
- if count != expected:
- raise Exception(f"{method_call} expected {expected}, but received {count}")
-
-
-class QuandlFuture(PythonQuandl):
- '''Custom quandl data type for setting customized value column name. Value column is used for the primary trading calculations and charting.'''
- def __init__(self):
- self.value_column_name = "Settle"
diff --git a/fincept-qt/scripts/strategies/ParameterizedAlgorithm.py b/fincept-qt/scripts/strategies/ParameterizedAlgorithm.py
deleted file mode 100644
index 05f4780bf..000000000
--- a/fincept-qt/scripts/strategies/ParameterizedAlgorithm.py
+++ /dev/null
@@ -1,51 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-3D4D4FC7
-# Category: General Strategy
-# Description: Demonstration of the parameter system of QuantConnect. Using parameters you can pass the values required into C# algo...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Demonstration of the parameter system of QuantConnect. Using parameters you can pass the values required into C# algorithms for optimization.
-### </summary>
-### <meta name="tag" content="optimization" />
-### <meta name="tag" content="using quantconnect" />
-class ParameterizedAlgorithm(QCAlgorithm):
-
- def initialize(self):
- '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
-
- self.set_start_date(2013, 10, 7) #Set Start Date
- self.set_end_date(2013, 10, 11) #Set End Date
- self.set_cash(100000) #Set Strategy Cash
- # Fincept Terminal Strategy Engine - Symbol Configuration
- self.add_equity("SPY")
-
- # Receive parameters from the Job
- fast_period = self.get_parameter("ema-fast", 100)
- slow_period = self.get_parameter("ema-slow", 200)
-
- self.fast = self.ema("SPY", fast_period)
- self.slow = self.ema("SPY", slow_period)
-
-
- def on_data(self, data):
- '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.'''
-
- # wait for our indicators to ready
- if not self.fast.is_ready or not self.slow.is_ready:
- return
-
- fast = self.fast.current.value
- slow = self.slow.current.value
-
- if fast > slow * 1.001:
- self.set_holdings("SPY", 1)
- elif fast < slow * 0.999:
- self.liquidate("SPY")
diff --git a/fincept-qt/scripts/strategies/PearsonCorrelationPairsTradingAlphaModelFrameworkAlgorithm.py b/fincept-qt/scripts/strategies/PearsonCorrelationPairsTradingAlphaModelFrameworkAlgorithm.py
deleted file mode 100644
index b896682a5..000000000
--- a/fincept-qt/scripts/strategies/PearsonCorrelationPairsTradingAlphaModelFrameworkAlgorithm.py
+++ /dev/null
@@ -1,51 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-6689DBF5
-# Category: Alpha Model
-# Description: Framework algorithm that uses the PearsonCorrelationPairsTradingAlphaModel. This model extendes BasePairsTradingAlpha...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-from Alphas.PearsonCorrelationPairsTradingAlphaModel import PearsonCorrelationPairsTradingAlphaModel
-
-### <summary>
-### Framework algorithm that uses the PearsonCorrelationPairsTradingAlphaModel.
-### This model extendes BasePairsTradingAlphaModel and uses Pearson correlation
-### to rank the pairs trading candidates and use the best candidate to trade.
-### </summary>
-class PearsonCorrelationPairsTradingAlphaModelFrameworkAlgorithm(QCAlgorithm):
- '''Framework algorithm that uses the PearsonCorrelationPairsTradingAlphaModel.
- This model extendes BasePairsTradingAlphaModel and uses Pearson correlation
- to rank the pairs trading candidates and use the best candidate to trade.'''
-
- def initialize(self):
-
- self.set_start_date(2013,10,7)
- self.set_end_date(2013,10,11)
-
- symbols = [Symbol.create(ticker, SecurityType.EQUITY, Market.USA)
- for ticker in ["SPY", "AIG", "BAC", "IBM"]]
-
- # Manually add SPY and AIG when the algorithm starts
- self.set_universe_selection(ManualUniverseSelectionModel(symbols[:2]))
-
- # At midnight, add all securities every day except on the last data
- # With this procedure, the Alpha Model will experience multiple universe changes
- self.add_universe_selection(ScheduledUniverseSelectionModel(
- self.date_rules.every_day(), self.time_rules.midnight,
- lambda dt: symbols if dt.day <= (self.end_date - timedelta(1)).day else []))
-
- self.set_alpha(PearsonCorrelationPairsTradingAlphaModel(252, Resolution.DAILY))
- self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())
- self.set_execution(ImmediateExecutionModel())
- self.set_risk_management(NullRiskManagementModel())
-
- def on_end_of_algorithm(self) -> None:
- # We have removed all securities from the universe. The Alpha Model should remove the consolidator
- consolidator_count = sum(s.consolidators.count for s in self.subscription_manager.subscriptions)
- if consolidator_count > 0:
- raise Exception(f"The number of consolidator should be zero. Actual: {consolidator_count}")
diff --git a/fincept-qt/scripts/strategies/PeriodBasedHistoryRequestNotAllowedWithTickResolutionRegressionAlgorithm.py b/fincept-qt/scripts/strategies/PeriodBasedHistoryRequestNotAllowedWithTickResolutionRegressionAlgorithm.py
deleted file mode 100644
index d3ceb04fb..000000000
--- a/fincept-qt/scripts/strategies/PeriodBasedHistoryRequestNotAllowedWithTickResolutionRegressionAlgorithm.py
+++ /dev/null
@@ -1,48 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-B9E58D2A
-# Category: Regression Test
-# Description: Regression algorithm for testing that period-based history requests are not allowed with tick resolution
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Regression algorithm for testing that period-based history requests are not allowed with tick resolution
-### </summary>
-class PeriodBasedHistoryRequestNotAllowedWithTickResolutionRegressionAlgorithm(QCAlgorithm):
- def initialize(self):
- self.set_start_date(2013, 10, 8)
- self.set_end_date(2013, 10, 9)
-
- spy = self.add_equity("SPY", Resolution.TICK).symbol
-
- # Tick resolution is not allowed for period-based history requests
- self.assert_that_history_throws_for_tick_resolution(lambda: self.history[Tick](spy, 1),
- "Tick history call with implicit tick resolution")
- self.assert_that_history_throws_for_tick_resolution(lambda: self.history[Tick](spy, 1, Resolution.TICK),
- "Tick history call with explicit tick resolution")
- self.assert_that_history_throws_for_tick_resolution(lambda: self.history[Tick]([spy], 1),
- "Tick history call with symbol array with implicit tick resolution")
- self.assert_that_history_throws_for_tick_resolution(lambda: self.history[Tick]([spy], 1, Resolution.TICK),
- "Tick history call with symbol array with explicit tick resolution")
-
- history = self.history[Tick](spy, TimeSpan.from_hours(12))
- if len(list(history)) == 0:
- raise Exception("On history call with implicit tick resolution: history returned no results")
-
- history = self.history[Tick](spy, TimeSpan.from_hours(12), Resolution.TICK)
- if len(list(history)) == 0:
- raise Exception("On history call with explicit tick resolution: history returned no results")
-
- def assert_that_history_throws_for_tick_resolution(self, history_call, history_call_description):
- try:
- history_call()
- raise Exception(f"{history_call_description}: expected an exception to be thrown")
- except InvalidOperationException:
- # expected
- pass
diff --git a/fincept-qt/scripts/strategies/Portfolio/__init__.py b/fincept-qt/scripts/strategies/Portfolio/__init__.py
deleted file mode 100644
index 753428b4a..000000000
--- a/fincept-qt/scripts/strategies/Portfolio/__init__.py
+++ /dev/null
@@ -1,42 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Portfolio Shim
-# Re-exports from fincept_engine + dynamic submodule stubs
-# ============================================================================
-
-import sys, os, types
-
-_parent = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
-if _parent not in sys.path:
- sys.path.insert(0, _parent)
-
-from fincept_engine.algorithm_imports import (
- PortfolioConstructionModel,
- EqualWeightingPortfolioConstructionModel,
- InsightWeightingPortfolioConstructionModel,
- MeanVarianceOptimizationPortfolioConstructionModel,
- BlackLittermanOptimizationPortfolioConstructionModel,
- AccumulativeInsightPortfolioConstructionModel,
- ConfidenceWeightedPortfolioConstructionModel,
- SectorWeightingPortfolioConstructionModel,
- PortfolioTarget, PortfolioBias
-)
-from fincept_engine.framework.portfolio_construction import (
- UnconstrainedMeanVariancePortfolioOptimizer
-)
-
-_submodules = {
- 'EqualWeightingPortfolioConstructionModel': {'EqualWeightingPortfolioConstructionModel': EqualWeightingPortfolioConstructionModel},
- 'InsightWeightingPortfolioConstructionModel': {'InsightWeightingPortfolioConstructionModel': InsightWeightingPortfolioConstructionModel},
- 'MeanVarianceOptimizationPortfolioConstructionModel': {'MeanVarianceOptimizationPortfolioConstructionModel': MeanVarianceOptimizationPortfolioConstructionModel},
- 'BlackLittermanOptimizationPortfolioConstructionModel': {'BlackLittermanOptimizationPortfolioConstructionModel': BlackLittermanOptimizationPortfolioConstructionModel},
- 'AccumulativeInsightPortfolioConstructionModel': {'AccumulativeInsightPortfolioConstructionModel': AccumulativeInsightPortfolioConstructionModel},
- 'ConfidenceWeightedPortfolioConstructionModel': {'ConfidenceWeightedPortfolioConstructionModel': ConfidenceWeightedPortfolioConstructionModel},
- 'SectorWeightingPortfolioConstructionModel': {'SectorWeightingPortfolioConstructionModel': SectorWeightingPortfolioConstructionModel},
- 'UnconstrainedMeanVariancePortfolioOptimizer': {'UnconstrainedMeanVariancePortfolioOptimizer': UnconstrainedMeanVariancePortfolioOptimizer},
-}
-
-for _name, _attrs in _submodules.items():
- _mod = types.ModuleType(f'Portfolio.{_name}')
- for _attr_name, _attr_val in _attrs.items():
- setattr(_mod, _attr_name, _attr_val)
- sys.modules[f'Portfolio.{_name}'] = _mod
diff --git a/fincept-qt/scripts/strategies/PortfolioRebalanceOnCustomFuncRegressionAlgorithm.py b/fincept-qt/scripts/strategies/PortfolioRebalanceOnCustomFuncRegressionAlgorithm.py
deleted file mode 100644
index 78ed2392f..000000000
--- a/fincept-qt/scripts/strategies/PortfolioRebalanceOnCustomFuncRegressionAlgorithm.py
+++ /dev/null
@@ -1,72 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-B4A28E80
-# Category: Portfolio Management
-# Description: Regression algorithm testing portfolio construction model control over rebalancing, specifying a custom rebalance fun...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Regression algorithm testing portfolio construction model control over rebalancing,
-### specifying a custom rebalance function that returns null in some cases, see GH 4075.
-### </summary>
-class PortfolioRebalanceOnCustomFuncRegressionAlgorithm(QCAlgorithm):
- def initialize(self):
- ''' Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
-
- self.universe_settings.resolution = Resolution.DAILY
-
- # Order margin value has to have a minimum of 0.5% of Portfolio value, allows filtering out small trades and reduce fees.
- # Commented so regression algorithm is more sensitive
- #self.settings.minimum_order_margin_portfolio_percentage = 0.005
-
- self.set_start_date(2015, 1, 1)
- self.set_end_date(2018, 1, 1)
-
- self.settings.rebalance_portfolio_on_insight_changes = False
- self.settings.rebalance_portfolio_on_security_changes = False
-
- self.set_universe_selection(CustomUniverseSelectionModel("CustomUniverseSelectionModel", lambda time: [ "AAPL", "IBM", "FB", "SPY", "AIG", "BAC", "BNO" ]))
- self.set_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, TimeSpan.from_minutes(20), 0.025, None))
- self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel(self.rebalance_function))
- self.set_execution(ImmediateExecutionModel())
- self.last_rebalance_time = self.start_date
-
- def rebalance_function(self, time):
- # for performance only run rebalance logic once a week, monday
- if time.weekday() != 0:
- return None
-
- if self.last_rebalance_time == self.start_date:
- # initial rebalance
- self.last_rebalance_time = time
- return time
-
- deviation = 0
- count = sum(1 for security in self.securities.values() if security.invested)
- if count > 0:
- self.last_rebalance_time = time
- portfolio_value_per_security = self.portfolio.total_portfolio_value / count
- for security in self.securities.values():
- if not security.invested:
- continue
- reserved_buying_power_for_current_position = (security.buying_power_model.get_reserved_buying_power_for_position(
- ReservedBuyingPowerForPositionParameters(security)).absolute_used_buying_power
- * security.buying_power_model.get_leverage(security)) # see GH issue 4107
- # we sum up deviation for each security
- deviation += (portfolio_value_per_security - reserved_buying_power_for_current_position) / portfolio_value_per_security
-
- # if securities are deviated 1.5% from their theoretical share of TotalPortfolioValue we rebalance
- if deviation >= 0.015:
- return time
- return None
-
- def on_order_event(self, order_event):
- if order_event.status == OrderStatus.SUBMITTED:
- if self.utc_time != self.last_rebalance_time or self.utc_time.weekday() != 0:
- raise ValueError(f"{self.utc_time} {order_event.symbol}")
diff --git a/fincept-qt/scripts/strategies/PortfolioRebalanceOnDateRulesRegressionAlgorithm.py b/fincept-qt/scripts/strategies/PortfolioRebalanceOnDateRulesRegressionAlgorithm.py
deleted file mode 100644
index d22096459..000000000
--- a/fincept-qt/scripts/strategies/PortfolioRebalanceOnDateRulesRegressionAlgorithm.py
+++ /dev/null
@@ -1,47 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-53259B36
-# Category: Portfolio Management
-# Description: Regression algorithm testing portfolio construction model control over rebalancing, specifying a date rules, see GH 4075
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Regression algorithm testing portfolio construction model control over rebalancing,
-### specifying a date rules, see GH 4075.
-### </summary>
-class PortfolioRebalanceOnDateRulesRegressionAlgorithm(QCAlgorithm):
- def initialize(self):
- ''' Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
-
- self.universe_settings.resolution = Resolution.DAILY
-
- # Order margin value has to have a minimum of 0.5% of Portfolio value, allows filtering out small trades and reduce fees.
- # Commented so regression algorithm is more sensitive
- #self.settings.minimum_order_margin_portfolio_percentage = 0.005
-
- # let's use 0 minimum order margin percentage so we can assert trades are only submitted immediately after rebalance on Wednesday
- # if not, due to TPV variations happening every day we might no cross the minimum on wednesday but yes another day of the week
- self.settings.minimum_order_margin_portfolio_percentage = 0
-
- self.set_start_date(2015,1,1)
- self.set_end_date(2017,1,1)
-
- self.settings.rebalance_portfolio_on_insight_changes = False
- self.settings.rebalance_portfolio_on_security_changes = False
-
- self.set_universe_selection(CustomUniverseSelectionModel("CustomUniverseSelectionModel", lambda time: [ "AAPL", "IBM", "FB", "SPY" ]))
- self.set_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, TimeSpan.from_minutes(20), 0.025, None))
- self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel(self.date_rules.every(DayOfWeek.WEDNESDAY)))
- self.set_execution(ImmediateExecutionModel())
-
- def on_order_event(self, order_event):
- if order_event.status == OrderStatus.SUBMITTED:
- self.debug(str(order_event))
- if self.utc_time.weekday() != 2:
- raise ValueError(str(self.utc_time) + " " + str(order_event.symbol) + " " + str(self.utc_time.weekday()))
diff --git a/fincept-qt/scripts/strategies/PortfolioTargetTagsRegressionAlgorithm.py b/fincept-qt/scripts/strategies/PortfolioTargetTagsRegressionAlgorithm.py
deleted file mode 100644
index 32e455f49..000000000
--- a/fincept-qt/scripts/strategies/PortfolioTargetTagsRegressionAlgorithm.py
+++ /dev/null
@@ -1,85 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-1D170EBB
-# Category: Portfolio Management
-# Description: Algorithm demonstrating the portfolio target tags usage
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Algorithm demonstrating the portfolio target tags usage
-### </summary>
-class PortfolioTargetTagsRegressionAlgorithm(QCAlgorithm):
- '''Algorithm demonstrating the portfolio target tags usage'''
-
- def initialize(self):
- self.set_start_date(2013,10,7) #Set Start Date
- self.set_end_date(2013,10,11) #Set End Date
- self.set_cash(100000) #Set Strategy Cash
-
- self.universe_settings.resolution = Resolution.MINUTE
-
- symbols = [ Symbol.create("SPY", SecurityType.EQUITY, Market.USA) ]
-
- # set algorithm framework models
- self.set_universe_selection(ManualUniverseSelectionModel(symbols))
- self.set_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(minutes = 20), 0.025, None))
-
- self.set_portfolio_construction(CustomPortfolioConstructionModel())
- self.set_risk_management(CustomRiskManagementModel())
- self.set_execution(CustomExecutionModel(self.set_target_tags_checked))
-
- self.target_tags_checked = False
-
- def set_target_tags_checked(self):
- self.target_tags_checked = True
-
- def on_end_of_algorithm(self):
- if not self.target_tags_checked:
- raise Exception("The portfolio targets tag were not checked")
-
-class CustomPortfolioConstructionModel(EqualWeightingPortfolioConstructionModel):
- def __init__(self):
- super().__init__(Resolution.DAILY)
-
- def create_targets(self, algorithm: QCAlgorithm, insights: List[Insight]) -> List[IPortfolioTarget]:
- targets = super().create_targets(algorithm, insights)
- return CustomPortfolioConstructionModel.add_p_portfolio_targets_tags(targets)
-
- @staticmethod
- def generate_portfolio_target_tag(target: IPortfolioTarget) -> str:
- return f"Portfolio target tag: {target.symbol} - {target.quantity}"
-
- @staticmethod
- def add_p_portfolio_targets_tags(targets: List[IPortfolioTarget]) -> List[IPortfolioTarget]:
- return [PortfolioTarget(target.symbol, target.quantity, CustomPortfolioConstructionModel.generate_portfolio_target_tag(target))
- for target in targets]
-
-class CustomRiskManagementModel(MaximumDrawdownPercentPerSecurity):
- def __init__(self):
- super().__init__(0.01)
-
- def manage_risk(self, algorithm: QCAlgorithm, targets: List[IPortfolioTarget]) -> List[IPortfolioTarget]:
- risk_managed_targets = super().manage_risk(algorithm, targets)
- return CustomPortfolioConstructionModel.add_p_portfolio_targets_tags(risk_managed_targets)
-
-class CustomExecutionModel(ImmediateExecutionModel):
- def __init__(self, targets_tag_checked_callback: Callable) -> None:
- super().__init__()
- self.targets_tag_checked_callback = targets_tag_checked_callback
-
- def execute(self, algorithm: QCAlgorithm, targets: List[IPortfolioTarget]) -> None:
- if len(targets) > 0:
- self.targets_tag_checked_callback()
-
- for target in targets:
- expected_tag = CustomPortfolioConstructionModel.generate_portfolio_target_tag(target)
- if target.tag != expected_tag:
- raise Exception(f"Unexpected portfolio target tag: {target.tag} - Expected: {expected_tag}")
-
- super().execute(algorithm, targets)
diff --git a/fincept-qt/scripts/strategies/PythonDictionaryFeatureRegressionAlgorithm.py b/fincept-qt/scripts/strategies/PythonDictionaryFeatureRegressionAlgorithm.py
deleted file mode 100644
index f1903d2a4..000000000
--- a/fincept-qt/scripts/strategies/PythonDictionaryFeatureRegressionAlgorithm.py
+++ /dev/null
@@ -1,125 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-3E91D425
-# Category: Regression Test
-# Description: Example algorithm showing that Slice, Securities and Portfolio behave as a Python Dictionary
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Example algorithm showing that Slice, Securities and Portfolio behave as a Python Dictionary
-### </summary>
-class PythonDictionaryFeatureRegressionAlgorithm(QCAlgorithm):
- '''Example algorithm showing that Slice, Securities and Portfolio behave as a Python Dictionary'''
-
- def initialize(self):
-
- self.set_start_date(2013,10, 7) #Set Start Date
- self.set_end_date(2013,10,11) #Set End Date
- self.set_cash(100000) #Set Strategy Cash
-
- self.spy_symbol = self.add_equity("SPY").symbol
- self.ibm_symbol = self.add_equity("IBM").symbol
- self.aig_symbol = self.add_equity("AIG").symbol
- self.aapl_symbol = Symbol.create("AAPL", SecurityType.EQUITY, Market.USA)
-
- date_rules = self.date_rules.on(2013, 10, 7)
- self.schedule.on(date_rules, self.time_rules.at(13, 0), self.test_securities_dictionary)
- self.schedule.on(date_rules, self.time_rules.at(14, 0), self.test_portfolio_dictionary)
- self.schedule.on(date_rules, self.time_rules.at(15, 0), self.test_slice_dictionary)
-
- def test_slice_dictionary(self):
- slice = self.current_slice
-
- symbols = ', '.join([f'{x}' for x in slice.keys()])
- slice_data = ', '.join([f'{x}' for x in slice.values()])
- slice_bars = ', '.join([f'{x}' for x in slice.bars.values()])
-
- if "SPY" not in slice:
- raise Exception('SPY (string) is not in Slice')
-
- if self.spy_symbol not in slice:
- raise Exception('SPY (Symbol) is not in Slice')
-
- spy = slice.get(self.spy_symbol)
- if spy is None:
- raise Exception('SPY is not in Slice')
-
- for symbol, bar in slice.bars.items():
- self.plot(symbol, 'Price', bar.close)
-
-
- def test_securities_dictionary(self):
- symbols = ', '.join([f'{x}' for x in self.securities.keys()])
- leverages = ', '.join([str(x.get_last_data()) for x in self.securities.values()])
-
- if "IBM" not in self.securities:
- raise Exception('IBM (string) is not in Securities')
-
- if self.ibm_symbol not in self.securities:
- raise Exception('IBM (Symbol) is not in Securities')
-
- ibm = self.securities.get(self.ibm_symbol)
- if ibm is None:
- raise Exception('ibm is None')
-
- aapl = self.securities.get(self.aapl_symbol)
- if aapl is not None:
- raise Exception('aapl is not None')
-
- for symbol, security in self.securities.items():
- self.plot(symbol, 'Price', security.price)
-
- def test_portfolio_dictionary(self):
- symbols = ', '.join([f'{x}' for x in self.portfolio.keys()])
- leverages = ', '.join([f'{x.symbol}: {x.leverage}' for x in self.portfolio.values()])
-
- if "AIG" not in self.securities:
- raise Exception('AIG (string) is not in Portfolio')
-
- if self.aig_symbol not in self.securities:
- raise Exception('AIG (Symbol) is not in Portfolio')
-
- aig = self.portfolio.get(self.aig_symbol)
- if aig is None:
- raise Exception('aig is None')
-
- aapl = self.portfolio.get(self.aapl_symbol)
- if aapl is not None:
- raise Exception('aapl is not None')
-
- for symbol, holdings in self.portfolio.items():
- msg = f'{symbol}: {holdings.leverage}'
-
- def on_end_of_algorithm(self):
-
- portfolio_copy = self.portfolio.copy()
- try:
- self.portfolio.clear() # Throws exception
- except Exception as e:
- self.debug(e)
-
- bar = self.securities.pop("SPY")
- length = len(self.securities)
- if length != 2:
- raise Exception(f'After popping SPY, Securities should have 2 elements, {length} found')
-
- securities_copy = self.securities.copy()
- self.securities.clear() # Does not throw
-
-
- def on_data(self, data):
- '''on_data event is the primary entry point for your algorithm. Each new data point will be pumped in here.
-
- Arguments:
- data: Slice object keyed by symbol containing the stock data
- '''
- if not self.portfolio.invested:
- self.set_holdings("SPY", 1/3)
- self.set_holdings("IBM", 1/3)
- self.set_holdings("AIG", 1/3)
diff --git a/fincept-qt/scripts/strategies/PytorchNeuralNetworkAlgorithm.py b/fincept-qt/scripts/strategies/PytorchNeuralNetworkAlgorithm.py
deleted file mode 100644
index d2ce7914d..000000000
--- a/fincept-qt/scripts/strategies/PytorchNeuralNetworkAlgorithm.py
+++ /dev/null
@@ -1,104 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-3BE1BA87
-# Category: Machine Learning
-# Description: Enter or exit positions based on relationship of the open price of the current bar and the prices defined by the mach...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-import torch
-import torch.nn.functional as F
-
-class PytorchNeuralNetworkAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2013, 10, 7) # Set Start Date
- self.set_end_date(2013, 10, 8) # Set End Date
-
- self.set_cash(100000) # Set Strategy Cash
-
- # add symbol
- spy = self.add_equity("SPY", Resolution.MINUTE)
- self._symbols = [spy.symbol] # using a list can extend to condition for multiple symbols
-
- self.lookback = 30 # days of historical data (look back)
-
- self.schedule.on(self.date_rules.every_day("SPY"), self.time_rules.after_market_open("SPY", 28), self.net_train) # train the NN
- self.schedule.on(self.date_rules.every_day("SPY"), self.time_rules.after_market_open("SPY", 30), self.trade)
-
- def net_train(self):
- # Daily historical data is used to train the machine learning model
- history = self.history(self._symbols, self.lookback + 1, Resolution.DAILY)
-
- # dicts that store prices for training
- self.prices_x = {}
- self.prices_y = {}
-
- # dicts that store prices for sell and buy
- self.sell_prices = {}
- self.buy_prices = {}
-
- for symbol in self._symbols:
- if not history.empty:
- # x: preditors; y: response
- self.prices_x[symbol] = list(history.loc[symbol.value]['open'])[:-1]
- self.prices_y[symbol] = list(history.loc[symbol.value]['open'])[1:]
-
- for symbol in self._symbols:
- # if this symbol has historical data
- if symbol in self.prices_x:
-
- net = Net(n_feature=1, n_hidden=10, n_output=1) # define the network
- optimizer = torch.optim.SGD(net.parameters(), lr=0.2)
- loss_func = torch.nn.MSELoss() # this is for regression mean squared loss
-
- for t in range(200):
- # Get data and do preprocessing
- x = torch.from_numpy(np.array(self.prices_x[symbol])).float()
- y = torch.from_numpy(np.array(self.prices_y[symbol])).float()
-
- # unsqueeze data (see pytorch doc for details)
- x = x.unsqueeze(1)
- y = y.unsqueeze(1)
-
- prediction = net(x) # input x and predict based on x
-
- loss = loss_func(prediction, y) # must be (1. nn output, 2. target)
-
- optimizer.zero_grad() # clear gradients for next train
- loss.backward() # backpropagation, compute gradients
- optimizer.step() # apply gradients
-
- # Follow the trend
- self.buy_prices[symbol] = net(y)[-1] + np.std(y.data.numpy())
- self.sell_prices[symbol] = net(y)[-1] - np.std(y.data.numpy())
-
- def trade(self):
- '''
- Enter or exit positions based on relationship of the open price of the current bar and the prices defined by the machine learning model.
- Liquidate if the open price is below the sell price and buy if the open price is above the buy price
- '''
- for holding in self.portfolio.values():
- if self.current_slice[holding.symbol].open < self.sell_prices[holding.symbol] and holding.invested:
- self.liquidate(holding.symbol)
-
- if self.current_slice[holding.symbol].open > self.buy_prices[holding.symbol] and not holding.invested:
- self.set_holdings(holding.symbol, 1 / len(self._symbols))
-
-
-
-# class for Pytorch NN model
-class Net(torch.nn.Module):
- def __init__(self, n_feature, n_hidden, n_output):
- super(Net, self).__init__()
- self.hidden = torch.nn.Linear(n_feature, n_hidden) # hidden layer
- self.predict = torch.nn.Linear(n_hidden, n_output) # output layer
-
- def forward(self, x):
- x = F.relu(self.hidden(x)) # activation function for hidden layer
- x = self.predict(x) # linear output
- return x
diff --git a/fincept-qt/scripts/strategies/QuitAfterInitializationRegressionAlgorithm.py b/fincept-qt/scripts/strategies/QuitAfterInitializationRegressionAlgorithm.py
deleted file mode 100644
index 22efb4e30..000000000
--- a/fincept-qt/scripts/strategies/QuitAfterInitializationRegressionAlgorithm.py
+++ /dev/null
@@ -1,45 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-0CB9D7FA
-# Category: Regression Test
-# Description: Quick-entry momentum strategy. Immediately buys SPY when price
-# is above 10-day EMA and RSI is below 70. Exits when RSI exceeds 80 or
-# price drops below EMA. Originally a regression test for init behavior.
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-class QuitAfterInitializationRegressionAlgorithm(QCAlgorithm):
- """Quick-entry momentum strategy with RSI filter."""
-
- def initialize(self):
- self.set_start_date(2023, 1, 1)
- self.set_end_date(2024, 1, 1)
- self.set_cash(100000)
-
- self.symbol = "SPY"
- self.add_equity(self.symbol, Resolution.DAILY)
-
- self._ema = self.ema(self.symbol, 10, Resolution.DAILY)
- self._rsi = self.rsi(self.symbol, 14, Resolution.DAILY)
-
- def on_data(self, data):
- if not self._ema.is_ready or not self._rsi.is_ready:
- return
- if self.symbol not in data:
- return
-
- price = data[self.symbol].close
- ema_val = self._ema.current.value
- rsi_val = self._rsi.current.value
-
- if not self.portfolio.invested:
- if price > ema_val and rsi_val < 70:
- self.set_holdings(self.symbol, 1)
- else:
- if rsi_val > 80 or price < ema_val:
- self.liquidate()
diff --git a/fincept-qt/scripts/strategies/QuitInInitializationRegressionAlgorithm.py b/fincept-qt/scripts/strategies/QuitInInitializationRegressionAlgorithm.py
deleted file mode 100644
index e41f113f9..000000000
--- a/fincept-qt/scripts/strategies/QuitInInitializationRegressionAlgorithm.py
+++ /dev/null
@@ -1,49 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-87512128
-# Category: Regression Test
-# Description: This regression algorithm is expected to stop executing after Initialization. Related to GH 6168 issue
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
-# Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-from AlgorithmImports import *
-
-### <summary>
-### This regression algorithm is expected to stop executing after Initialization. Related to GH 6168 issue
-### </summary>
-class QuitInInitializationRegressionAlgorithm(QCAlgorithm):
- '''Basic template algorithm simply initializes the date range and cash'''
-
- def initialize(self):
- '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
-
- self.set_start_date(2013,10, 7) #Set Start Date
- self.set_end_date(2013,10,11) #Set End Date
- self.set_cash(100000) #Set Strategy Cash
-
- self.add_equity("SPY", Resolution.DAILY)
- self.quit()
-
- def on_data(self, data):
- '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
-
- Arguments:
- data: Slice object keyed by symbol containing the stock data
- '''
- raise ValueError("Algorithm should of stopped!")
diff --git a/fincept-qt/scripts/strategies/RangeConsolidatorAlgorithm.py b/fincept-qt/scripts/strategies/RangeConsolidatorAlgorithm.py
deleted file mode 100644
index 59c0e1bcb..000000000
--- a/fincept-qt/scripts/strategies/RangeConsolidatorAlgorithm.py
+++ /dev/null
@@ -1,45 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-052CED9D
-# Category: Data Consolidation
-# Description: Breakout strategy using price range analysis. Buys when the
-# current close breaks above the 10-day high, sells when it drops below the
-# 10-day low. Inspired by range consolidation breakout patterns.
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-class RangeConsolidatorAlgorithm(QCAlgorithm):
- """Price range breakout strategy: enters on new highs, exits on new lows."""
-
- def initialize(self):
- self.set_start_date(2023, 1, 1)
- self.set_end_date(2024, 1, 1)
- self.set_cash(100000)
-
- self.symbol = "SPY"
- self.add_equity(self.symbol, Resolution.DAILY)
-
- self._max = self.max(self.symbol, 10, Resolution.DAILY)
- self._min = self.min(self.symbol, 10, Resolution.DAILY)
-
- def on_data(self, data):
- if not self._max.is_ready or not self._min.is_ready:
- return
- if self.symbol not in data:
- return
-
- price = data[self.symbol].close
- upper = self._max.current.value
- lower = self._min.current.value
-
- # Breakout above 10-day high → buy
- if not self.portfolio.invested and price >= upper:
- self.set_holdings(self.symbol, 1)
- # Breakdown below 10-day low → sell
- elif self.portfolio.invested and price <= lower:
- self.liquidate()
diff --git a/fincept-qt/scripts/strategies/RangeConsolidatorWithTickAlgorithm.py b/fincept-qt/scripts/strategies/RangeConsolidatorWithTickAlgorithm.py
deleted file mode 100644
index 2bdfeee3e..000000000
--- a/fincept-qt/scripts/strategies/RangeConsolidatorWithTickAlgorithm.py
+++ /dev/null
@@ -1,45 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-0761902F
-# Category: Data Consolidation
-# Description: Bollinger Band mean-reversion strategy adapted from tick-level
-# range consolidation. Buys when price drops below lower BB (2 stdev), sells
-# when price rises above upper BB. Uses 20-period bands.
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-class RangeConsolidatorWithTickAlgorithm(QCAlgorithm):
- """Bollinger Band mean-reversion: buys at lower band, sells at upper."""
-
- def initialize(self):
- self.set_start_date(2023, 1, 1)
- self.set_end_date(2024, 1, 1)
- self.set_cash(100000)
-
- self.symbol = "SPY"
- self.add_equity(self.symbol, Resolution.DAILY)
-
- self._bb = self.bb(self.symbol, 20, 2, Resolution.DAILY)
-
- def on_data(self, data):
- if not self._bb.is_ready:
- return
- if self.symbol not in data:
- return
-
- price = data[self.symbol].close
- upper = self._bb.upper_band.current.value
- lower = self._bb.lower_band.current.value
- middle = self._bb.middle_band.current.value
-
- # Buy when price is below lower Bollinger Band
- if not self.portfolio.invested and price < lower:
- self.set_holdings(self.symbol, 1)
- # Sell when price reaches upper band or middle band on recovery
- elif self.portfolio.invested and price > upper:
- self.liquidate()
diff --git a/fincept-qt/scripts/strategies/RawDataRegressionAlgorithm.py b/fincept-qt/scripts/strategies/RawDataRegressionAlgorithm.py
deleted file mode 100644
index cbcb68345..000000000
--- a/fincept-qt/scripts/strategies/RawDataRegressionAlgorithm.py
+++ /dev/null
@@ -1,64 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-4C4ACA6D
-# Category: Regression Test
-# Description: Raw Data Regression Algorithm
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-from QuantConnect.Data.Auxiliary import *
-from QuantConnect.Lean.Engine.DataFeeds import DefaultDataProvider
-
-_ticker = "GOOGL"
-_expected_raw_prices = [ 1158.72,
-1131.97, 1114.28, 1120.15, 1114.51, 1134.89, 1135.1, 571.50, 545.25, 540.63 ]
-
-# <summary>
-# In this algorithm we demonstrate how to use the raw data for our securities
-# and verify that the behavior is correct.
-# </summary>
-# <meta name="tag" content="using data" />
-# <meta name="tag" content="regression test" />
-class RawDataRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2014, 3, 25)
- self.set_end_date(2014, 4, 7)
- self.set_cash(100000)
-
- # Set our DataNormalizationMode to raw
- self.universe_settings.data_normalization_mode = DataNormalizationMode.RAW
- self._googl = self.add_equity(_ticker, Resolution.DAILY).symbol
-
- # Get our factor file for this regression
- data_provider = DefaultDataProvider()
- map_file_provider = LocalDiskMapFileProvider()
- map_file_provider.initialize(data_provider)
- factor_file_provider = LocalDiskFactorFileProvider()
- factor_file_provider.initialize(map_file_provider, data_provider)
-
- # Get our factor file for this regression
- self._factor_file = factor_file_provider.get(self._googl)
-
-
- def on_data(self, data):
- if not self.portfolio.invested:
- self.set_holdings(self._googl, 1)
-
- if data.bars.contains_key(self._googl):
- googl_data = data.bars[self._googl]
-
- # Assert our volume matches what we expected
- expected_raw_price = _expected_raw_prices.pop(0)
- if expected_raw_price != googl_data.close:
- # Our values don't match lets try and give a reason why
- day_factor = self._factor_file.get_price_scale_factor(googl_data.time)
- probable_raw_price = googl_data.close / day_factor # Undo adjustment
-
- raise Exception("Close price was incorrect; it appears to be the adjusted value"
- if expected_raw_price == probable_raw_price else
- "Close price was incorrect; Data may have changed.")
diff --git a/fincept-qt/scripts/strategies/RawPricesCoarseUniverseAlgorithm.py b/fincept-qt/scripts/strategies/RawPricesCoarseUniverseAlgorithm.py
deleted file mode 100644
index e30bc0bae..000000000
--- a/fincept-qt/scripts/strategies/RawPricesCoarseUniverseAlgorithm.py
+++ /dev/null
@@ -1,71 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-8426823A
-# Category: Universe Selection
-# Description: In this algorithm we demonstrate how to use the coarse fundamental data to define a universe as the top dollar volume...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### In this algorithm we demonstrate how to use the coarse fundamental data to define a universe as the top dollar volume and set the algorithm to use raw prices
-### </summary>
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="universes" />
-### <meta name="tag" content="coarse universes" />
-### <meta name="tag" content="fine universes" />
-class RawPricesCoarseUniverseAlgorithm(QCAlgorithm):
-
- def initialize(self):
- '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
-
- # what resolution should the data *added* to the universe be?
- self.universe_settings.resolution = Resolution.DAILY
-
- self.set_start_date(2014,1,1) #Set Start Date
- self.set_end_date(2015,1,1) #Set End Date
- self.set_cash(50000) #Set Strategy Cash
-
- # Set the security initializer with the characteristics defined in CustomSecurityInitializer
- self.set_security_initializer(self.custom_security_initializer)
-
- # this add universe method accepts a single parameter that is a function that
- # accepts an IEnumerable<CoarseFundamental> and returns IEnumerable<Symbol>
- self.add_universe(self.coarse_selection_function)
-
- self.__number_of_symbols = 5
-
- def custom_security_initializer(self, security):
- '''Initialize the security with raw prices and zero fees
- Args:
- security: Security which characteristics we want to change'''
- security.set_data_normalization_mode(DataNormalizationMode.RAW)
- security.set_fee_model(ConstantFeeModel(0))
-
- # sort the data by daily dollar volume and take the top 'NumberOfSymbols'
- def coarse_selection_function(self, coarse):
- # sort descending by daily dollar volume
- sorted_by_dollar_volume = sorted(coarse, key=lambda x: x.dollar_volume, reverse=True)
-
- # return the symbol objects of the top entries from our sorted collection
- return [ x.symbol for x in sorted_by_dollar_volume[:self.__number_of_symbols] ]
-
-
- # this event fires whenever we have changes to our universe
- def on_securities_changed(self, changes):
- # liquidate removed securities
- for security in changes.removed_securities:
- if security.invested:
- self.liquidate(security.symbol)
-
- # we want 20% allocation in each security in our universe
- for security in changes.added_securities:
- self.set_holdings(security.symbol, 0.2)
-
- def on_order_event(self, order_event):
- if order_event.status == OrderStatus.FILLED:
- self.log(f"OnOrderEvent({self.utc_time}):: {order_event}")
diff --git a/fincept-qt/scripts/strategies/RawPricesUniverseRegressionAlgorithm.py b/fincept-qt/scripts/strategies/RawPricesUniverseRegressionAlgorithm.py
deleted file mode 100644
index cd5a577c7..000000000
--- a/fincept-qt/scripts/strategies/RawPricesUniverseRegressionAlgorithm.py
+++ /dev/null
@@ -1,62 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-EEE07C98
-# Category: Universe Selection
-# Description: In this algorithm we demonstrate how to use the UniverseSettings to define the data normalization mode (raw)
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### In this algorithm we demonstrate how to use the UniverseSettings
-### to define the data normalization mode (raw)
-### </summary>
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="universes" />
-### <meta name="tag" content="coarse universes" />
-### <meta name="tag" content="fine universes" />
-class RawPricesUniverseRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self):
- '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
-
- # what resolution should the data *added* to the universe be?
- self.universe_settings.resolution = Resolution.DAILY
-
- # Use raw prices
- self.universe_settings.data_normalization_mode = DataNormalizationMode.RAW
-
- self.set_start_date(2014,3,24) #Set Start Date
- self.set_end_date(2014,4,7) #Set End Date
- self.set_cash(50000) #Set Strategy Cash
-
- # Set the security initializer with zero fees and price initial seed
- securitySeeder = FuncSecuritySeeder(self.GetLastKnownPrices)
- self.set_security_initializer(CompositeSecurityInitializer(
- FuncSecurityInitializer(lambda x: x.set_fee_model(ConstantFeeModel(0))),
- FuncSecurityInitializer(lambda security: securitySeeder.SeedSecurity(security))))
-
- self.add_universe("MyUniverse", Resolution.DAILY, self.selection_function)
-
-
- def selection_function(self, date_time):
- if date_time.day % 2 == 0:
- return ["SPY", "IWM", "QQQ"]
- else:
- return ["AIG", "BAC", "IBM"]
-
-
- # this event fires whenever we have changes to our universe
- def on_securities_changed(self, changes):
- # liquidate removed securities
- for security in changes.removed_securities:
- if security.invested:
- self.liquidate(security.symbol)
-
- # we want 20% allocation in each security in our universe
- for security in changes.added_securities:
- self.set_holdings(security.symbol, 0.2)
diff --git a/fincept-qt/scripts/strategies/RegisterIndicatorRegressionAlgorithm.py b/fincept-qt/scripts/strategies/RegisterIndicatorRegressionAlgorithm.py
deleted file mode 100644
index 7a2b01ede..000000000
--- a/fincept-qt/scripts/strategies/RegisterIndicatorRegressionAlgorithm.py
+++ /dev/null
@@ -1,51 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-0D15187F
-# Category: Indicators
-# Description: Triple SMA crossover strategy demonstrating indicator registration.
-# Uses 5/10/20-period SMAs with registered auto-update. Buys when all three
-# are aligned bullish (5 > 10 > 20), sells when alignment breaks.
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-class RegisterIndicatorRegressionAlgorithm(QCAlgorithm):
- """Triple SMA crossover with indicator registration."""
-
- def initialize(self):
- self.set_start_date(2023, 1, 1)
- self.set_end_date(2024, 1, 1)
- self.set_cash(100000)
-
- self.symbol = "SPY"
- self.add_equity(self.symbol, Resolution.DAILY)
-
- # Create and register SMAs (name, period)
- self._sma5 = SimpleMovingAverage("SMA5", 5)
- self._sma10 = SimpleMovingAverage("SMA10", 10)
- self._sma20 = SimpleMovingAverage("SMA20", 20)
-
- self.register_indicator(self.symbol, self._sma5, Resolution.DAILY)
- self.register_indicator(self.symbol, self._sma10, Resolution.DAILY)
- self.register_indicator(self.symbol, self._sma20, Resolution.DAILY)
-
- def on_data(self, data):
- if not self._sma20.is_ready:
- return
- if self.symbol not in data:
- return
-
- s5 = self._sma5.current.value
- s10 = self._sma10.current.value
- s20 = self._sma20.current.value
-
- # All three aligned bullish: 5 > 10 > 20
- if not self.portfolio.invested and s5 > s10 > s20:
- self.set_holdings(self.symbol, 1)
- # Alignment broken
- elif self.portfolio.invested and s5 < s10:
- self.liquidate()
diff --git a/fincept-qt/scripts/strategies/RegressionAlgorithm.py b/fincept-qt/scripts/strategies/RegressionAlgorithm.py
deleted file mode 100644
index d0f1ee33f..000000000
--- a/fincept-qt/scripts/strategies/RegressionAlgorithm.py
+++ /dev/null
@@ -1,54 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-D350E387
-# Category: Regression Test
-# Description: Algorithm used for regression tests purposes
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Algorithm used for regression tests purposes
-### </summary>
-### <meta name="tag" content="regression test" />
-class RegressionAlgorithm(QCAlgorithm):
-
- def initialize(self):
- '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
-
- self.set_start_date(2013,10,7) #Set Start Date
- self.set_end_date(2013,10,11) #Set End Date
- self.set_cash(10000000) #Set Strategy Cash
- # Fincept Terminal Strategy Engine - Symbol Configuration
- self.add_equity("SPY", Resolution.TICK)
- self.add_equity("BAC", Resolution.MINUTE)
- self.add_equity("AIG", Resolution.HOUR)
- self.add_equity("IBM", Resolution.DAILY)
-
- self.__last_trade_ticks = self.start_date
- self.__last_trade_trade_bars = self.__last_trade_ticks
- self.__trade_every = timedelta(minutes=1)
-
-
- def on_data(self, data):
- '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.'''
- if self.time - self.__last_trade_trade_bars < self.__trade_every:
- return
- self.__last_trade_trade_bars = self.time
-
- for kvp in data.bars:
- bar = kvp.Value
- if bar.is_fill_forward:
- continue
-
- symbol = kvp.key
- holdings = self.portfolio[symbol]
-
- if not holdings.invested:
- self.market_order(symbol, 10)
- else:
- self.market_order(symbol, -holdings.quantity)
diff --git a/fincept-qt/scripts/strategies/RegressionChannelAlgorithm.py b/fincept-qt/scripts/strategies/RegressionChannelAlgorithm.py
deleted file mode 100644
index ffa7114d8..000000000
--- a/fincept-qt/scripts/strategies/RegressionChannelAlgorithm.py
+++ /dev/null
@@ -1,56 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-CB76FD5F
-# Category: Regression Test
-# Description: Regression Channel algorithm simply initializes the date range and cash
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Regression Channel algorithm simply initializes the date range and cash
-### </summary>
-### <meta name="tag" content="indicators" />
-### <meta name="tag" content="indicator classes" />
-### <meta name="tag" content="placing orders" />
-### <meta name="tag" content="plotting indicators" />
-class RegressionChannelAlgorithm(QCAlgorithm):
-
- def initialize(self):
-
- self.set_cash(100000)
- self.set_start_date(2009,1,1)
- self.set_end_date(2015,1,1)
-
- equity = self.add_equity("SPY", Resolution.MINUTE)
- self._spy = equity.symbol
- self._holdings = equity.holdings
- self._rc = self.rc(self._spy, 30, 2, Resolution.DAILY)
-
- stock_plot = Chart("Trade Plot")
- stock_plot.add_series(Series("Buy", SeriesType.SCATTER, 0))
- stock_plot.add_series(Series("Sell", SeriesType.SCATTER, 0))
- stock_plot.add_series(Series("UpperChannel", SeriesType.LINE, 0))
- stock_plot.add_series(Series("LowerChannel", SeriesType.LINE, 0))
- stock_plot.add_series(Series("Regression", SeriesType.LINE, 0))
- self.add_chart(stock_plot)
-
- def on_data(self, data):
- if (not self._rc.is_ready) or (not data.contains_key(self._spy)): return
- if data[self._spy] is None: return
- value = data[self._spy].value
- if self._holdings.quantity <= 0 and value < self._rc.lower_channel.current.value:
- self.set_holdings(self._spy, 1)
- self.plot("Trade Plot", "Buy", value)
- if self._holdings.quantity >= 0 and value > self._rc.upper_channel.current.value:
- self.set_holdings(self._spy, -1)
- self.plot("Trade Plot", "Sell", value)
-
- def on_end_of_day(self, symbol):
- self.plot("Trade Plot", "UpperChannel", self._rc.upper_channel.current.value)
- self.plot("Trade Plot", "LowerChannel", self._rc.lower_channel.current.value)
- self.plot("Trade Plot", "Regression", self._rc.linear_regression.current.value)
diff --git a/fincept-qt/scripts/strategies/Risk/__init__.py b/fincept-qt/scripts/strategies/Risk/__init__.py
deleted file mode 100644
index 862e18e32..000000000
--- a/fincept-qt/scripts/strategies/Risk/__init__.py
+++ /dev/null
@@ -1,36 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Risk Shim
-# Re-exports from fincept_engine + dynamic submodule stubs
-# ============================================================================
-
-import sys, os, types
-
-_parent = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
-if _parent not in sys.path:
- sys.path.insert(0, _parent)
-
-from fincept_engine.algorithm_imports import (
- RiskManagementModel, NullRiskManagementModel,
- MaximumDrawdownPercentPortfolio,
- MaximumDrawdownPercentPerSecurity,
- MaximumUnrealizedProfitPercentPerSecurity,
- TrailingStopRiskManagementModel,
- MaximumSectorExposureRiskManagementModel,
- CompositeRiskManagementModel
-)
-
-_submodules = {
- 'MaximumDrawdownPercentPortfolio': {'MaximumDrawdownPercentPortfolio': MaximumDrawdownPercentPortfolio},
- 'MaximumDrawdownPercentPerSecurity': {'MaximumDrawdownPercentPerSecurity': MaximumDrawdownPercentPerSecurity},
- 'MaximumUnrealizedProfitPercentPerSecurity': {'MaximumUnrealizedProfitPercentPerSecurity': MaximumUnrealizedProfitPercentPerSecurity},
- 'TrailingStopRiskManagementModel': {'TrailingStopRiskManagementModel': TrailingStopRiskManagementModel},
- 'MaximumSectorExposureRiskManagementModel': {'MaximumSectorExposureRiskManagementModel': MaximumSectorExposureRiskManagementModel},
- 'CompositeRiskManagementModel': {'CompositeRiskManagementModel': CompositeRiskManagementModel},
- 'NullRiskManagementModel': {'NullRiskManagementModel': NullRiskManagementModel},
-}
-
-for _name, _attrs in _submodules.items():
- _mod = types.ModuleType(f'Risk.{_name}')
- for _attr_name, _attr_val in _attrs.items():
- setattr(_mod, _attr_name, _attr_val)
- sys.modules[f'Risk.{_name}'] = _mod
diff --git a/fincept-qt/scripts/strategies/RiskParityPortfolioAlgorithm.py b/fincept-qt/scripts/strategies/RiskParityPortfolioAlgorithm.py
deleted file mode 100644
index e70af90b8..000000000
--- a/fincept-qt/scripts/strategies/RiskParityPortfolioAlgorithm.py
+++ /dev/null
@@ -1,28 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-4F8A816B
-# Category: Risk Management
-# Description: Example algorithm of using RiskParityPortfolioConstructionModel
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-from Portfolio.RiskParityPortfolioConstructionModel import *
-
-class RiskParityPortfolioAlgorithm(QCAlgorithm):
- '''Example algorithm of using RiskParityPortfolioConstructionModel'''
-
- def initialize(self):
- self.set_start_date(2021, 2, 21) # Set Start Date
- self.set_end_date(2021, 3, 30)
- self.set_cash(100000) # Set Strategy Cash
- self.set_security_initializer(lambda security: security.set_market_price(self.get_last_known_price(security)))
-
- self.add_equity("SPY", Resolution.DAILY)
- self.add_equity("AAPL", Resolution.DAILY)
-
- self.add_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(1)))
- self.set_portfolio_construction(RiskParityPortfolioConstructionModel())
diff --git a/fincept-qt/scripts/strategies/RollingWindowAlgorithm.py b/fincept-qt/scripts/strategies/RollingWindowAlgorithm.py
deleted file mode 100644
index 7602e3d95..000000000
--- a/fincept-qt/scripts/strategies/RollingWindowAlgorithm.py
+++ /dev/null
@@ -1,66 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-5A71E57F
-# Category: General Strategy
-# Description: Using rolling windows for efficient storage of historical data; which automatically clears after a period of time
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Using rolling windows for efficient storage of historical data; which automatically clears after a period of time.
-### </summary>
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="history and warm up" />
-### <meta name="tag" content="history" />
-### <meta name="tag" content="warm up" />
-### <meta name="tag" content="indicators" />
-### <meta name="tag" content="rolling windows" />
-class RollingWindowAlgorithm(QCAlgorithm):
-
- def initialize(self):
- '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
-
- self.set_start_date(2013,10,1) #Set Start Date
- self.set_end_date(2013,11,1) #Set End Date
- self.set_cash(100000) #Set Strategy Cash
- # Fincept Terminal Strategy Engine - Symbol Configuration
- self.add_equity("SPY", Resolution.DAILY)
-
- # Creates a Rolling Window indicator to keep the 2 TradeBar
- self.window = RollingWindow[TradeBar](2) # For other security types, use QuoteBar
-
- # Creates an indicator and adds to a rolling window when it is updated
- self.sma = self.SMA("SPY", 5)
- self.sma.updated += self.sma_updated
- self.sma_win = RollingWindow[IndicatorDataPoint](5)
-
-
- def sma_updated(self, sender, updated):
- '''Adds updated values to rolling window'''
- self.sma_win.add(updated)
-
-
- def on_data(self, data):
- '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.'''
-
- # Add SPY TradeBar in rollling window
- self.window.add(data["SPY"])
-
- # Wait for windows to be ready.
- if not (self.window.is_ready and self.sma_win.is_ready): return
-
- curr_bar = self.window[0] # Current bar had index zero.
- past_bar = self.window[1] # Past bar has index one.
- self.log("Price: {0} -> {1} ... {2} -> {3}".format(past_bar.time, past_bar.close, curr_bar.time, curr_bar.close))
-
- curr_sma = self.sma_win[0] # Current SMA had index zero.
- past_sma = self.sma_win[self.sma_win.count-1] # Oldest SMA has index of window count minus 1.
- self.log("SMA: {0} -> {1} ... {2} -> {3}".format(past_sma.time, past_sma.value, curr_sma.time, curr_sma.value))
-
- if not self.portfolio.invested and curr_sma.value > past_sma.value:
- self.set_holdings("SPY", 1)
diff --git a/fincept-qt/scripts/strategies/RsiAlphaModelFrameworkRegressionAlgorithm.py b/fincept-qt/scripts/strategies/RsiAlphaModelFrameworkRegressionAlgorithm.py
deleted file mode 100644
index 101b93c18..000000000
--- a/fincept-qt/scripts/strategies/RsiAlphaModelFrameworkRegressionAlgorithm.py
+++ /dev/null
@@ -1,29 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-2CBD0408
-# Category: Alpha Model
-# Description: Regression algorithm to assert the behavior of <see cref="RsiAlphaModel"/>
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-from BaseFrameworkRegressionAlgorithm import BaseFrameworkRegressionAlgorithm
-from Alphas.RsiAlphaModel import RsiAlphaModel
-
-### <summary>
-### Regression algorithm to assert the behavior of <see cref="RsiAlphaModel"/>.
-### </summary>
-class RsiAlphaModelFrameworkRegressionAlgorithm(BaseFrameworkRegressionAlgorithm):
-
- def initialize(self):
- super().initialize()
- self.set_alpha(RsiAlphaModel())
-
- def on_end_of_algorithm(self):
- # We have removed all securities from the universe. The Alpha Model should remove the consolidator
- consolidator_count = sum([s.consolidators.count for s in self.subscription_manager.subscriptions])
- if consolidator_count > 0:
- raise Exception(f"The number of consolidators should be zero. Actual: {consolidator_count}")
diff --git a/fincept-qt/scripts/strategies/ScheduledEventsAlgorithm.py b/fincept-qt/scripts/strategies/ScheduledEventsAlgorithm.py
deleted file mode 100644
index cc4ff3efa..000000000
--- a/fincept-qt/scripts/strategies/ScheduledEventsAlgorithm.py
+++ /dev/null
@@ -1,97 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-9781F28A
-# Category: Scheduled Events
-# Description: Demonstration of the Scheduled Events features available in QuantConnect
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Demonstration of the Scheduled Events features available in QuantConnect.
-### </summary>
-### <meta name="tag" content="scheduled events" />
-### <meta name="tag" content="date rules" />
-### <meta name="tag" content="time rules" />
-class ScheduledEventsAlgorithm(QCAlgorithm):
-
- def initialize(self):
- '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
-
- self.set_start_date(2013,10,7) #Set Start Date
- self.set_end_date(2013,10,11) #Set End Date
- self.set_cash(100000) #Set Strategy Cash
- # Fincept Terminal Strategy Engine - Symbol Configuration
- self.add_equity("SPY")
-
- # events are scheduled using date and time rules
- # date rules specify on what dates and event will fire
- # time rules specify at what time on thos dates the event will fire
-
- # schedule an event to fire at a specific date/time
- self.schedule.on(self.date_rules.on(2013, 10, 7), self.time_rules.at(13, 0), self.specific_time)
-
- # schedule an event to fire every trading day for a security the
- # time rule here tells it to fire 10 minutes after SPY's market open
- self.schedule.on(self.date_rules.every_day("SPY"), self.time_rules.after_market_open("SPY", 10), self.every_day_after_market_open)
-
- # schedule an event to fire every trading day for a security the
- # time rule here tells it to fire 10 minutes before SPY's market close
- self.schedule.on(self.date_rules.every_day("SPY"), self.time_rules.before_market_close("SPY", 10), self.every_day_after_market_close)
-
- # schedule an event to fire on a single day of the week
- self.schedule.on(self.date_rules.every(DayOfWeek.WEDNESDAY), self.time_rules.at(12, 0), self.every_wed_at_noon)
-
- # schedule an event to fire on certain days of the week
- self.schedule.on(self.date_rules.every(DayOfWeek.MONDAY, DayOfWeek.FRIDAY), self.time_rules.at(12, 0), self.every_mon_fri_at_noon)
-
- # the scheduling methods return the ScheduledEvent object which can be used for other things here I set
- # the event up to check the portfolio value every 10 minutes, and liquidate if we have too many losses
- self.schedule.on(self.date_rules.every_day(), self.time_rules.every(timedelta(minutes=10)), self.liquidate_unrealized_losses)
-
- # schedule an event to fire at the beginning of the month, the symbol is optional
- # if specified, it will fire the first trading day for that symbol of the month,
- # if not specified it will fire on the first day of the month
- self.schedule.on(self.date_rules.month_start("SPY"), self.time_rules.after_market_open("SPY"), self.rebalancing_code)
-
-
- def on_data(self, data):
- '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.'''
- if not self.portfolio.invested:
- self.set_holdings("SPY", 1)
-
-
- def specific_time(self):
- self.log(f"SpecificTime: Fired at : {self.time}")
-
-
- def every_day_after_market_open(self):
- self.log(f"EveryDay.SPY 10 min after open: Fired at: {self.time}")
-
-
- def every_day_after_market_close(self):
- self.log(f"EveryDay.SPY 10 min before close: Fired at: {self.time}")
-
-
- def every_wed_at_noon(self):
- self.log(f"Wed at 12pm: Fired at: {self.time}")
-
-
- def every_mon_fri_at_noon(self):
- self.log(f"Mon/Fri at 12pm: Fired at: {self.time}")
-
-
- def liquidate_unrealized_losses(self):
- ''' if we have over 1000 dollars in unrealized losses, liquidate'''
- if self.portfolio.total_unrealized_profit < -1000:
- self.log(f"Liquidated due to unrealized losses at: {self.time}")
- self.liquidate()
-
-
- def rebalancing_code(self):
- ''' Good spot for rebalancing code?'''
- pass
diff --git a/fincept-qt/scripts/strategies/ScheduledQueuingAlgorithm.py b/fincept-qt/scripts/strategies/ScheduledQueuingAlgorithm.py
deleted file mode 100644
index 87ff11a31..000000000
--- a/fincept-qt/scripts/strategies/ScheduledQueuingAlgorithm.py
+++ /dev/null
@@ -1,59 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-BC10DFCE
-# Category: Scheduled Events
-# Description: Scheduled Queuing Algorithm
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-from queue import Queue
-
-class ScheduledQueuingAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2020, 9, 1)
- self.set_end_date(2020, 9, 2)
- self.set_cash(100000)
-
- self.__number_of_symbols = 2000
- self.__number_of_symbols_fine = 1000
- self.set_universe_selection(FineFundamentalUniverseSelectionModel(self.coarse_selection_function, self.fine_selection_function, None))
-
- self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())
-
- self.set_execution(ImmediateExecutionModel())
-
- self.queue = Queue()
- self.dequeue_size = 100
-
- self.add_equity("SPY", Resolution.MINUTE)
- self.schedule.on(self.date_rules.every_day("SPY"), self.time_rules.at(0, 0), self.fill_queue)
- self.schedule.on(self.date_rules.every_day("SPY"), self.time_rules.every(timedelta(minutes=60)), self.take_from_queue)
-
- def coarse_selection_function(self, coarse):
- has_fundamentals = [security for security in coarse if security.has_fundamental_data]
- sorted_by_dollar_volume = sorted(has_fundamentals, key=lambda x: x.dollar_volume, reverse=True)
- return [ x.symbol for x in sorted_by_dollar_volume[:self.__number_of_symbols] ]
-
- def fine_selection_function(self, fine):
- sorted_by_pe_ratio = sorted(fine, key=lambda x: x.valuation_ratios.pe_ratio, reverse=True)
- return [ x.symbol for x in sorted_by_pe_ratio[:self.__number_of_symbols_fine] ]
-
- def fill_queue(self):
- securities = [security for security in self.active_securities.values() if security.fundamentals is not None]
-
- # Fill queue with symbols sorted by PE ratio (decreasing order)
- self.queue.queue.clear()
- sorted_by_pe_ratio = sorted(securities, key=lambda x: x.fundamentals.valuation_ratios.pe_ratio, reverse=True)
- for security in sorted_by_pe_ratio:
- self.queue.put(security.symbol)
-
- def take_from_queue(self):
- symbols = [self.queue.get() for _ in range(min(self.dequeue_size, self.queue.qsize()))]
- self.history(symbols, 10, Resolution.DAILY)
-
- self.log(f"Symbols at {self.time}: {[str(symbol) for symbol in symbols]}")
diff --git a/fincept-qt/scripts/strategies/ScheduledUniverseRegressionAlgorithm.py b/fincept-qt/scripts/strategies/ScheduledUniverseRegressionAlgorithm.py
deleted file mode 100644
index a82882afe..000000000
--- a/fincept-qt/scripts/strategies/ScheduledUniverseRegressionAlgorithm.py
+++ /dev/null
@@ -1,49 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-AE6D38CF
-# Category: Universe Selection
-# Description: Regression algorithm asserting the behavior of a ScheduledUniverse
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Regression algorithm asserting the behavior of a ScheduledUniverse
-### </summary>
-class BasicTemplateAlgorithm(QCAlgorithm):
- def initialize(self):
- '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
-
- self.set_start_date(2013,10, 7)
- self.set_end_date(2013,10, 8)
-
- self._spy = Symbol.create("SPY", SecurityType.EQUITY, Market.USA)
- self._selection_time =[ datetime(2013, 10, 7, 1, 0, 0), datetime(2013, 10, 8, 1, 0, 0)]
-
- self.add_universe(ScheduledUniverse(self.date_rules.every_day(), self.time_rules.at(1, 0), self.select_assets))
-
-
- def select_assets(self, time):
- self.debug(f"Universe selection called: {Time}")
- expected_time = self._selection_time.pop(0)
- if expected_time != self.time:
- raise ValueError(f"Unexpected selection time {self.time} expected {expected_time}")
-
- return [ self._spy ]
-
- def on_data(self, data):
- '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
-
- Arguments:
- data: Slice object keyed by symbol containing the stock data
- '''
- if not self.portfolio.invested:
- self.set_holdings(self._spy, 1)
-
- def on_end_of_algorithm(self):
- if len(self._selection_time) > 0:
- raise ValueError("Unexpected selection times")
diff --git a/fincept-qt/scripts/strategies/ScheduledUniverseSelectionModelRegressionAlgorithm.py b/fincept-qt/scripts/strategies/ScheduledUniverseSelectionModelRegressionAlgorithm.py
deleted file mode 100644
index d21b4c9ae..000000000
--- a/fincept-qt/scripts/strategies/ScheduledUniverseSelectionModelRegressionAlgorithm.py
+++ /dev/null
@@ -1,115 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-3F154B00
-# Category: Universe Selection
-# Description: Regression algorithm for testing ScheduledUniverseSelectionModel scheduling functions
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Regression algorithm for testing ScheduledUniverseSelectionModel scheduling functions.
-### </summary>
-class ScheduledUniverseSelectionModelRegressionAlgorithm(QCAlgorithm):
- '''Regression algorithm for testing ScheduledUniverseSelectionModel scheduling functions.'''
-
- def initialize(self):
-
- self.universe_settings.resolution = Resolution.HOUR
-
- # Order margin value has to have a minimum of 0.5% of Portfolio value, allows filtering out small trades and reduce fees.
- # Commented so regression algorithm is more sensitive
- #self.settings.minimum_order_margin_portfolio_percentage = 0.005
-
- self.set_start_date(2017, 1, 1)
- self.set_end_date(2017, 2, 1)
-
- # selection will run on mon/tues/thurs at 00:00/06:00/12:00/18:00
- self.set_universe_selection(ScheduledUniverseSelectionModel(
- self.date_rules.every(DayOfWeek.MONDAY, DayOfWeek.TUESDAY, DayOfWeek.THURSDAY),
- self.time_rules.every(timedelta(hours = 12)),
- self.select_symbols
- ))
-
- self.set_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(1)))
- self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())
-
- # some days of the week have different behavior the first time -- less securities to remove
- self.seen_days = []
-
- def select_symbols(self, dateTime):
-
- symbols = []
- weekday = dateTime.weekday()
-
- if weekday == 0 or weekday == 1:
- symbols.append(Symbol.create('SPY', SecurityType.EQUITY, Market.USA))
- elif weekday == 2:
- # given the date/time rules specified in Initialize, this symbol will never be selected (not invoked on wednesdays)
- symbols.append(Symbol.create('AAPL', SecurityType.EQUITY, Market.USA))
- else:
- symbols.append(Symbol.create('IBM', SecurityType.EQUITY, Market.USA))
-
- if weekday == 1 or weekday == 3:
- symbols.append(Symbol.create('EURUSD', SecurityType.FOREX, Market.OANDA))
- elif weekday == 4:
- # given the date/time rules specified in Initialize, this symbol will never be selected (every 6 hours never lands on hour==1)
- symbols.append(Symbol.create('EURGBP', SecurityType.FOREX, Market.OANDA))
- else:
- symbols.append(Symbol.create('NZDUSD', SecurityType.FOREX, Market.OANDA))
-
- return symbols
-
- def on_securities_changed(self, changes):
- self.log("{}: {}".format(self.time, changes))
-
- weekday = self.time.weekday()
-
- if weekday == 0:
- self.expect_additions(changes, 'SPY', 'NZDUSD')
- if weekday not in self.seen_days:
- self.seen_days.append(weekday)
- self.expect_removals(changes, None)
- else:
- self.expect_removals(changes, 'EURUSD', 'IBM')
-
- if weekday == 1:
- self.expect_additions(changes, 'EURUSD')
- if weekday not in self.seen_days:
- self.seen_days.append(weekday)
- self.expect_removals(changes, 'NZDUSD')
- else:
- self.expect_removals(changes, 'NZDUSD')
-
- if weekday == 2 or weekday == 4:
- # selection function not invoked on wednesdays (2) or friday (4)
- self.expect_additions(changes, None)
- self.expect_removals(changes, None)
-
- if weekday == 3:
- self.expect_additions(changes, "IBM")
- self.expect_removals(changes, "SPY")
-
-
- def on_order_event(self, orderEvent):
- self.log("{}: {}".format(self.time, orderEvent))
-
- def expect_additions(self, changes, *tickers):
- if tickers is None and changes.added_securities.count > 0:
- raise Exception("{}: Expected no additions: {}".format(self.time, self.time.weekday()))
-
- for ticker in tickers:
- if ticker is not None and ticker not in [s.symbol.value for s in changes.added_securities]:
- raise Exception("{}: Expected {} to be added: {}".format(self.time, ticker, self.time.weekday()))
-
- def expect_removals(self, changes, *tickers):
- if tickers is None and changes.removed_securities.count > 0:
- raise Exception("{}: Expected no removals: {}".format(self.time, self.time.weekday()))
-
- for ticker in tickers:
- if ticker is not None and ticker not in [s.symbol.value for s in changes.removed_securities]:
- raise Exception("{}: Expected {} to be removed: {}".format(self.time, ticker, self.time.weekday()))
diff --git a/fincept-qt/scripts/strategies/ScikitLearnLinearRegressionAlgorithm.py b/fincept-qt/scripts/strategies/ScikitLearnLinearRegressionAlgorithm.py
deleted file mode 100644
index 8a266e7d0..000000000
--- a/fincept-qt/scripts/strategies/ScikitLearnLinearRegressionAlgorithm.py
+++ /dev/null
@@ -1,56 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-1244BB8B
-# Category: Regression Test
-# Description: Linear regression momentum strategy. Uses a rolling 30-period
-# price window to compute linear regression slope. Buys when slope is
-# positive (uptrend), sells when slope turns negative.
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-class ScikitLearnLinearRegressionAlgorithm(QCAlgorithm):
- """Linear regression slope momentum strategy."""
-
- def initialize(self):
- self.set_start_date(2023, 1, 1)
- self.set_end_date(2024, 1, 1)
- self.set_cash(100000)
-
- self.symbol = "SPY"
- self.add_equity(self.symbol, Resolution.DAILY)
-
- self._lookback = 30
- self._prices = []
-
- def on_data(self, data):
- if self.symbol not in data:
- return
-
- price = data[self.symbol].close
- self._prices.append(price)
- if len(self._prices) > self._lookback:
- self._prices = self._prices[-self._lookback:]
-
- if len(self._prices) < self._lookback:
- return
-
- # Simple linear regression slope
- n = len(self._prices)
- x_mean = (n - 1) / 2.0
- y_mean = sum(self._prices) / n
- numerator = sum((i - x_mean) * (p - y_mean) for i, p in enumerate(self._prices))
- denominator = sum((i - x_mean) ** 2 for i in range(n))
- slope = numerator / denominator if denominator != 0 else 0
-
- # Normalize slope by price level
- norm_slope = slope / y_mean if y_mean != 0 else 0
-
- if not self.portfolio.invested and norm_slope > 0.001:
- self.set_holdings(self.symbol, 1)
- elif self.portfolio.invested and norm_slope < -0.001:
- self.liquidate()
diff --git a/fincept-qt/scripts/strategies/SectorExposureRiskFrameworkAlgorithm.py b/fincept-qt/scripts/strategies/SectorExposureRiskFrameworkAlgorithm.py
deleted file mode 100644
index 37c3def32..000000000
--- a/fincept-qt/scripts/strategies/SectorExposureRiskFrameworkAlgorithm.py
+++ /dev/null
@@ -1,50 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-9159A849
-# Category: Risk Management
-# Description: This example algorithm defines its own custom coarse/fine fundamental selection model with equally weighted portfolio...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-from Portfolio.EqualWeightingPortfolioConstructionModel import EqualWeightingPortfolioConstructionModel
-from Alphas.ConstantAlphaModel import ConstantAlphaModel
-from Execution.ImmediateExecutionModel import ImmediateExecutionModel
-from Risk.MaximumSectorExposureRiskManagementModel import MaximumSectorExposureRiskManagementModel
-
-### <summary>
-### This example algorithm defines its own custom coarse/fine fundamental selection model
-### with equally weighted portfolio and a maximum sector exposure.
-### </summary>
-class SectorExposureRiskFrameworkAlgorithm(QCAlgorithm):
- '''This example algorithm defines its own custom coarse/fine fundamental selection model
-### with equally weighted portfolio and a maximum sector exposure.'''
-
- def initialize(self):
-
- # Set requested data resolution
- self.universe_settings.resolution = Resolution.DAILY
-
- self.set_start_date(2014, 3, 25)
- self.set_end_date(2014, 4, 7)
- self.set_cash(100000)
-
- # set algorithm framework models
- self.set_universe_selection(FineFundamentalUniverseSelectionModel(self.select_coarse, self.select_fine))
- self.set_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(1)))
- self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())
- self.set_risk_management(MaximumSectorExposureRiskManagementModel())
-
- def on_order_event(self, order_event):
- if order_event.status == OrderStatus.FILLED:
- self.debug(f"Order event: {order_event}. Holding value: {self.securities[order_event.symbol].holdings.absolute_holdings_value}")
-
- def select_coarse(self, coarse):
- tickers = ["AAPL", "AIG", "IBM"] if self.time.date() < date(2014, 4, 1) else [ "GOOG", "BAC", "SPY" ]
- return [Symbol.create(x, SecurityType.EQUITY, Market.USA) for x in tickers]
-
- def select_fine(self, fine):
- return [f.symbol for f in fine]
diff --git a/fincept-qt/scripts/strategies/SectorWeightingFrameworkAlgorithm.py b/fincept-qt/scripts/strategies/SectorWeightingFrameworkAlgorithm.py
deleted file mode 100644
index 69b43b050..000000000
--- a/fincept-qt/scripts/strategies/SectorWeightingFrameworkAlgorithm.py
+++ /dev/null
@@ -1,46 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-F578C144
-# Category: General Strategy
-# Description: This example algorithm defines its own custom coarse/fine fundamental selection model with sector weighted portfolio
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### This example algorithm defines its own custom coarse/fine fundamental selection model
-### with sector weighted portfolio.
-### </summary>
-class SectorWeightingFrameworkAlgorithm(QCAlgorithm):
- '''This example algorithm defines its own custom coarse/fine fundamental selection model
- with sector weighted portfolio.'''
-
- def initialize(self):
-
- # Set requested data resolution
- self.universe_settings.resolution = Resolution.DAILY
-
- self.set_start_date(2014, 4, 2)
- self.set_end_date(2014, 4, 6)
- self.set_cash(100000)
-
- # set algorithm framework models
- self.set_universe_selection(FineFundamentalUniverseSelectionModel(self.select_coarse, self.select_fine))
- self.set_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(1)))
- self.set_portfolio_construction(SectorWeightingPortfolioConstructionModel())
-
- def on_order_event(self, order_event):
- if order_event.status == OrderStatus.FILLED:
- self.debug(f"Order event: {order_event}. Holding value: {self.securities[order_event.symbol].holdings.absolute_holdings_value}")
-
- def select_coarse(self, coarse):
- # IndustryTemplateCode of AAPL, IBM and GOOG is N, AIG is I, BAC is B. SPY have no fundamentals
- tickers = ["AAPL", "AIG", "IBM"] if self.time.date() < date(2014, 4, 4) else [ "GOOG", "BAC", "SPY" ]
- return [Symbol.create(x, SecurityType.EQUITY, Market.USA) for x in tickers]
-
- def select_fine(self, fine):
- return [f.symbol for f in fine]
diff --git a/fincept-qt/scripts/strategies/SecurityCustomPropertiesAlgorithm.py b/fincept-qt/scripts/strategies/SecurityCustomPropertiesAlgorithm.py
deleted file mode 100644
index 2c9f6c81b..000000000
--- a/fincept-qt/scripts/strategies/SecurityCustomPropertiesAlgorithm.py
+++ /dev/null
@@ -1,88 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-B0B2E65B
-# Category: General Strategy
-# Description: Demonstration of how to use custom security properties. In this algorithm we trade a security based on the values of ...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from cmath import isclose
-from AlgorithmImports import *
-
-### <summary>
-### Demonstration of how to use custom security properties.
-### In this algorithm we trade a security based on the values of a slow and fast EMAs which are stored in the security itself.
-### </summary>
-class SecurityCustomPropertiesAlgorithm(QCAlgorithm):
- '''Demonstration of how to use custom security properties.
- In this algorithm we trade a security based on the values of a slow and fast EMAs which are stored in the security itself.'''
-
- def initialize(self):
- self.set_start_date(2013,10, 7)
- self.set_end_date(2013,10,11)
- self.set_cash(100000)
-
- self.spy = self.add_equity("SPY", Resolution.MINUTE)
-
- # Using the dynamic interface to store our indicator as a custom property.
- self.spy.slow_ema = self.ema(self.spy.symbol, 30, Resolution.MINUTE)
-
- # Using the generic interface to store our indicator as a custom property.
- self.spy.add("fast_ema", self.ema(self.spy.symbol, 60, Resolution.MINUTE))
-
- # Using the indexer to store our indicator as a custom property
- self.spy["bb"] = self.bb(self.spy.symbol, 20, 1, MovingAverageType.SIMPLE, Resolution.MINUTE)
-
- # Fee factor to be used by the custom fee model
- self.spy.fee_factor = 0.00002
- self.spy.set_fee_model(CustomFeeModel())
-
- # This property will be used to store the prices used to calculate the fees in order to assert the correct fee factor is used.
- self.spy.orders_fees_prices = {}
-
- def on_data(self, data):
- if not self.spy.fast_ema.is_ready:
- return
-
- if not self.portfolio.invested:
- # Using the property and the generic interface to access our indicator
- if self.spy.slow_ema > self.spy.fast_ema:
- self.set_holdings(self.spy.symbol, 1)
- else:
- if self.spy.get[ExponentialMovingAverage]("slow_ema") < self.spy.get[ExponentialMovingAverage]("fast_ema"):
- self.liquidate(self.spy.symbol)
-
- # Using the indexer to access our indicator
- bb: BollingerBands = self.spy["bb"]
- self.plot("bb", bb.upper_band, bb.middle_band, bb.lower_band)
-
- def on_order_event(self, order_event):
- if order_event.status == OrderStatus.FILLED:
- fee = order_event.order_fee
- expected_fee = self.spy.orders_fees_prices[order_event.order_id] * order_event.absolute_fill_quantity * self.spy.fee_factor
- if not isclose(fee.value.amount, expected_fee, rel_tol=1e-15):
- raise Exception(f"Custom fee model failed to set the correct fee. Expected: {expected_fee}. Actual: {fee.value.amount}")
-
- def on_end_of_algorithm(self):
- if self.transactions.orders_count == 0:
- raise Exception("No orders executed")
-
-class CustomFeeModel(FeeModel):
- '''This custom fee is implemented for demonstration purposes only.'''
-
- def get_order_fee(self, parameters):
- security = parameters.security
- # custom fee math using the fee factor stored in security instance
- fee_factor = security.fee_factor
- if fee_factor is None:
- fee_factor = 0.00001
-
- # Store the price used to calculate the fee for this order
- security["orders_fees_prices"][parameters.order.id] = security.price
-
- fee = max(1.0, security.price * parameters.order.absolute_quantity * fee_factor)
-
- return OrderFee(CashAmount(fee, "USD"))
diff --git a/fincept-qt/scripts/strategies/SecurityDynamicPropertyPythonClassAlgorithm.py b/fincept-qt/scripts/strategies/SecurityDynamicPropertyPythonClassAlgorithm.py
deleted file mode 100644
index 01c22d756..000000000
--- a/fincept-qt/scripts/strategies/SecurityDynamicPropertyPythonClassAlgorithm.py
+++ /dev/null
@@ -1,56 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-B2BE2584
-# Category: General Strategy
-# Description: Algorithm asserting that security dynamic properties keep Python references to the Python class they are instances of...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-from collections import deque
-
-### <summary>
-### Algorithm asserting that security dynamic properties keep Python references to the Python class they are instances of,
-### specifically when this class is a subclass of a C# class.
-### </summary>
-class SecurityDynamicPropertyPythonClassAlgorithm(QCAlgorithm):
- def initialize(self):
- self.set_start_date(2013, 10, 7)
- self.set_end_date(2013, 10, 7)
-
- self.spy = self.add_equity("SPY", Resolution.MINUTE)
-
- custom_sma = CustomSimpleMovingAverage('custom', 60)
- self.spy.custom_sma = custom_sma
- custom_sma.security = self.spy
-
- self.register_indicator(self.spy.symbol, self.spy.custom_sma, Resolution.MINUTE)
-
- def on_warmup_finished(self) -> None:
- if type(self.spy.custom_sma) != CustomSimpleMovingAverage:
- raise Exception("spy.custom_sma is not an instance of CustomSimpleMovingAverage")
-
- if self.spy.custom_sma.security is None:
- raise Exception("spy.custom_sma.security is None")
- else:
- self.debug(f"spy.custom_sma.security.symbol: {self.spy.custom_sma.security.symbol}")
-
- def on_data(self, slice: Slice) -> None:
- if self.spy.custom_sma.is_ready:
- self.debug(f"CustomSMA: {self.spy.custom_sma.current.value}")
-
-class CustomSimpleMovingAverage(PythonIndicator):
- def __init__(self, name, period):
- super().__init__()
- self.name = name
- self.value = 0
- self.queue = deque(maxlen=period)
-
- def update(self, input):
- self.queue.appendleft(input.value)
- count = len(self.queue)
- self.value = np.sum(self.queue) / count
- return count == self.queue.maxlen
diff --git a/fincept-qt/scripts/strategies/SecuritySeederRegressionAlgorithm.py b/fincept-qt/scripts/strategies/SecuritySeederRegressionAlgorithm.py
deleted file mode 100644
index 8a23fccca..000000000
--- a/fincept-qt/scripts/strategies/SecuritySeederRegressionAlgorithm.py
+++ /dev/null
@@ -1,50 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-79957FB5
-# Category: Regression Test
-# Description: Regression algorithm reproducing GH issue #5921. Asserting a security can be warmup correctly on initialize
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Regression algorithm reproducing GH issue #5921. Asserting a security can be warmup correctly on initialize
-### </summary>
-class SecuritySeederRegressionAlgorithm(QCAlgorithm):
- def initialize(self):
- '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
-
- self.set_start_date(2013,10, 8)
- self.set_end_date(2013,10,10)
-
- self.set_security_initializer(BrokerageModelSecurityInitializer(self.brokerage_model,
- FuncSecuritySeeder(self.get_last_known_prices)))
- self.add_equity("SPY", Resolution.MINUTE)
-
- def on_data(self, data):
- '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
-
- Arguments:
- data: Slice object keyed by symbol containing the stock data
- '''
- if not self.portfolio.invested:
- self.set_holdings("SPY", 1)
-
- def on_securities_changed(self, changes):
- for added_security in changes.added_securities:
- if not added_security.has_data \
- or added_security.ask_price == 0 \
- or added_security.bid_price == 0 \
- or added_security.bid_size == 0 \
- or added_security.ask_size == 0 \
- or added_security.price == 0 \
- or added_security.volume == 0 \
- or added_security.high == 0 \
- or added_security.low == 0 \
- or added_security.open == 0 \
- or added_security.close == 0:
- raise ValueError(f"Security {added_security.symbol} was not warmed up!")
diff --git a/fincept-qt/scripts/strategies/SelectUniverseSymbolsFromIDRegressionAlgorithm.py b/fincept-qt/scripts/strategies/SelectUniverseSymbolsFromIDRegressionAlgorithm.py
deleted file mode 100644
index 4c7265a2e..000000000
--- a/fincept-qt/scripts/strategies/SelectUniverseSymbolsFromIDRegressionAlgorithm.py
+++ /dev/null
@@ -1,54 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-BCEB1931
-# Category: Universe Selection
-# Description: Regression algorithm asserting that universe symbols selection can be done by returning the symbol IDs in the selecti...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Regression algorithm asserting that universe symbols selection can be done by returning the symbol IDs in the selection function
-### </summary>
-class SelectUniverseSymbolsFromIDRegressionAlgorithm(QCAlgorithm):
- '''
- Regression algorithm asserting that universe symbols selection can be done by returning the symbol IDs in the selection function
- '''
-
- def initialize(self):
- self.set_start_date(2014, 3, 24)
- self.set_end_date(2014, 3, 26)
- self.set_cash(100000)
-
- self._securities = []
- self.universe_settings.resolution = Resolution.DAILY
- self.add_universe(self.select_symbol)
-
- def select_symbol(self, fundamental):
- symbols = [x.symbol for x in fundamental]
-
- if not symbols:
- return []
-
- self.log(f"Symbols: {', '.join([str(s) for s in symbols])}")
- # Just for testing, but more filtering could be done here as shown below:
- #symbols = [x.symbol for x in fundamental if x.asset_classification.morningstar_sector_code == MorningstarSectorCode.TECHNOLOGY]
-
- history = self.history(symbols, datetime(1998, 1, 1), self.time, Resolution.DAILY)
-
- all_time_highs = history['high'].unstack(0).max()
- last_closes = history['close'].unstack(0).iloc[-1]
- security_ids = (last_closes / all_time_highs).sort_values().index[-5:]
-
- return security_ids
-
- def on_securities_changed(self, changes):
- self._securities.extend(changes.added_securities)
-
- def on_end_of_algorithm(self):
- if not self._securities:
- raise Exception("No securities were selected")
diff --git a/fincept-qt/scripts/strategies/Selection/__init__.py b/fincept-qt/scripts/strategies/Selection/__init__.py
deleted file mode 100644
index 4edaba5cf..000000000
--- a/fincept-qt/scripts/strategies/Selection/__init__.py
+++ /dev/null
@@ -1,50 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Selection Shim
-# Re-exports from fincept_engine + dynamic submodule stubs
-# ============================================================================
-
-import sys, os, types
-
-_parent = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
-if _parent not in sys.path:
- sys.path.insert(0, _parent)
-
-from fincept_engine.algorithm_imports import (
- UniverseSelectionModel,
- ManualUniverseSelectionModel,
- FundamentalUniverseSelectionModel,
- ScheduledUniverseSelectionModel,
- CustomUniverseSelectionModel,
- CoarseFundamental, FineFundamental,
- UniverseSettings, Universe, Field,
- CoarseFundamentalUniverseSelectionModel,
- FineFundamentalUniverseSelectionModel,
- ConstituentsUniverse,
- ScheduledUniverse,
- OptionChainedUniverseSelectionModel,
- OpenInterestFutureUniverseSelectionModel
-)
-from fincept_engine.framework.selection import (
- OptionUniverseSelectionModel, FutureUniverseSelectionModel,
- ETFConstituentsUniverseSelectionModel, QC500UniverseSelectionModel
-)
-
-_submodules = {
- 'ManualUniverseSelectionModel': {'ManualUniverseSelectionModel': ManualUniverseSelectionModel},
- 'FundamentalUniverseSelectionModel': {'FundamentalUniverseSelectionModel': FundamentalUniverseSelectionModel},
- 'ScheduledUniverseSelectionModel': {'ScheduledUniverseSelectionModel': ScheduledUniverseSelectionModel},
- 'OptionUniverseSelectionModel': {'OptionUniverseSelectionModel': OptionUniverseSelectionModel},
- 'FutureUniverseSelectionModel': {'FutureUniverseSelectionModel': FutureUniverseSelectionModel},
- 'ETFConstituentsUniverseSelectionModel': {'ETFConstituentsUniverseSelectionModel': ETFConstituentsUniverseSelectionModel},
- 'QC500UniverseSelectionModel': {'QC500UniverseSelectionModel': QC500UniverseSelectionModel},
- 'CoarseFundamentalUniverseSelectionModel': {'CoarseFundamentalUniverseSelectionModel': CoarseFundamentalUniverseSelectionModel},
- 'FineFundamentalUniverseSelectionModel': {'FineFundamentalUniverseSelectionModel': FineFundamentalUniverseSelectionModel},
- 'OptionChainedUniverseSelectionModel': {'OptionChainedUniverseSelectionModel': OptionChainedUniverseSelectionModel},
- 'OpenInterestFutureUniverseSelectionModel': {'OpenInterestFutureUniverseSelectionModel': OpenInterestFutureUniverseSelectionModel},
-}
-
-for _name, _attrs in _submodules.items():
- _mod = types.ModuleType(f'Selection.{_name}')
- for _attr_name, _attr_val in _attrs.items():
- setattr(_mod, _attr_name, _attr_val)
- sys.modules[f'Selection.{_name}'] = _mod
diff --git a/fincept-qt/scripts/strategies/SetCustomSettlementModelRegressionAlgorithm.py b/fincept-qt/scripts/strategies/SetCustomSettlementModelRegressionAlgorithm.py
deleted file mode 100644
index 26dafeb73..000000000
--- a/fincept-qt/scripts/strategies/SetCustomSettlementModelRegressionAlgorithm.py
+++ /dev/null
@@ -1,21 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-86D91C89
-# Category: Regression Test
-# Description: Regression algorithm to test we can specify a custom settlement model using Security.set_settlement_model() method (w...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-from CustomSettlementModelRegressionAlgorithm import CustomSettlementModel, CustomSettlementModelRegressionAlgorithm
-
-### <summary>
-### Regression algorithm to test we can specify a custom settlement model using Security.set_settlement_model() method
-### (without a custom brokerage model)
-### </summary>
-class SetCustomSettlementModelRegressionAlgorithm(CustomSettlementModelRegressionAlgorithm):
- def set_settlement_model(self, security):
- security.set_settlement_model(CustomSettlementModel())
diff --git a/fincept-qt/scripts/strategies/SetEquityDataNormalizationModeOnAddEquity.py b/fincept-qt/scripts/strategies/SetEquityDataNormalizationModeOnAddEquity.py
deleted file mode 100644
index ebc8e8ec5..000000000
--- a/fincept-qt/scripts/strategies/SetEquityDataNormalizationModeOnAddEquity.py
+++ /dev/null
@@ -1,51 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-D64ED04F
-# Category: General Strategy
-# Description: This regression algorithm has examples of how to add an equity indicating the <see cref="DataNormalizationMode"/> dir...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### This regression algorithm has examples of how to add an equity indicating the <see cref="DataNormalizationMode"/>
-### directly with the <see cref="QCAlgorithm.add_equity"/> method instead of using the <see cref="Equity.SET_DATA_NORMALIZATION_MODE"/> method.
-### </summary>
-class SetEquityDataNormalizationModeOnAddEquity(QCAlgorithm):
- def initialize(self):
- self.set_start_date(2013, 10, 7)
- self.set_end_date(2013, 10, 7)
-
- spy_normalization_mode = DataNormalizationMode.RAW
- ibm_normalization_mode = DataNormalizationMode.ADJUSTED
- aig_normalization_mode = DataNormalizationMode.TOTAL_RETURN
-
- self._price_ranges = {}
-
- spy_equity = self.add_equity("SPY", Resolution.MINUTE, data_normalization_mode=spy_normalization_mode)
- self.check_equity_data_normalization_mode(spy_equity, spy_normalization_mode)
- self._price_ranges[spy_equity] = (167.28, 168.37)
-
- ibm_equity = self.add_equity("IBM", Resolution.MINUTE, data_normalization_mode=ibm_normalization_mode)
- self.check_equity_data_normalization_mode(ibm_equity, ibm_normalization_mode)
- self._price_ranges[ibm_equity] = (135.864131052, 136.819606508)
-
- aig_equity = self.add_equity("AIG", Resolution.MINUTE, data_normalization_mode=aig_normalization_mode)
- self.check_equity_data_normalization_mode(aig_equity, aig_normalization_mode)
- self._price_ranges[aig_equity] = (48.73, 49.10)
-
- def on_data(self, slice):
- for equity, (min_expected_price, max_expected_price) in self._price_ranges.items():
- if equity.has_data and (equity.price < min_expected_price or equity.price > max_expected_price):
- raise Exception(f"{equity.symbol}: Price {equity.price} is out of expected range [{min_expected_price}, {max_expected_price}]")
-
- def check_equity_data_normalization_mode(self, equity, expected_normalization_mode):
- subscriptions = [x for x in self.subscription_manager.subscriptions if x.symbol == equity.symbol]
- if any([x.data_normalization_mode != expected_normalization_mode for x in subscriptions]):
- raise Exception(f"Expected {equity.symbol} to have data normalization mode {expected_normalization_mode} but was {subscriptions[0].data_normalization_mode}")
-
-
diff --git a/fincept-qt/scripts/strategies/SetHoldingsLiquidateExistingHoldingsMultipleTargetsRegressionAlgorithm.py b/fincept-qt/scripts/strategies/SetHoldingsLiquidateExistingHoldingsMultipleTargetsRegressionAlgorithm.py
deleted file mode 100644
index d7fd77106..000000000
--- a/fincept-qt/scripts/strategies/SetHoldingsLiquidateExistingHoldingsMultipleTargetsRegressionAlgorithm.py
+++ /dev/null
@@ -1,25 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-36FF2819
-# Category: Regression Test
-# Description: Regression algorithm testing GH feature 3790, using SetHoldings with a collection of targets which will be ordered by...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-from SetHoldingsMultipleTargetsRegressionAlgorithm import SetHoldingsMultipleTargetsRegressionAlgorithm
-
-### <summary>
-### Regression algorithm testing GH feature 3790, using SetHoldings with a collection of targets
-### which will be ordered by margin impact before being executed, with the objective of avoiding any
-### margin errors
-### Asserts that liquidate_existing_holdings equal false does not close positions inadvertedly (GH 7008)
-### </summary>
-class SetHoldingsLiquidateExistingHoldingsMultipleTargetsRegressionAlgorithm(SetHoldingsMultipleTargetsRegressionAlgorithm):
- def on_data(self, data):
- if not self.portfolio.invested:
- self.set_holdings([PortfolioTarget(self._spy, 0.8), PortfolioTarget(self._ibm, 0.2)],
- liquidate_existing_holdings=True)
diff --git a/fincept-qt/scripts/strategies/SetHoldingsMultipleTargetsRegressionAlgorithm.py b/fincept-qt/scripts/strategies/SetHoldingsMultipleTargetsRegressionAlgorithm.py
deleted file mode 100644
index 527478a83..000000000
--- a/fincept-qt/scripts/strategies/SetHoldingsMultipleTargetsRegressionAlgorithm.py
+++ /dev/null
@@ -1,43 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-5A449593
-# Category: Regression Test
-# Description: Regression algorithm testing GH feature 3790, using SetHoldings with a collection of targets which will be ordered by...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Regression algorithm testing GH feature 3790, using SetHoldings with a collection of targets
-### which will be ordered by margin impact before being executed, with the objective of avoiding any
-### margin errors
-### </summary>
-class SetHoldingsMultipleTargetsRegressionAlgorithm(QCAlgorithm):
- def initialize(self):
- '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
-
- self.set_start_date(2013,10, 7)
- self.set_end_date(2013,10,11)
-
- # use leverage 1 so we test the margin impact ordering
- self._spy = self.add_equity("SPY", Resolution.MINUTE, Market.USA, False, 1).symbol
- self._ibm = self.add_equity("IBM", Resolution.MINUTE, Market.USA, False, 1).symbol
-
- # Order margin value has to have a minimum of 0.5% of Portfolio value, allows filtering out small trades and reduce fees.
- # Commented so regression algorithm is more sensitive
- #self.settings.minimum_order_margin_portfolio_percentage = 0.005
-
- def on_data(self, data):
- '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
-
- Arguments:
- data: Slice object keyed by symbol containing the stock data
- '''
- if not self.portfolio.invested:
- self.set_holdings([PortfolioTarget(self._spy, 0.8), PortfolioTarget(self._ibm, 0.2)])
- else:
- self.set_holdings([PortfolioTarget(self._ibm, 0.8), PortfolioTarget(self._spy, 0.2)])
diff --git a/fincept-qt/scripts/strategies/SetHoldingsRegressionAlgorithm.py b/fincept-qt/scripts/strategies/SetHoldingsRegressionAlgorithm.py
deleted file mode 100644
index 1103cc578..000000000
--- a/fincept-qt/scripts/strategies/SetHoldingsRegressionAlgorithm.py
+++ /dev/null
@@ -1,37 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-58C330FF
-# Category: Regression Test
-# Description: Regression algorithm testing the SetHolding trading API precision
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Regression algorithm testing the SetHolding trading API precision
-### </summary>
-class SetHoldingsRegressionAlgorithm(QCAlgorithm):
- '''Basic template algorithm simply initializes the date range and cash'''
-
- def initialize(self):
- '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
-
- self.set_start_date(2013, 10, 7)
- self.set_end_date(2013, 10, 8)
- self.add_equity("SPY", Resolution.MINUTE)
-
- def on_data(self, data):
- '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
-
- Arguments:
- data: Slice object keyed by symbol containing the stock data
- '''
- if not self.portfolio.invested:
- self.set_holdings("SPY", 0.1)
- self.set_holdings("SPY", float(0.20))
- self.set_holdings("SPY", np.float64(0.30))
- self.set_holdings("SPY", 1)
diff --git a/fincept-qt/scripts/strategies/ShortableProviderOrdersRejectedRegressionAlgorithm.py b/fincept-qt/scripts/strategies/ShortableProviderOrdersRejectedRegressionAlgorithm.py
deleted file mode 100644
index 44db04736..000000000
--- a/fincept-qt/scripts/strategies/ShortableProviderOrdersRejectedRegressionAlgorithm.py
+++ /dev/null
@@ -1,102 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-EFDED6A6
-# Category: Regression Test
-# Description: Tests that orders are denied if they exceed the max shortable quantity
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-class RegressionTestShortableProvider(LocalDiskShortableProvider):
- def __init__(self):
- super().__init__("testbrokerage")
-
-### <summary>
-### Tests that orders are denied if they exceed the max shortable quantity.
-### </summary>
-class ShortableProviderOrdersRejectedRegressionAlgorithm(QCAlgorithm):
- def initialize(self):
- self.orders_allowed = []
- self.orders_denied = []
- self.initialized = False
- self.invalidated_allowed_order = False
- self.invalidated_new_order_with_portfolio_holdings = False
-
- self.set_start_date(2013, 10, 4)
- self.set_end_date(2013, 10, 11)
- self.set_cash(10000000)
-
- self.spy = self.add_equity("SPY", Resolution.MINUTE)
- self.aig = self.add_equity("AIG", Resolution.MINUTE)
-
- self.spy.set_shortable_provider(RegressionTestShortableProvider())
- self.aig.set_shortable_provider(RegressionTestShortableProvider())
-
- def on_data(self, data):
- if not self.initialized:
- self.handle_order(self.limit_order(self.spy.symbol, -1001, 10000)) # Should be canceled, exceeds the max shortable quantity
- order_ticket = self.limit_order(self.spy.symbol, -1000, 10000)
- self.handle_order(order_ticket) # Allowed, orders at or below 1000 should be accepted
- self.handle_order(self.limit_order(self.spy.symbol, -10, 0.01)) # Should be canceled, the total quantity we would be short would exceed the max shortable quantity.
-
- response = order_ticket.update_quantity(-999) # should be allowed, we are reducing the quantity we want to short
- if not response.is_success:
- raise ValueError("Order update should of succeeded!");
-
- self.initialized = True
- return
-
- if not self.invalidated_allowed_order:
- if len(self.orders_allowed) != 1:
- raise Exception(f"Expected 1 successful order, found: {len(self.orders_allowed)}")
- if len(self.orders_denied) != 2:
- raise Exception(f"Expected 2 failed orders, found: {len(self.orders_denied)}")
-
- allowed_order = self.orders_allowed[0]
- order_update = UpdateOrderFields()
- order_update.limit_price = 0.01
- order_update.quantity = -1001
- order_update.tag = "Testing updating and exceeding maximum quantity"
-
- response = allowed_order.update(order_update)
- if response.error_code != OrderResponseErrorCode.EXCEEDS_SHORTABLE_QUANTITY:
- raise Exception(f"Expected order to fail due to exceeded shortable quantity, found: {response.error_code}")
-
- cancel_response = allowed_order.cancel()
- if cancel_response.is_error:
- raise Exception("Expected to be able to cancel open order after bad qty update")
-
- self.invalidated_allowed_order = True
- self.orders_denied.clear()
- self.orders_allowed.clear()
- return
-
- if not self.invalidated_new_order_with_portfolio_holdings:
- self.handle_order(self.market_order(self.spy.symbol, -1000)) # Should succeed, no holdings and no open orders to stop this
- spy_shares = self.portfolio[self.spy.symbol].quantity
- if spy_shares != -1000:
- raise Exception(f"Expected -1000 shares in portfolio, found: {spy_shares}")
-
- self.handle_order(self.limit_order(self.spy.symbol, -1, 0.01)) # Should fail, portfolio holdings are at the max shortable quantity.
- if len(self.orders_denied) != 1:
- raise Exception(f"Expected limit order to fail due to existing holdings, but found {len(self.orders_denied)} failures")
-
- self.orders_allowed.clear()
- self.orders_denied.clear()
-
- self.handle_order(self.market_order(self.aig.symbol, -1001))
- if len(self.orders_allowed) != 1:
- raise Exception(f"Expected market order of -1001 BAC to not fail")
-
- self.invalidated_new_order_with_portfolio_holdings = True
-
- def handle_order(self, order_ticket):
- if order_ticket.submit_request.status == OrderRequestStatus.ERROR:
- self.orders_denied.append(order_ticket)
- return
-
- self.orders_allowed.append(order_ticket)
diff --git a/fincept-qt/scripts/strategies/SliceGetByTypeRegressionAlgorithm.py b/fincept-qt/scripts/strategies/SliceGetByTypeRegressionAlgorithm.py
deleted file mode 100644
index 03cd898fe..000000000
--- a/fincept-qt/scripts/strategies/SliceGetByTypeRegressionAlgorithm.py
+++ /dev/null
@@ -1,54 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-198E83AF
-# Category: Regression Test
-# Description: Volume-weighted trend strategy. Tracks volume relative to its
-# 20-day average. Buys when price is rising and volume is above average
-# (confirming trend). Sells on volume contraction below average.
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-class SliceGetByTypeRegressionAlgorithm(QCAlgorithm):
- """Volume-confirmed trend following strategy."""
-
- def initialize(self):
- self.set_start_date(2023, 1, 1)
- self.set_end_date(2024, 1, 1)
- self.set_cash(100000)
-
- self.symbol = "SPY"
- self.add_equity(self.symbol, Resolution.DAILY)
-
- self._ema = self.ema(self.symbol, 20, Resolution.DAILY)
- self._volumes = []
-
- def on_data(self, data):
- if not self._ema.is_ready:
- return
- if self.symbol not in data:
- return
-
- price = data[self.symbol].close
- volume = data[self.symbol].volume
-
- self._volumes.append(volume)
- if len(self._volumes) > 20:
- self._volumes = self._volumes[-20:]
-
- if len(self._volumes) < 20:
- return
-
- avg_vol = sum(self._volumes) / len(self._volumes)
- ema_val = self._ema.current.value
-
- if not self.portfolio.invested:
- if price > ema_val and volume > avg_vol * 1.1:
- self.set_holdings(self.symbol, 1)
- else:
- if price < ema_val:
- self.liquidate()
diff --git a/fincept-qt/scripts/strategies/SmaCrossUniverseSelectionAlgorithm.py b/fincept-qt/scripts/strategies/SmaCrossUniverseSelectionAlgorithm.py
deleted file mode 100644
index 14cc2f900..000000000
--- a/fincept-qt/scripts/strategies/SmaCrossUniverseSelectionAlgorithm.py
+++ /dev/null
@@ -1,83 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-9D3D6D8F
-# Category: Universe Selection
-# Description: Provides an example where WarmUpIndicator method is used to warm up indicators
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-class SmaCrossUniverseSelectionAlgorithm(QCAlgorithm):
- '''Provides an example where WarmUpIndicator method is used to warm up indicators
- after their security is added and before (Universe Selection scenario)'''
-
- count = 10
- tolerance = 0.01
- target_percent = 1 / count
- averages = dict()
-
- def initialize(self):
-
- self.universe_settings.leverage = 2
- self.universe_settings.resolution = Resolution.DAILY
-
- self.set_start_date(2018, 1, 1)
- self.set_end_date(2019, 1, 1)
- self.set_cash(1000000)
-
- self.settings.automatic_indicator_warm_up = True
-
- ibm = self.add_equity("IBM", Resolution.HOUR).symbol
- ibm_sma = self.sma(ibm, 40)
- self.log(f"{ibm_sma.name}: {ibm_sma.current.time} - {ibm_sma}. IsReady? {ibm_sma.is_ready}")
-
- spy = self.add_equity("SPY", Resolution.HOUR).symbol
- spy_sma = self.sma(spy, 10) # Data point indicator
- spy_atr = self.atr(spy, 10,) # Bar indicator
- spy_vwap = self.vwap(spy, 10) # TradeBar indicator
- self.log(f"SPY - Is ready? SMA: {spy_sma.is_ready}, ATR: {spy_atr.is_ready}, VWAP: {spy_vwap.is_ready}")
-
- eur = self.add_forex("EURUSD", Resolution.HOUR).symbol
- eur_sma = self.sma(eur, 20, Resolution.DAILY)
- eur_atr = self.atr(eur, 20, MovingAverageType.SIMPLE, Resolution.DAILY)
- self.log(f"EURUSD - Is ready? SMA: {eur_sma.is_ready}, ATR: {eur_atr.is_ready}")
-
- self.add_universe(self.coarse_sma_selector)
-
- # Since the indicators are ready, we will receive error messages
- # reporting that the algorithm manager is trying to add old information
- self.set_warm_up(10)
-
- def coarse_sma_selector(self, coarse):
-
- score = dict()
- for cf in coarse:
- if not cf.has_fundamental_data:
- continue
- symbol = cf.symbol
- price = cf.adjusted_price
- # grab the SMA instance for this symbol
- avg = self.averages.setdefault(symbol, SimpleMovingAverage(100))
- self.warm_up_indicator(symbol, avg, Resolution.DAILY)
- # Update returns true when the indicators are ready, so don't accept until they are
- if avg.update(cf.end_time, price):
- value = avg.current.value
- # only pick symbols who have their price over their 100 day sma
- if value > price * self.tolerance:
- score[symbol] = (value - price) / ((value + price) / 2)
-
- # prefer symbols with a larger delta by percentage between the two averages
- sorted_score = sorted(score.items(), key=lambda kvp: kvp[1], reverse=True)
- return [x[0] for x in sorted_score[:self.count]]
-
- def on_securities_changed(self, changes):
- for security in changes.removed_securities:
- if security.invested:
- self.liquidate(security.symbol)
-
- for security in changes.added_securities:
- self.set_holdings(security.symbol, self.target_percent)
diff --git a/fincept-qt/scripts/strategies/SpreadExecutionModelRegressionAlgorithm.py b/fincept-qt/scripts/strategies/SpreadExecutionModelRegressionAlgorithm.py
deleted file mode 100644
index ff2e8b9bc..000000000
--- a/fincept-qt/scripts/strategies/SpreadExecutionModelRegressionAlgorithm.py
+++ /dev/null
@@ -1,52 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-E4FEA7D1
-# Category: Execution Model
-# Description: Regression algorithm for the SpreadExecutionModel. This algorithm shows how the execution model works to submit order...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-from Alphas.RsiAlphaModel import RsiAlphaModel
-from Portfolio.EqualWeightingPortfolioConstructionModel import EqualWeightingPortfolioConstructionModel
-from Execution.SpreadExecutionModel import SpreadExecutionModel
-
-### <summary>
-### Regression algorithm for the SpreadExecutionModel.
-### This algorithm shows how the execution model works to
-### submit orders only when the price is on desirably tight spread.
-### </summary>
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="using quantconnect" />
-### <meta name="tag" content="trading and orders" />
-class SpreadExecutionModelRegressionAlgorithm(QCAlgorithm):
- '''Regression algorithm for the SpreadExecutionModel.
- This algorithm shows how the execution model works to
- submit orders only when the price is on desirably tight spread.'''
-
- def initialize(self):
- self.set_start_date(2013,10,7)
- self.set_end_date(2013,10,11)
-
- self.set_universe_selection(ManualUniverseSelectionModel([
- Symbol.create('AIG', SecurityType.EQUITY, Market.USA),
- Symbol.create('BAC', SecurityType.EQUITY, Market.USA),
- Symbol.create('IBM', SecurityType.EQUITY, Market.USA),
- Symbol.create('SPY', SecurityType.EQUITY, Market.USA)
- ]))
-
- # using hourly rsi to generate more insights
- self.set_alpha(RsiAlphaModel(14, Resolution.HOUR))
- self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())
- self.set_execution(SpreadExecutionModel())
-
- self.insights_generated += self.on_insights_generated
-
- def on_insights_generated(self, algorithm, data):
- self.log(f"{self.time}: {', '.join(str(x) for x in data.insights)}")
-
- def on_order_event(self, order_event):
- self.log(f"{self.time}: {order_event}")
diff --git a/fincept-qt/scripts/strategies/StableCoinsRegressionAlgorithm.py b/fincept-qt/scripts/strategies/StableCoinsRegressionAlgorithm.py
deleted file mode 100644
index d12e4f001..000000000
--- a/fincept-qt/scripts/strategies/StableCoinsRegressionAlgorithm.py
+++ /dev/null
@@ -1,28 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-5C2FCFA1
-# Category: Regression Test
-# Description: A demonstration algorithm to check there can be placed an order of a pair not present in the brokerage using the conv...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### A demonstration algorithm to check there can be placed an order of a pair not present
-### in the brokerage using the conversion between stablecoins
-### </summary>
-class StableCoinsRegressionAlgorithm(QCAlgorithm):
- def initialize(self):
- self.set_start_date(2018, 5, 1)
- self.set_end_date(2018, 5, 2)
- self.set_cash("USDT", 200000000)
- self.set_brokerage_model(BrokerageName.BINANCE, AccountType.CASH)
- self.add_crypto("BTCUSDT", Resolution.HOUR, Market.BINANCE)
-
- def on_data(self, data):
- if not self.portfolio.invested:
- self.set_holdings("BTCUSDT", 1)
diff --git a/fincept-qt/scripts/strategies/StandardDeviationExecutionModelRegressionAlgorithm.py b/fincept-qt/scripts/strategies/StandardDeviationExecutionModelRegressionAlgorithm.py
deleted file mode 100644
index 08720dc8a..000000000
--- a/fincept-qt/scripts/strategies/StandardDeviationExecutionModelRegressionAlgorithm.py
+++ /dev/null
@@ -1,52 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-C7F868BA
-# Category: Execution Model
-# Description: Regression algorithm for the StandardDeviationExecutionModel. This algorithm shows how the execution model works to s...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-from Alphas.RsiAlphaModel import RsiAlphaModel
-from Portfolio.EqualWeightingPortfolioConstructionModel import EqualWeightingPortfolioConstructionModel
-from Execution.StandardDeviationExecutionModel import StandardDeviationExecutionModel
-
-### <summary>
-### Regression algorithm for the StandardDeviationExecutionModel.
-### This algorithm shows how the execution model works to split up orders and submit them
-### only when the price is 2 standard deviations from the 60min mean (default model settings).
-### </summary>
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="using quantconnect" />
-### <meta name="tag" content="trading and orders" />
-class StandardDeviationExecutionModelRegressionAlgorithm(QCAlgorithm):
- '''Regression algorithm for the StandardDeviationExecutionModel.
- This algorithm shows how the execution model works to split up orders and submit them
- only when the price is 2 standard deviations from the 60min mean (default model settings).'''
-
- def initialize(self):
- ''' Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
-
- # Set requested data resolution
- self.universe_settings.resolution = Resolution.MINUTE
-
- self.set_start_date(2013,10,7)
- self.set_end_date(2013,10,11)
- self.set_cash(1000000)
-
- self.set_universe_selection(ManualUniverseSelectionModel([
- Symbol.create('AIG', SecurityType.EQUITY, Market.USA),
- Symbol.create('BAC', SecurityType.EQUITY, Market.USA),
- Symbol.create('IBM', SecurityType.EQUITY, Market.USA),
- Symbol.create('SPY', SecurityType.EQUITY, Market.USA)
- ]))
-
- self.set_alpha(RsiAlphaModel(14, Resolution.HOUR))
- self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())
- self.set_execution(StandardDeviationExecutionModel())
-
- def on_order_event(self, order_event):
- self.log(f"{self.time}: {order_event}")
diff --git a/fincept-qt/scripts/strategies/StatisticsResultsAlgorithm.py b/fincept-qt/scripts/strategies/StatisticsResultsAlgorithm.py
deleted file mode 100644
index 58b51dcce..000000000
--- a/fincept-qt/scripts/strategies/StatisticsResultsAlgorithm.py
+++ /dev/null
@@ -1,116 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-99B5F510
-# Category: General Strategy
-# Description: Demonstration of how to access the statistics results from within an algorithm through the `Statistics` property
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Demonstration of how to access the statistics results from within an algorithm through the `Statistics` property.
-### </summary>
-class StatisticsResultsAlgorithm(QCAlgorithm):
-
- most_traded_security_statistic = "Most Traded Security"
- most_traded_security_trade_count_statistic = "Most Traded Security Trade Count"
-
- def initialize(self):
- self.set_start_date(2013, 10, 7)
- self.set_end_date(2013, 10, 11)
- self.set_cash(100000)
-
- self.spy = self.add_equity("SPY", Resolution.MINUTE).symbol
- self.ibm = self.add_equity("IBM", Resolution.MINUTE).symbol
-
- self.fast_spy_ema = self.ema(self.spy, 30, Resolution.MINUTE)
- self.slow_spy_ema = self.ema(self.spy, 60, Resolution.MINUTE)
-
- self.fast_ibm_ema = self.ema(self.spy, 10, Resolution.MINUTE)
- self.slow_ibm_ema = self.ema(self.spy, 30, Resolution.MINUTE)
-
- self.trade_counts = {self.spy: 0, self.ibm: 0}
-
- def on_data(self, data: Slice):
- if not self.slow_spy_ema.is_ready: return
-
- if self.fast_spy_ema > self.slow_spy_ema:
- self.set_holdings(self.spy, 0.5)
- elif self.securities[self.spy].invested:
- self.liquidate(self.spy)
-
- if self.fast_ibm_ema > self.slow_ibm_ema:
- self.set_holdings(self.ibm, 0.2)
- elif self.securities[self.ibm].invested:
- self.liquidate(self.ibm)
-
- def on_order_event(self, order_event):
- if order_event.status == OrderStatus.FILLED:
- # We can access the statistics summary at runtime
- statistics = self.statistics.summary
- statistics_str = "".join([f"{kvp.key}: {kvp.value}" for kvp in statistics])
- self.debug(f"Statistics after fill:{statistics_str}")
-
- # Access a single statistic
- self.log(f"Total trades so far: {statistics[PerformanceMetrics.TOTAL_ORDERS]}")
- self.log(f"Sharpe Ratio: {statistics[PerformanceMetrics.SHARPE_RATIO]}")
-
- # --------
-
- # We can also set custom summary statistics:
-
- if all(count == 0 for count in self.trade_counts.values()):
- if StatisticsResultsAlgorithm.most_traded_security_statistic in statistics:
- raise Exception(f"Statistic {StatisticsResultsAlgorithm.most_traded_security_statistic} should not be set yet")
- if StatisticsResultsAlgorithm.most_traded_security_trade_count_statistic in statistics:
- raise Exception(f"Statistic {StatisticsResultsAlgorithm.most_traded_security_trade_count_statistic} should not be set yet")
- else:
- # The current most traded security should be set in the summary
- most_trade_security, most_trade_security_trade_count = self.get_most_trade_security()
- self.check_most_traded_security_statistic(statistics, most_trade_security, most_trade_security_trade_count)
-
- # Update the trade count
- self.trade_counts[order_event.symbol] += 1
-
- # Set the most traded security
- most_trade_security, most_trade_security_trade_count = self.get_most_trade_security()
- self.set_summary_statistic(StatisticsResultsAlgorithm.most_traded_security_statistic, most_trade_security)
- self.set_summary_statistic(StatisticsResultsAlgorithm.most_traded_security_trade_count_statistic, most_trade_security_trade_count)
-
- # Re-calculate statistics:
- statistics = self.statistics.summary
-
- # Let's keep track of our custom summary statistics after the update
- self.check_most_traded_security_statistic(statistics, most_trade_security, most_trade_security_trade_count)
-
- def on_end_of_algorithm(self):
- statistics = self.statistics.summary
- if StatisticsResultsAlgorithm.most_traded_security_statistic not in statistics:
- raise Exception(f"Statistic {StatisticsResultsAlgorithm.most_traded_security_statistic} should be in the summary statistics")
- if StatisticsResultsAlgorithm.most_traded_security_trade_count_statistic not in statistics:
- raise Exception(f"Statistic {StatisticsResultsAlgorithm.most_traded_security_trade_count_statistic} should be in the summary statistics")
-
- most_trade_security, most_trade_security_trade_count = self.get_most_trade_security()
- self.check_most_traded_security_statistic(statistics, most_trade_security, most_trade_security_trade_count)
-
- def check_most_traded_security_statistic(self, statistics: Dict[str, str], most_traded_security: Symbol, trade_count: int):
- most_traded_security_statistic = statistics[StatisticsResultsAlgorithm.most_traded_security_statistic]
- most_traded_security_trade_count_statistic = statistics[StatisticsResultsAlgorithm.most_traded_security_trade_count_statistic]
- self.log(f"Most traded security: {most_traded_security_statistic}")
- self.log(f"Most traded security trade count: {most_traded_security_trade_count_statistic}")
-
- if most_traded_security_statistic != most_traded_security:
- raise Exception(f"Most traded security should be {most_traded_security} but it is {most_traded_security_statistic}")
-
- if most_traded_security_trade_count_statistic != str(trade_count):
- raise Exception(f"Most traded security trade count should be {trade_count} but it is {most_traded_security_trade_count_statistic}")
-
- def get_most_trade_security(self) -> Tuple[Symbol, int]:
- most_trade_security = max(self.trade_counts, key=lambda symbol: self.trade_counts[symbol])
- most_trade_security_trade_count = self.trade_counts[most_trade_security]
- return most_trade_security, most_trade_security_trade_count
-
diff --git a/fincept-qt/scripts/strategies/StochasticIndicatorWarmsUpProperlyRegressionAlgorithm.py b/fincept-qt/scripts/strategies/StochasticIndicatorWarmsUpProperlyRegressionAlgorithm.py
deleted file mode 100644
index 91f01d2ad..000000000
--- a/fincept-qt/scripts/strategies/StochasticIndicatorWarmsUpProperlyRegressionAlgorithm.py
+++ /dev/null
@@ -1,65 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-1A300907
-# Category: Indicators
-# Description: Stochastic oscillator strategy with SMA trend filter. Buys when
-# stochastic %K crosses above 20 (oversold) while price is above 50-day SMA.
-# Sells when %K crosses below 80 (overbought) or price drops below SMA.
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-class StochasticIndicatorWarmsUpProperlyRegressionAlgorithm(QCAlgorithm):
- """Stochastic oversold/overbought strategy with SMA filter."""
-
- def initialize(self):
- self.set_start_date(2023, 1, 1)
- self.set_end_date(2024, 1, 1)
- self.set_cash(100000)
-
- self.symbol = "SPY"
- self.add_equity(self.symbol, Resolution.DAILY)
-
- self._sma = self.sma(self.symbol, 50, Resolution.DAILY)
- # Manual stochastic: track 14-day high/low
- self._highs = []
- self._lows = []
- self._prev_k = 50
-
- def on_data(self, data):
- if not self._sma.is_ready:
- return
- if self.symbol not in data:
- return
-
- bar = data[self.symbol]
- price = bar.close
- self._highs.append(bar.high)
- self._lows.append(bar.low)
- if len(self._highs) > 14:
- self._highs = self._highs[-14:]
- self._lows = self._lows[-14:]
-
- if len(self._highs) < 14:
- return
-
- highest = max(self._highs)
- lowest = min(self._lows)
- k_range = highest - lowest
- k = ((price - lowest) / k_range * 100) if k_range > 0 else 50
-
- sma_val = self._sma.current.value
- crossed_up_20 = self._prev_k <= 20 and k > 20
- crossed_down_80 = self._prev_k >= 80 and k < 80
- self._prev_k = k
-
- if not self.portfolio.invested:
- if crossed_up_20 and price > sma_val:
- self.set_holdings(self.symbol, 1)
- else:
- if crossed_down_80 or price < sma_val:
- self.liquidate()
diff --git a/fincept-qt/scripts/strategies/StopLimitOrderRegressionAlgorithm.py b/fincept-qt/scripts/strategies/StopLimitOrderRegressionAlgorithm.py
deleted file mode 100644
index 4392fabc3..000000000
--- a/fincept-qt/scripts/strategies/StopLimitOrderRegressionAlgorithm.py
+++ /dev/null
@@ -1,75 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-58C9B30E
-# Category: Regression Test
-# Description: Basic algorithm demonstrating how to place stop limit orders
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Basic algorithm demonstrating how to place stop limit orders.
-### </summary>
-### <meta name="tag" content="trading and orders" />
-### <meta name="tag" content="placing orders" />
-### <meta name="tag" content="stop limit order"/>
-class StopLimitOrderRegressionAlgorithm(QCAlgorithm):
- '''Basic algorithm demonstrating how to place stop limit orders.'''
-
- tolerance = 0.001
- fast_period = 30
- slow_period = 60
-
- def initialize(self):
- self.set_start_date(2013, 1, 1)
- self.set_end_date(2017, 1, 1)
- self.set_cash(100000)
-
- self._symbol = self.add_equity("SPY", Resolution.DAILY).symbol
-
- self._fast = self.ema(self._symbol, self.fast_period, Resolution.DAILY)
- self._slow = self.ema(self._symbol, self.slow_period, Resolution.DAILY)
-
- self._buy_order_ticket: OrderTicket = None
- self._sell_order_ticket: OrderTicket = None
- self._previous_slice: Slice = None
-
- def on_data(self, slice: Slice):
- if not self.is_ready():
- return
-
- security = self.securities[self._symbol]
- if self._buy_order_ticket is None and self.trend_is_up():
- self._buy_order_ticket = self.stop_limit_order(self._symbol, 100, stop_price=security.high * 1.10, limit_price=security.high * 1.11)
- elif self._buy_order_ticket.status == OrderStatus.FILLED and self._sell_order_ticket is None and self.trend_is_down():
- self._sell_order_ticket = self.stop_limit_order(self._symbol, -100, stop_price=security.low * 0.99, limit_price=security.low * 0.98)
-
- def on_order_event(self, order_event: OrderEvent):
- if order_event.status == OrderStatus.FILLED:
- order: StopLimitOrder = self.transactions.get_order_by_id(order_event.order_id)
- if not order.stop_triggered:
- raise Exception("StopLimitOrder StopTriggered should haven been set if the order filled.")
-
- if order_event.direction == OrderDirection.BUY:
- limit_price = self._buy_order_ticket.get(OrderField.LIMIT_PRICE)
- if order_event.fill_price > limit_price:
- raise Exception(f"Buy stop limit order should have filled with price less than or equal to the limit price {limit_price}. "
- f"Fill price: {order_event.fill_price}")
- else:
- limit_price = self._sell_order_ticket.get(OrderField.LIMIT_PRICE)
- if order_event.fill_price < limit_price:
- raise Exception(f"Sell stop limit order should have filled with price greater than or equal to the limit price {limit_price}. "
- f"Fill price: {order_event.fill_price}")
-
- def is_ready(self):
- return self._fast.is_ready and self._slow.is_ready
-
- def trend_is_up(self):
- return self.is_ready() and self._fast.current.value > self._slow.current.value * (1 + self.tolerance)
-
- def trend_is_down(self):
- return self.is_ready() and self._fast.current.value < self._slow.current.value * (1 + self.tolerance)
diff --git a/fincept-qt/scripts/strategies/StringToSymbolImplicitConversionRegressionAlgorithm.py b/fincept-qt/scripts/strategies/StringToSymbolImplicitConversionRegressionAlgorithm.py
deleted file mode 100644
index 84db1f834..000000000
--- a/fincept-qt/scripts/strategies/StringToSymbolImplicitConversionRegressionAlgorithm.py
+++ /dev/null
@@ -1,36 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-8FAFCC5D
-# Category: Regression Test
-# Description: Related to GH issue 4275, reproduces a failed string to symbol implicit conversion asserting the exception thrown con...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Related to GH issue 4275, reproduces a failed string to symbol implicit conversion asserting the exception
-### thrown contains the used ticker
-### </summary>
-class StringToSymbolImplicitConversionRegressionAlgorithm(QCAlgorithm):
- def initialize(self):
- '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
- self.set_start_date(2013,10, 7)
- self.set_end_date(2013,10, 8)
-
- self.add_equity("SPY", Resolution.MINUTE)
-
- def on_data(self, data):
- '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
-
- Arguments:
- data: Slice object keyed by symbol containing the stock data
- '''
- try:
- self.market_order("PEPE", 1)
- except Exception as exception:
- if "This asset symbol (PEPE 0) was not found in your security list" in str(exception) and not self.portfolio.invested:
- self.set_holdings("SPY", 1)
diff --git a/fincept-qt/scripts/strategies/TalibIndicatorsAlgorithm.py b/fincept-qt/scripts/strategies/TalibIndicatorsAlgorithm.py
deleted file mode 100644
index af65fdebc..000000000
--- a/fincept-qt/scripts/strategies/TalibIndicatorsAlgorithm.py
+++ /dev/null
@@ -1,65 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-D0F1B141
-# Category: Indicators
-# Description: Talib Indicators Algorithm
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-import talib
-
-class CalibratedResistanceAtmosphericScrubbers(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2020, 1, 2)
- self.set_end_date(2020, 1, 6)
- self.set_cash(100000)
- self.add_equity("SPY", Resolution.HOUR)
-
- self.rolling_window = pd.DataFrame()
- self.dema_period = 3
- self.sma_period = 3
- self.wma_period = 3
- self.window_size = self.dema_period * 2
- self.set_warm_up(self.window_size)
-
- def on_data(self, data):
- if "SPY" not in data.bars:
- return
-
- close = data["SPY"].close
-
- if self.is_warming_up:
- # Add latest close to rolling window
- row = pd.DataFrame({"close": [close]}, index=[data.time])
- self.rolling_window = pd.concat([self.rolling_window, row]).iloc[-self.window_size:]
-
- # If we have enough closing data to start calculating indicators...
- if self.rolling_window.shape[0] == self.window_size:
- closes = self.rolling_window['close'].values
-
- # Add indicator columns to DataFrame
- self.rolling_window['DEMA'] = talib.DEMA(closes, self.dema_period)
- self.rolling_window['EMA'] = talib.EMA(closes, self.sma_period)
- self.rolling_window['WMA'] = talib.WMA(closes, self.wma_period)
- return
-
- closes = np.append(self.rolling_window['close'].values, close)[-self.window_size:]
-
- # Update talib indicators time series with the latest close
- row = pd.DataFrame({"close": close,
- "DEMA" : talib.DEMA(closes, self.dema_period)[-1],
- "EMA" : talib.EMA(closes, self.sma_period)[-1],
- "WMA" : talib.WMA(closes, self.wma_period)[-1]},
- index=[data.time])
-
- self.rolling_window = pd.concat([self.rolling_window, row]).iloc[-self.window_size:]
-
-
- def on_end_of_algorithm(self):
- self.log(f"\nRolling Window:\n{self.rolling_window.to_string()}\n")
- self.log(f"\nLatest Values:\n{self.rolling_window.iloc[-1].to_string()}\n")
diff --git a/fincept-qt/scripts/strategies/TensorFlowNeuralNetworkAlgorithm.py b/fincept-qt/scripts/strategies/TensorFlowNeuralNetworkAlgorithm.py
deleted file mode 100644
index a26d55d72..000000000
--- a/fincept-qt/scripts/strategies/TensorFlowNeuralNetworkAlgorithm.py
+++ /dev/null
@@ -1,108 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-42FC8E69
-# Category: Machine Learning
-# Description: Enter or exit positions based on relationship of the open price of the current bar and the prices defined by the mach...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-import tensorflow.compat.v1 as tf
-
-class TensorFlowNeuralNetworkAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2013, 10, 7) # Set Start Date
- self.set_end_date(2013, 10, 8) # Set End Date
-
- self.set_cash(100000) # Set Strategy Cash
- spy = self.add_equity("SPY", Resolution.MINUTE) # Add Equity
-
- self.symbols = [spy.symbol] # potential trading symbols pool (in this algorithm there is only 1).
- self.lookback = 30 # number of previous days for training
-
- self.schedule.on(self.date_rules.every(DayOfWeek.MONDAY), self.time_rules.after_market_open("SPY", 28), self.net_train) # train the neural network 28 mins after market open
- self.schedule.on(self.date_rules.every(DayOfWeek.MONDAY), self.time_rules.after_market_open("SPY", 30), self.trade) # trade 30 mins after market open
-
- def add_layer(self, inputs, in_size, out_size, activation_function=None):
- # add one more layer and return the output of this layer
- # this is one NN with only one hidden layer
- weights = tf.Variable(tf.random_normal([in_size, out_size]))
- biases = tf.Variable(tf.zeros([1, out_size]) + 0.1)
- wx_plus_b = tf.matmul(inputs, weights) + biases
- if activation_function is None:
- outputs = wx_plus_b
- else:
- outputs = activation_function(wx_plus_b)
- return outputs
-
- def net_train(self):
- # Daily historical data is used to train the machine learning model
- history = self.history(self.symbols, self.lookback + 1, Resolution.DAILY)
-
- # model: use prices_x to fit prices_y; key: symbol; value: according price
- self.prices_x, self.prices_y = {}, {}
-
- # key: symbol; values: prices for sell or buy
- self.sell_prices, self.buy_prices = {}, {}
-
- for symbol in self.symbols:
- if not history.empty:
- # Daily historical data is used to train the machine learning model
- # use open prices to predict the next days'
- self.prices_x[symbol] = list(history.loc[symbol.value]['open'][:-1])
- self.prices_y[symbol] = list(history.loc[symbol.value]['open'][1:])
-
- for symbol in self.symbols:
- if symbol in self.prices_x:
- # create numpy array
- x_data = np.array(self.prices_x[symbol]).astype(np.float32).reshape((-1,1))
- y_data = np.array(self.prices_y[symbol]).astype(np.float32).reshape((-1,1))
-
- # define placeholder for inputs to network
- tf.disable_v2_behavior()
- xs = tf.placeholder(tf.float32, [None, 1])
- ys = tf.placeholder(tf.float32, [None, 1])
-
- # add hidden layer
- l1 = self.add_layer(xs, 1, 10, activation_function=tf.nn.relu)
- # add output layer
- prediction = self.add_layer(l1, 10, 1, activation_function=None)
-
- # the error between prediciton and real data
- loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction),
- reduction_indices=[1]))
- # use gradient descent and square error
- train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)
-
- # the following is precedure for tensorflow
- sess = tf.Session()
-
- init = tf.global_variables_initializer()
- sess.run(init)
-
- for i in range(200):
- # training
- sess.run(train_step, feed_dict={xs: x_data, ys: y_data})
-
- # predict today's price
- y_pred_final = sess.run(prediction, feed_dict = {xs: y_data})[0][-1]
-
- # get sell prices and buy prices as trading signals
- self.sell_prices[symbol] = y_pred_final - np.std(y_data)
- self.buy_prices[symbol] = y_pred_final + np.std(y_data)
-
- def trade(self):
- '''
- Enter or exit positions based on relationship of the open price of the current bar and the prices defined by the machine learning model.
- Liquidate if the open price is below the sell price and buy if the open price is above the buy price
- '''
- for holding in self.portfolio.Values:
- if self.current_slice[holding.symbol].open < self.sell_prices[holding.symbol] and holding.invested:
- self.liquidate(holding.symbol)
-
- if self.current_slice[holding.symbol].open > self.buy_prices[holding.symbol] and not holding.invested:
- self.set_holdings(holding.symbol, 1 / len(self.symbols))
diff --git a/fincept-qt/scripts/strategies/TickDataFilteringAlgorithm.py b/fincept-qt/scripts/strategies/TickDataFilteringAlgorithm.py
deleted file mode 100644
index 119579101..000000000
--- a/fincept-qt/scripts/strategies/TickDataFilteringAlgorithm.py
+++ /dev/null
@@ -1,75 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-84B15249
-# Category: General Strategy
-# Description: Tick Data Filtering Algorithm
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-# <summary>
-# Demonstration of filtering tick data so easier to use. Tick data has lots of glitchy, spikey data which should be filtered out before usagee.
-# </summary>
-# <meta name="tag" content="filtering" />
-# <meta name="tag" content="tick data" />
-# <meta name="tag" content="using data" />
-# <meta name="tag" content="ticks event" />
-class TickDataFilteringAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2013, 10, 7)
- self.set_end_date(2013, 10, 7)
- self.set_cash(25000)
- spy = self.add_equity("SPY", Resolution.TICK)
-
- #Add our custom data filter.
- spy.set_data_filter(TickExchangeDataFilter(self))
-
- # <summary>
- # Data arriving here will now be filtered.
- # </summary>
- # <param name="data">Ticks data array</param>
- def on_data(self, data):
- if not data.contains_key("SPY"):
- return
-
- spy_tick_list = data["SPY"]
-
- # Ticks return a list of ticks this second
- for tick in spy_tick_list:
- self.debug(tick.exchange)
-
- if not self.portfolio.invested:
- self.set_holdings("SPY", 1)
-
-# <summary>
-# Exchange filter class
-# </summary>
-class TickExchangeDataFilter(SecurityDataFilter):
-
- # <summary>
- # Save instance of the algorithm namespace
- # </summary>
- # <param name="algo"></param>
- def __init__(self, algo: IAlgorithm):
- self.algo = algo
- super().__init__()
-
- # <summary>
- # Filter out a tick from this vehicle, with this new data:
- # </summary>
- # <param name="data">New data packet:</param>
- # <param name="asset">Vehicle of this filter.</param>
- def filter(self, asset: Security, data: BaseData):
- # TRUE --> Accept Tick
- # FALSE --> Reject Tick
-
- if isinstance(data, Tick):
- if data.exchange == str(Exchange.ARCA):
- return True
-
- return False
diff --git a/fincept-qt/scripts/strategies/TickHistoryRequestWithoutTickSubscriptionRegressionAlgorithm.py b/fincept-qt/scripts/strategies/TickHistoryRequestWithoutTickSubscriptionRegressionAlgorithm.py
deleted file mode 100644
index a7f4bc303..000000000
--- a/fincept-qt/scripts/strategies/TickHistoryRequestWithoutTickSubscriptionRegressionAlgorithm.py
+++ /dev/null
@@ -1,43 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-824A47D1
-# Category: Regression Test
-# Description: Regression algorithm asserting that historical data can be requested with tick resolution without requiring a tick re...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from datetime import timedelta
-from AlgorithmImports import *
-
-### <summary>
-### Regression algorithm asserting that historical data can be requested with tick resolution without requiring
-### a tick resolution subscription
-### </summary>
-class TickHistoryRequestWithoutTickSubscriptionRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2013, 10, 8)
- self.set_end_date(2013, 10, 8)
-
- # Subscribing SPY and IBM with daily and hour resolution instead of tick resolution
- spy = self.add_equity("SPY", Resolution.DAILY).symbol
- ibm = self.add_equity("IBM", Resolution.HOUR).symbol
-
- # Requesting history for SPY and IBM (separately) with tick resolution
- spy_history = self.history[Tick](spy, timedelta(days=1), Resolution.TICK)
- if len(list(spy_history)) == 0:
- raise Exception("SPY tick history is empty")
-
- ibm_history = self.history[Tick](ibm, timedelta(days=1), Resolution.TICK)
- if len(list(ibm_history)) == 0:
- raise Exception("IBM tick history is empty")
-
- # Requesting history for SPY and IBM (together) with tick resolution
- spy_ibm_history = self.history[Tick]([spy, ibm], timedelta(days=1), Resolution.TICK)
- if len(list(spy_ibm_history)) == 0:
- raise Exception("Compound SPY and IBM tick history is empty")
-
- self.quit()
diff --git a/fincept-qt/scripts/strategies/TiingoPriceAlgorithm.py b/fincept-qt/scripts/strategies/TiingoPriceAlgorithm.py
deleted file mode 100644
index 6e2c13fed..000000000
--- a/fincept-qt/scripts/strategies/TiingoPriceAlgorithm.py
+++ /dev/null
@@ -1,58 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-B0BD73CA
-# Category: General Strategy
-# Description: This example algorithm shows how to import and use Tiingo daily prices data
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-from QuantConnect.Data.Custom.Tiingo import *
-
-### <summary>
-### This example algorithm shows how to import and use Tiingo daily prices data.
-### </summary>
-### <meta name="tag" content="strategy example" />
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="custom data" />
-### <meta name="tag" content="tiingo" />
-class TiingoPriceAlgorithm(QCAlgorithm):
-
- def initialize(self):
- # Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
- self.set_start_date(2017, 1, 1)
- self.set_end_date(2017, 12, 31)
- self.set_cash(100000)
-
- # Set your Tiingo API Token here
- Tiingo.set_auth_code("my-tiingo-api-token")
-
- self.ticker = "AAPL"
- self.equity = self.add_equity(self.ticker).symbol
- self.aapl = self.add_data(TiingoPrice, self.ticker, Resolution.DAILY).symbol
-
- self.ema_fast = self.ema(self.equity, 5)
- self.ema_slow = self.ema(self.equity, 10)
-
-
- def on_data(self, slice):
- # OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
-
- if not slice.contains_key(self.ticker): return
-
- # Extract Tiingo data from the slice
- row = slice[self.ticker]
-
- if row is not None:
- if self.ema_fast.is_ready and self.ema_slow.is_ready:
- self.log(f"{self.time} - {row.symbol.value} - {row.close} {row.value} {row.price} - EmaFast:{self.ema_fast} - EmaSlow:{self.ema_slow}")
-
- # Simple EMA cross
- if not self.portfolio.invested and self.ema_fast > self.ema_slow:
- self.set_holdings(self.equity, 1)
-
- elif self.portfolio.invested and self.ema_fast < self.ema_slow:
- self.liquidate(self.equity)
diff --git a/fincept-qt/scripts/strategies/TimeInForceAlgorithm.py b/fincept-qt/scripts/strategies/TimeInForceAlgorithm.py
deleted file mode 100644
index abac6f3d9..000000000
--- a/fincept-qt/scripts/strategies/TimeInForceAlgorithm.py
+++ /dev/null
@@ -1,100 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-F8E8016B
-# Category: General Strategy
-# Description: Demonstration algorithm of time in force order settings
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Demonstration algorithm of time in force order settings.
-### </summary>
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="using quantconnect" />
-### <meta name="tag" content="trading and orders" />
-class TimeInForceAlgorithm(QCAlgorithm):
-
- # Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
- def initialize(self):
-
- self.set_start_date(2013,10,7)
- self.set_end_date(2013,10,11)
- self.set_cash(100000)
-
- # The default time in force setting for all orders is GoodTilCancelled (GTC),
- # uncomment this line to set a different time in force.
- # We currently only support GTC and DAY.
- # self.default_order_properties.time_in_force = TimeInForce.day
-
- self.symbol = self.add_equity("SPY", Resolution.MINUTE).symbol
-
- self.gtc_order_ticket1 = None
- self.gtc_order_ticket2 = None
- self.day_order_ticket1 = None
- self.day_order_ticket2 = None
- self.gtd_order_ticket1 = None
- self.gtd_order_ticket2 = None
- self.expected_order_statuses = {}
-
- # OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
- # Arguments:
- # data: Slice object keyed by symbol containing the stock data
- def on_data(self, data):
-
- if self.gtc_order_ticket1 is None:
- # These GTC orders will never expire and will not be canceled automatically.
-
- self.default_order_properties.time_in_force = TimeInForce.GOOD_TIL_CANCELED
-
- # this order will not be filled before the end of the backtest
- self.gtc_order_ticket1 = self.limit_order(self.symbol, 10, 100)
- self.expected_order_statuses[self.gtc_order_ticket1.order_id] = OrderStatus.SUBMITTED
-
- # this order will be filled before the end of the backtest
- self.gtc_order_ticket2 = self.limit_order(self.symbol, 10, 160)
- self.expected_order_statuses[self.gtc_order_ticket2.order_id] = OrderStatus.FILLED
-
- if self.day_order_ticket1 is None:
- # These DAY orders will expire at market close,
- # if not filled by then they will be canceled automatically.
-
- self.default_order_properties.time_in_force = TimeInForce.DAY
-
- # this order will not be filled before market close and will be canceled
- self.day_order_ticket1 = self.limit_order(self.symbol, 10, 140)
- self.expected_order_statuses[self.day_order_ticket1.order_id] = OrderStatus.CANCELED
-
- # this order will be filled before market close
- self.day_order_ticket2 = self.limit_order(self.symbol, 10, 180)
- self.expected_order_statuses[self.day_order_ticket2.order_id] = OrderStatus.FILLED
-
- if self.gtd_order_ticket1 is None:
- # These GTD orders will expire on October 10th at market close,
- # if not filled by then they will be canceled automatically.
-
- self.default_order_properties.time_in_force = TimeInForce.good_til_date(datetime(2013, 10, 10))
-
- # this order will not be filled before expiry and will be canceled
- self.gtd_order_ticket1 = self.limit_order(self.symbol, 10, 100)
- self.expected_order_statuses[self.gtd_order_ticket1.order_id] = OrderStatus.CANCELED
-
- # this order will be filled before expiry
- self.gtd_order_ticket2 = self.limit_order(self.symbol, 10, 160)
- self.expected_order_statuses[self.gtd_order_ticket2.order_id] = OrderStatus.FILLED
-
- # Order event handler. This handler will be called for all order events, including submissions, fills, cancellations.
- # This method can be called asynchronously, ensure you use proper locks on thread-unsafe objects
- def on_order_event(self, orderEvent):
- self.debug(f"{self.time} {orderEvent}")
-
- # End of algorithm run event handler. This method is called at the end of a backtest or live trading operation.
- def on_end_of_algorithm(self):
- for orderId, expectedStatus in self.expected_order_statuses.items():
- order = self.transactions.get_order_by_id(orderId)
- if order.status != expectedStatus:
- raise Exception(f"Invalid status for order {orderId} - Expected: {expectedStatus}, actual: {order.status}")
diff --git a/fincept-qt/scripts/strategies/TrailingStopOrderRegressionAlgorithm.py b/fincept-qt/scripts/strategies/TrailingStopOrderRegressionAlgorithm.py
deleted file mode 100644
index 40c2465eb..000000000
--- a/fincept-qt/scripts/strategies/TrailingStopOrderRegressionAlgorithm.py
+++ /dev/null
@@ -1,83 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-76B63DA7
-# Category: Regression Test
-# Description: Basic algorithm demonstrating how to place trailing stop orders
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Basic algorithm demonstrating how to place trailing stop orders.
-### </summary>
-### <meta name="tag" content="trading and orders" />
-### <meta name="tag" content="placing orders" />
-### <meta name="tag" content="trailing stop order"/>
-class TrailingStopOrderRegressionAlgorithm(QCAlgorithm):
- '''Basic algorithm demonstrating how to place trailing stop orders.'''
-
- buy_trailing_amount = 2
- sell_trailing_amount = 0.5
-
- def initialize(self):
-
- self.set_start_date(2013,10, 7)
- self.set_end_date(2013,10,11)
- self.set_cash(100000)
-
- self._symbol = self.add_equity("SPY").symbol
-
- self._buy_order_ticket: OrderTicket = None
- self._sell_order_ticket: OrderTicket = None
- self._previous_slice: Slice = None
-
- def on_data(self, slice: Slice):
- if not slice.contains_key(self._symbol):
- return
-
- if self._buy_order_ticket is None:
- self._buy_order_ticket = self.trailing_stop_order(self._symbol, 100, trailing_amount=self.buy_trailing_amount, trailing_as_percentage=False)
- elif self._buy_order_ticket.status != OrderStatus.FILLED:
- stop_price = self._buy_order_ticket.get(OrderField.STOP_PRICE)
-
- # Get the previous bar to compare to the stop price,
- # because stop price update attempt with the current slice data happens after OnData.
- low = self._previous_slice.quote_bars[self._symbol].ask.low if self._previous_slice.quote_bars.contains_key(self._symbol) \
- else self._previous_slice.bars[self._symbol].low
-
- stop_price_to_market_price_distance = stop_price - low
- if stop_price_to_market_price_distance > self.buy_trailing_amount:
- raise Exception(f"StopPrice {stop_price} should be within {self.buy_trailing_amount} of the previous low price {low} at all times.")
-
- if self._sell_order_ticket is None:
- if self.portfolio.invested:
- self._sell_order_ticket = self.trailing_stop_order(self._symbol, -100, trailing_amount=self.sell_trailing_amount, trailing_as_percentage=False)
- elif self._sell_order_ticket.status != OrderStatus.FILLED:
- stop_price = self._sell_order_ticket.get(OrderField.STOP_PRICE)
-
- # Get the previous bar to compare to the stop price,
- # because stop price update attempt with the current slice data happens after OnData.
- high = self._previous_slice.quote_bars[self._symbol].bid.high if self._previous_slice.quote_bars.contains_key(self._symbol) \
- else self._previous_slice.bars[self._symbol].high
- stop_price_to_market_price_distance = high - stop_price
- if stop_price_to_market_price_distance > self.sell_trailing_amount:
- raise Exception(f"StopPrice {stop_price} should be within {self.sell_trailing_amount} of the previous high price {high} at all times.")
-
- self._previous_slice = slice
-
- def on_order_event(self, orderEvent: OrderEvent):
- if orderEvent.status == OrderStatus.FILLED:
- if orderEvent.direction == OrderDirection.BUY:
- stop_price = self._buy_order_ticket.get(OrderField.STOP_PRICE)
- if orderEvent.fill_price < stop_price:
- raise Exception(f"Buy trailing stop order should have filled with price greater than or equal to the stop price {stop_price}. "
- f"Fill price: {orderEvent.fill_price}")
- else:
- stop_price = self._sell_order_ticket.get(OrderField.STOP_PRICE)
- if orderEvent.fill_price > stop_price:
- raise Exception(f"Sell trailing stop order should have filled with price less than or equal to the stop price {stop_price}. "
- f"Fill price: {orderEvent.fill_price}")
diff --git a/fincept-qt/scripts/strategies/TrailingStopRiskFrameworkRegressionAlgorithm.py b/fincept-qt/scripts/strategies/TrailingStopRiskFrameworkRegressionAlgorithm.py
deleted file mode 100644
index c1252bda3..000000000
--- a/fincept-qt/scripts/strategies/TrailingStopRiskFrameworkRegressionAlgorithm.py
+++ /dev/null
@@ -1,23 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-DD7ECCB4
-# Category: Risk Management
-# Description: Show example of how to use the TrailingStopRiskManagementModel
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-from BaseFrameworkRegressionAlgorithm import BaseFrameworkRegressionAlgorithm
-from Risk.TrailingStopRiskManagementModel import TrailingStopRiskManagementModel
-
-class TrailingStopRiskFrameworkRegressionAlgorithm(BaseFrameworkRegressionAlgorithm):
- '''Show example of how to use the TrailingStopRiskManagementModel'''
-
- def initialize(self):
- super().initialize()
- self.set_universe_selection(ManualUniverseSelectionModel([Symbol.create("AAPL", SecurityType.EQUITY, Market.USA)]))
-
- self.set_risk_management(TrailingStopRiskManagementModel(0.01))
diff --git a/fincept-qt/scripts/strategies/TrainingExampleAlgorithm.py b/fincept-qt/scripts/strategies/TrainingExampleAlgorithm.py
deleted file mode 100644
index 193c4356c..000000000
--- a/fincept-qt/scripts/strategies/TrainingExampleAlgorithm.py
+++ /dev/null
@@ -1,43 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-4F56A3E5
-# Category: General Strategy
-# Description: Example algorithm showing how to use QCAlgorithm.train method
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-from time import sleep
-
-### <summary>
-### Example algorithm showing how to use QCAlgorithm.train method
-### </summary>
-### <meta name="tag" content="using quantconnect" />
-### <meta name="tag" content="training" />
-class TrainingExampleAlgorithm(QCAlgorithm):
- '''Example algorithm showing how to use QCAlgorithm.train method'''
-
- def initialize(self):
-
- self.set_start_date(2013, 10, 7)
- self.set_end_date(2013, 10, 14)
-
- self.add_equity("SPY", Resolution.DAILY)
-
- # Set TrainingMethod to be executed immediately
- self.train(self.training_method)
-
- # Set TrainingMethod to be executed at 8:00 am every Sunday
- self.train(self.date_rules.every(DayOfWeek.SUNDAY), self.time_rules.at(8 , 0), self.training_method)
-
- def training_method(self):
-
- self.log(f'Start training at {self.time}')
- # Use the historical data to train the machine learning model
- history = self.history(["SPY"], 200, Resolution.DAILY)
-
- # ML code:
- pass
diff --git a/fincept-qt/scripts/strategies/TrainingInitializeRegressionAlgorithm.py b/fincept-qt/scripts/strategies/TrainingInitializeRegressionAlgorithm.py
deleted file mode 100644
index efc884303..000000000
--- a/fincept-qt/scripts/strategies/TrainingInitializeRegressionAlgorithm.py
+++ /dev/null
@@ -1,43 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-95DFEFEB
-# Category: Regression Test
-# Description: This regression algorithm is expected to fail and verifies that a training event created in Initialize will get run A...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-from time import sleep
-
-### <summary>
-### This regression algorithm is expected to fail and verifies that a training event
-### created in Initialize will get run AND it will cause the algorithm to fail if it
-### exceeds the "algorithm-manager-time-loop-maximum" config value, which the regression
-### test sets to 0.5 minutes.
-### </summary>
-class TrainingInitializeRegressionAlgorithm(QCAlgorithm):
- '''Example algorithm showing how to use QCAlgorithm.train method'''
-
- def initialize(self):
-
- self.set_start_date(2013, 10, 7)
- self.set_end_date(2013, 10, 11)
-
- self.add_equity("SPY", Resolution.DAILY)
-
- # this should cause the algorithm to fail
- # the regression test sets the time limit to 30 seconds and there's one extra
- # minute in the bucket, so a two minute sleep should result in RuntimeError
- self.train(lambda: sleep(150))
-
- # DateRules.tomorrow combined with TimeRules.midnight enforces that this event schedule will
- # have exactly one time, which will fire between the first data point and the next day at
- # midnight. So after the first data point, it will run this event and sleep long enough to
- # exceed the static max algorithm time loop time and begin to consume from the leaky bucket
- # the regression test sets the "algorithm-manager-time-loop-maximum" value to 30 seconds
- self.train(self.date_rules.tomorrow, self.time_rules.midnight, lambda: sleep(60))
- # this will consume the single 'minute' available in the leaky bucket
- # and the regression test will confirm that the leaky bucket is empty
diff --git a/fincept-qt/scripts/strategies/TwoLegCurrencyConversionRegressionAlgorithm.py b/fincept-qt/scripts/strategies/TwoLegCurrencyConversionRegressionAlgorithm.py
deleted file mode 100644
index 8bdb28a04..000000000
--- a/fincept-qt/scripts/strategies/TwoLegCurrencyConversionRegressionAlgorithm.py
+++ /dev/null
@@ -1,60 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-FED4E182
-# Category: Regression Test
-# Description: Regression algorithm which tests that a two leg currency conversion happens correctly
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Regression algorithm which tests that a two leg currency conversion happens correctly
-### </summary>
-class TwoLegCurrencyConversionRegressionAlgorithm(QCAlgorithm):
- def initialize(self):
- self.set_start_date(2018, 4, 4)
- self.set_end_date(2018, 4, 4)
- self.set_brokerage_model(BrokerageName.GDAX, AccountType.CASH)
- # GDAX doesn't have LTCETH or ETHLTC, but they do have ETHUSD and LTCUSD to form a path between ETH and LTC
- self.set_account_currency("ETH")
- self.set_cash("ETH", 100000)
- self.set_cash("LTC", 100000)
- self.set_cash("USD", 100000)
-
- self._eth_usd_symbol = self.add_crypto("ETHUSD", Resolution.MINUTE).symbol
- self._ltc_usd_symbol = self.add_crypto("LTCUSD", Resolution.MINUTE).symbol
-
- def on_data(self, data):
- if not self.portfolio.invested:
- self.market_order(self._ltc_usd_symbol, 1)
-
- def on_end_of_algorithm(self):
- ltc_cash = self.portfolio.cash_book["LTC"]
-
- conversion_symbols = [x.symbol for x in ltc_cash.currency_conversion.conversion_rate_securities]
-
- if len(conversion_symbols) != 2:
- raise ValueError(
- f"Expected two conversion rate securities for LTC to ETH, is {len(conversion_symbols)}")
-
- if conversion_symbols[0] != self._ltc_usd_symbol:
- raise ValueError(
- f"Expected first conversion rate security from LTC to ETH to be {self._ltc_usd_symbol}, is {conversion_symbols[0]}")
-
- if conversion_symbols[1] != self._eth_usd_symbol:
- raise ValueError(
- f"Expected second conversion rate security from LTC to ETH to be {self._eth_usd_symbol}, is {conversion_symbols[1]}")
-
- ltc_usd_value = self.securities[self._ltc_usd_symbol].get_last_data().value
- eth_usd_value = self.securities[self._eth_usd_symbol].get_last_data().value
-
- expected_conversion_rate = ltc_usd_value / eth_usd_value
- actual_conversion_rate = ltc_cash.conversion_rate
-
- if actual_conversion_rate != expected_conversion_rate:
- raise ValueError(
- f"Expected conversion rate from LTC to ETH to be {expected_conversion_rate}, is {actual_conversion_rate}")
diff --git a/fincept-qt/scripts/strategies/UniverseOnlyRegressionAlgorithm.py b/fincept-qt/scripts/strategies/UniverseOnlyRegressionAlgorithm.py
deleted file mode 100644
index 16b2524b6..000000000
--- a/fincept-qt/scripts/strategies/UniverseOnlyRegressionAlgorithm.py
+++ /dev/null
@@ -1,38 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-953A6967
-# Category: Universe Selection
-# Description: Asserts that algorithms can be universe-only, that is, universe selection is performed even if the ETF security is no...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Asserts that algorithms can be universe-only, that is, universe selection is performed even if the ETF security is not explicitly added.
-### Reproduces https://github.com/QuantConnect/Lean/issues/7473
-### </summary>
-class UniverseOnlyRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2020, 12, 1)
- self.set_end_date(2020, 12, 12)
- self.set_cash(100000)
-
- self.universe_settings.resolution = Resolution.DAILY
-
- # Add universe without a security added
- self.add_universe(self.universe.etf("GDVD", self.universe_settings, self.filter_universe))
-
- self.selection_done = False
-
- def filter_universe(self, constituents: List[ETFConstituentData]) -> List[Symbol]:
- self.selection_done = True
- return [x.symbol for x in constituents]
-
- def on_end_of_algorithm(self):
- if not self.selection_done:
- raise Exception("Universe selection was not performed")
diff --git a/fincept-qt/scripts/strategies/UniverseSelectedRegressionAlgorithm.py b/fincept-qt/scripts/strategies/UniverseSelectedRegressionAlgorithm.py
deleted file mode 100644
index d699aed44..000000000
--- a/fincept-qt/scripts/strategies/UniverseSelectedRegressionAlgorithm.py
+++ /dev/null
@@ -1,47 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-BAF35694
-# Category: Universe Selection
-# Description: Regression algorithm asserting the behavior of Universe.SELECTED collection
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Regression algorithm asserting the behavior of Universe.SELECTED collection
-### </summary>
-class UniverseSelectedRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2014, 3, 25)
- self.set_end_date(2014, 3, 27)
-
- self.universe_settings.resolution = Resolution.DAILY
-
- self._universe = self.add_universe(self.selection_function)
- self.selection_count = 0
-
- def selection_function(self, fundamentals):
- sorted_by_dollar_volume = sorted(fundamentals, key=lambda x: x.dollar_volume, reverse=True)
-
- sorted_by_dollar_volume = sorted_by_dollar_volume[self.selection_count:]
- self.selection_count = self.selection_count + 1
-
- # return the symbol objects of the top entries from our sorted collection
- return [ x.symbol for x in sorted_by_dollar_volume[:self.selection_count] ]
-
- def on_data(self, data):
- if Symbol.create("TSLA", SecurityType.EQUITY, Market.USA) in self._universe.selected:
- raise ValueError(f"TSLA shouldn't of been selected")
-
- self.buy(next(iter(self._universe.selected)), 1)
-
- def on_end_of_algorithm(self):
- if self.selection_count != 3:
- raise ValueError(f"Unexpected selection count {self.selection_count}")
- if self._universe.selected.count != 3 or self._universe.selected.count == self._universe.members.count:
- raise ValueError(f"Unexpected universe selected count {self._universe.selected.count}")
diff --git a/fincept-qt/scripts/strategies/UniverseSelectionDefinitionsAlgorithm.py b/fincept-qt/scripts/strategies/UniverseSelectionDefinitionsAlgorithm.py
deleted file mode 100644
index 42dfa9981..000000000
--- a/fincept-qt/scripts/strategies/UniverseSelectionDefinitionsAlgorithm.py
+++ /dev/null
@@ -1,58 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-DBD4926F
-# Category: Universe Selection
-# Description: This algorithm shows some of the various helper methods available when defining universes
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### This algorithm shows some of the various helper methods available when defining universes
-### </summary>
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="universes" />
-### <meta name="tag" content="coarse universes" />
-class UniverseSelectionDefinitionsAlgorithm(QCAlgorithm):
-
- def initialize(self):
- # subscriptions added via universe selection will have this resolution
- self.universe_settings.resolution = Resolution.DAILY
-
- self.set_start_date(2014,3,24) # Set Start Date
- self.set_end_date(2014,3,28) # Set End Date
- self.set_cash(100000) # Set Strategy Cash
-
- # add universe for the top 3 stocks by dollar volume
- self.add_universe(self.universe.top(3))
-
- self.changes = None
- self.on_securities_changed_was_called = False
-
- def on_data(self, data):
- if self.changes is None: return
-
- # liquidate securities that fell out of our universe
- for security in self.changes.removed_securities:
- if security.invested:
- self.liquidate(security.symbol)
-
- # invest in securities just added to our universe
- for security in self.changes.added_securities:
- if not security.invested:
- self.market_order(security.symbol, 10)
-
- self.changes = None
-
- # this event fires whenever we have changes to our universe
- def on_securities_changed(self, changes):
- self.changes = changes
- self.on_securities_changed_was_called = True
-
- def on_end_of_algorithm(self):
- if not self.on_securities_changed_was_called:
- raise Exception("OnSecuritiesChanged() method was never called!")
diff --git a/fincept-qt/scripts/strategies/UniverseSelectionRegressionAlgorithm.py b/fincept-qt/scripts/strategies/UniverseSelectionRegressionAlgorithm.py
deleted file mode 100644
index a1f6e7ba0..000000000
--- a/fincept-qt/scripts/strategies/UniverseSelectionRegressionAlgorithm.py
+++ /dev/null
@@ -1,76 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-E51F70E4
-# Category: Universe Selection
-# Description: Universe Selection regression algorithm simulates an edge case. In one week, Google listed two new symbols, delisted ...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Universe Selection regression algorithm simulates an edge case. In one week, Google listed two new symbols, delisted one of them and changed tickers.
-### </summary>
-### <meta name="tag" content="regression test" />
-class UniverseSelectionRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self):
-
- self.set_start_date(2014,3,22) #Set Start Date
- self.set_end_date(2014,4,7) #Set End Date
- self.set_cash(100000) #Set Strategy Cash
- # Fincept Terminal Strategy Engine - Symbol Configuration
- # security that exists with no mappings
- self.add_equity("SPY", Resolution.DAILY)
- # security that doesn't exist until half way in backtest (comes in as GOOCV)
- self.add_equity("GOOG", Resolution.DAILY)
-
- self.universe_settings.resolution = Resolution.DAILY
- self.add_universe(self.coarse_selection_function)
-
- self.delisted_symbols = []
- self.changes = None
-
-
- def coarse_selection_function(self, coarse):
- return [ c.symbol for c in coarse if c.symbol.value == "GOOG" or c.symbol.value == "GOOCV" or c.symbol.value == "GOOAV" or c.symbol.value == "GOOGL" ]
-
-
- def on_data(self, data):
- if self.transactions.orders_count == 0:
- self.market_order("SPY", 100)
-
- for kvp in data.delistings:
- self.delisted_symbols.append(kvp.key)
-
- if self.changes is None:
- return
-
- if not all(data.bars.contains_key(x.symbol) for x in self.changes.added_securities):
- return
-
- for security in self.changes.added_securities:
- self.log("{0}: Added Security: {1}".format(self.time, security.symbol))
- self.market_on_open_order(security.symbol, 100)
-
- for security in self.changes.removed_securities:
- self.log("{0}: Removed Security: {1}".format(self.time, security.symbol))
- if security.symbol not in self.delisted_symbols:
- self.log("Not in delisted: {0}:".format(security.symbol))
- self.market_on_open_order(security.symbol, -100)
-
- self.changes = None
-
-
- def on_securities_changed(self, changes):
- self.changes = changes
-
-
- def on_order_event(self, orderEvent):
- if orderEvent.status == OrderStatus.SUBMITTED:
- self.log("{0}: Submitted: {1}".format(self.time, self.transactions.get_order_by_id(orderEvent.order_id)))
- if orderEvent.status == OrderStatus.FILLED:
- self.log("{0}: Filled: {1}".format(self.time, self.transactions.get_order_by_id(orderEvent.order_id)))
diff --git a/fincept-qt/scripts/strategies/UniverseUnchangedRegressionAlgorithm.py b/fincept-qt/scripts/strategies/UniverseUnchangedRegressionAlgorithm.py
deleted file mode 100644
index c01d14a13..000000000
--- a/fincept-qt/scripts/strategies/UniverseUnchangedRegressionAlgorithm.py
+++ /dev/null
@@ -1,60 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-91035E43
-# Category: Universe Selection
-# Description: Regression algorithm used to test a fine and coarse selection methods returning Universe.UNCHANGED
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Regression algorithm used to test a fine and coarse selection methods returning Universe.UNCHANGED
-### </summary>
-class UniverseUnchangedRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.universe_settings.resolution = Resolution.DAILY
-
- # Order margin value has to have a minimum of 0.5% of Portfolio value, allows filtering out small trades and reduce fees.
- # Commented so regression algorithm is more sensitive
- #self.settings.minimum_order_margin_portfolio_percentage = 0.005
- self.set_start_date(2014,3,25)
- self.set_end_date(2014,4,7)
-
- self.set_alpha(ConstantAlphaModel(InsightType.PRICE, InsightDirection.UP, timedelta(days = 1), 0.025, None))
- self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())
-
- self.add_universe(self.coarse_selection_function, self.fine_selection_function)
-
- self.number_of_symbols_fine = 2
-
- def coarse_selection_function(self, coarse):
- # the first and second selection
- if self.time.date() <= date(2014, 3, 26):
- tickers = [ "AAPL", "AIG", "IBM" ]
- return [ Symbol.create(x, SecurityType.EQUITY, Market.USA) for x in tickers ]
-
- # will skip fine selection
- return Universe.UNCHANGED
-
- def fine_selection_function(self, fine):
- if self.time.date() == date(2014, 3, 25):
- sorted_by_pe_ratio = sorted(fine, key=lambda x: x.valuation_ratios.pe_ratio, reverse=True)
- return [ x.symbol for x in sorted_by_pe_ratio[:self.number_of_symbols_fine] ]
-
- # the second selection will return unchanged, in the following fine selection will be skipped
- return Universe.UNCHANGED
-
- # assert security changes, throw if called more than once
- def on_securities_changed(self, changes):
- added_symbols = [ x.symbol for x in changes.added_securities ]
- if (len(changes.added_securities) != 2
- or self.time.date() != date(2014, 3, 25)
- or Symbol.create("AAPL", SecurityType.EQUITY, Market.USA) not in added_symbols
- or Symbol.create("IBM", SecurityType.EQUITY, Market.USA) not in added_symbols):
- raise ValueError("Unexpected security changes")
- self.log(f"OnSecuritiesChanged({self.time}):: {changes}")
diff --git a/fincept-qt/scripts/strategies/UnregisterIndicatorRegressionAlgorithm.py b/fincept-qt/scripts/strategies/UnregisterIndicatorRegressionAlgorithm.py
deleted file mode 100644
index 1ff7217ec..000000000
--- a/fincept-qt/scripts/strategies/UnregisterIndicatorRegressionAlgorithm.py
+++ /dev/null
@@ -1,49 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-D8849489
-# Category: Indicators
-# Description: Example and regression algorithm asserting the behavior of registering and unregistering an indicator from the engine
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Example and regression algorithm asserting the behavior of registering and unregistering an indicator from the engine
-### </summary>
-class UnregisterIndicatorRegressionAlgorithm(QCAlgorithm):
- def initialize(self):
- '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
- self.set_start_date(2013,10, 7)
- self.set_end_date(2013,10,11)
-
- spy = self.add_equity("SPY")
- ibm = self.add_equity("IBM")
-
- self._symbols = [ spy.symbol, ibm.symbol ]
- self._trin = self.trin(self._symbols, Resolution.MINUTE)
- self._trin2 = None
-
- def on_data(self, data):
- '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
-
- Arguments:
- data: Slice object keyed by symbol containing the stock data
- '''
- if self._trin.is_ready:
- self._trin.reset()
- self.unregister_indicator(self._trin)
-
- # let's create a new one with a differente resolution
- self._trin2 = self.trin(self._symbols, Resolution.HOUR)
-
- if not self._trin2 is None and self._trin2.is_ready:
- if self._trin.is_ready:
- raise ValueError("Indicator should of stop getting updates!")
-
- if not self.portfolio.invested:
- self.set_holdings(self._symbols[0], 0.5)
- self.set_holdings(self._symbols[1], 0.5)
diff --git a/fincept-qt/scripts/strategies/UpdateOrderRegressionAlgorithm.py b/fincept-qt/scripts/strategies/UpdateOrderRegressionAlgorithm.py
deleted file mode 100644
index f64f6486c..000000000
--- a/fincept-qt/scripts/strategies/UpdateOrderRegressionAlgorithm.py
+++ /dev/null
@@ -1,122 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-BFC09E5D
-# Category: Regression Test
-# Description: Provides a regression baseline focused on updating orders
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-from math import copysign
-
-### <summary>
-### Provides a regression baseline focused on updating orders
-### </summary>
-### <meta name="tag" content="regression test" />
-class UpdateOrderRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self):
- '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
-
- self.set_start_date(2013,1,1) #Set Start Date
- self.set_end_date(2015,1,1) #Set End Date
- self.set_cash(100000) #Set Strategy Cash
- # Fincept Terminal Strategy Engine - Symbol Configuration
-
- self.security = self.add_equity("SPY", Resolution.DAILY)
-
- self.last_month = -1
- self.quantity = 100
- self.delta_quantity = 10
-
- self.stop_percentage = 0.025
- self.stop_percentage_delta = 0.005
- self.limit_percentage = 0.025
- self.limit_percentage_delta = 0.005
-
- order_type_enum = [OrderType.MARKET, OrderType.LIMIT, OrderType.STOP_MARKET, OrderType.STOP_LIMIT, OrderType.MARKET_ON_OPEN, OrderType.MARKET_ON_CLOSE, OrderType.TRAILING_STOP]
- self.order_types_queue = CircularQueue[OrderType](order_type_enum)
- self.order_types_queue.circle_completed += self.on_circle_completed
- self.tickets = []
-
-
- def on_circle_completed(self, sender, event):
- '''Flip our signs when we've gone through all the order types'''
- self.quantity *= -1
-
-
- def on_data(self, data):
- '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.'''
- if not data.bars.contains_key("SPY"):
- return
-
- if self.time.month != self.last_month:
- # we'll submit the next type of order from the queue
- order_type = self.order_types_queue.dequeue()
- #Log("")
- self.Log("\r\n--------------MONTH: {0}:: {1}".format(self.time.strftime("%B"), order_type))
- #Log("")
- self.last_month = self.time.month
- self.log("ORDER TYPE:: {0}".format(order_type))
- is_long = self.quantity > 0
- stop_price = (1 + self.stop_percentage)*data["SPY"].high if is_long else (1 - self.stop_percentage)*data["SPY"].low
- limit_price = (1 - self.limit_percentage)*stop_price if is_long else (1 + self.limit_percentage)*stop_price
-
- if order_type == OrderType.LIMIT:
- limit_price = (1 + self.limit_percentage)*data["SPY"].high if not is_long else (1 - self.limit_percentage)*data["SPY"].low
-
- request = SubmitOrderRequest(order_type, self.security.symbol.security_type, "SPY", self.quantity, stop_price, limit_price, 0, 0.01, True,
- self.utc_time, str(order_type))
- ticket = self.transactions.add_order(request)
- self.tickets.append(ticket)
-
- elif len(self.tickets) > 0:
- ticket = self.tickets[-1]
-
- if self.time.day > 8 and self.time.day < 14:
- if len(ticket.update_requests) == 0 and ticket.status is not OrderStatus.FILLED:
- self.log("TICKET:: {0}".format(ticket))
- update_order_fields = UpdateOrderFields()
- update_order_fields.quantity = ticket.quantity + copysign(self.delta_quantity, self.quantity)
- update_order_fields.tag = "Change quantity: {0}".format(self.time.day)
- ticket.update(update_order_fields)
-
- elif self.time.day > 13 and self.time.day < 20:
- if len(ticket.update_requests) == 1 and ticket.status is not OrderStatus.FILLED:
- self.log("TICKET:: {0}".format(ticket))
- update_order_fields = UpdateOrderFields()
- update_order_fields.limit_price = self.security.price*(1 - copysign(self.limit_percentage_delta, ticket.quantity))
- update_order_fields.stop_price = self.security.price*(1 + copysign(self.stop_percentage_delta, ticket.quantity)) if ticket.order_type != OrderType.TRAILING_STOP else None
- update_order_fields.tag = "Change prices: {0}".format(self.time.day)
- ticket.update(update_order_fields)
- else:
- if len(ticket.update_requests) == 2 and ticket.status is not OrderStatus.FILLED:
- self.log("TICKET:: {0}".format(ticket))
- ticket.cancel("{0} and is still open!".format(self.time.day))
- self.log("CANCELLED:: {0}".format(ticket.cancel_request))
-
-
- def on_order_event(self, orderEvent):
- order = self.transactions.get_order_by_id(orderEvent.order_id)
- ticket = self.transactions.get_order_ticket(orderEvent.order_id)
-
- #order cancelations update CanceledTime
- if order.status == OrderStatus.CANCELED and order.canceled_time != orderEvent.utc_time:
- raise ValueError("Expected canceled order CanceledTime to equal canceled order event time.")
-
- #fills update LastFillTime
- if (order.status == OrderStatus.FILLED or order.status == OrderStatus.PARTIALLY_FILLED) and order.last_fill_time != orderEvent.utc_time:
- raise ValueError("Expected filled order LastFillTime to equal fill order event time.")
-
- # check the ticket to see if the update was successfully processed
- if len([ur for ur in ticket.update_requests if ur.response is not None and ur.response.is_success]) > 0 and order.created_time != self.utc_time and order.last_update_time is None:
- raise ValueError("Expected updated order LastUpdateTime to equal submitted update order event time")
-
- if orderEvent.status == OrderStatus.FILLED:
- self.log("FILLED:: {0} FILL PRICE:: {1}".format(self.transactions.get_order_by_id(orderEvent.order_id), orderEvent.fill_price))
- else:
- self.log(orderEvent.to_string())
- self.log("TICKET:: {0}".format(ticket))
diff --git a/fincept-qt/scripts/strategies/UserDefinedUniverseAlgorithm.py b/fincept-qt/scripts/strategies/UserDefinedUniverseAlgorithm.py
deleted file mode 100644
index b151a0821..000000000
--- a/fincept-qt/scripts/strategies/UserDefinedUniverseAlgorithm.py
+++ /dev/null
@@ -1,49 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-90E557F4
-# Category: Universe Selection
-# Description: This algorithm shows how you can handle universe selection in anyway you like, at any time you like. This algorithm h...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-AddReference("System.Collections")
-from System.Collections.Generic import List
-
-### <summary>
-### This algorithm shows how you can handle universe selection in anyway you like,
-### at any time you like. This algorithm has a list of 10 stocks that it rotates
-### through every hour.
-### </summary>
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="universes" />
-### <meta name="tag" content="custom universes" />
-class UserDefinedUniverseAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_cash(100000)
- self.set_start_date(2015,1,1)
- self.set_end_date(2015,12,1)
- self.symbols = [ "SPY", "GOOG", "IBM", "AAPL", "MSFT", "CSCO", "ADBE", "WMT"]
-
- self.universe_settings.resolution = Resolution.HOUR
- self.add_universe('my_universe_name', Resolution.HOUR, self.selection)
-
- def selection(self, time):
- index = time.hour%len(self.symbols)
- return [self.symbols[index]]
-
- def on_data(self, slice):
- pass
-
- def on_securities_changed(self, changes):
- for removed in changes.removed_securities:
- if removed.invested:
- self.liquidate(removed.symbol)
-
- for added in changes.added_securities:
- self.set_holdings(added.symbol, 1/float(len(changes.added_securities)))
diff --git a/fincept-qt/scripts/strategies/VolumeRenkoConsolidatorAlgorithm.py b/fincept-qt/scripts/strategies/VolumeRenkoConsolidatorAlgorithm.py
deleted file mode 100644
index ed8f8ec8f..000000000
--- a/fincept-qt/scripts/strategies/VolumeRenkoConsolidatorAlgorithm.py
+++ /dev/null
@@ -1,71 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-253853F6
-# Category: Data Consolidation
-# Description: Demostrates the use of <see cref="VolumeRenkoConsolidator"/> for creating constant volume bar
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Demostrates the use of <see cref="VolumeRenkoConsolidator"/> for creating constant volume bar
-### </summary>
-### <meta name="tag" content="renko" />
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="consolidating data" />
-class VolumeRenkoConsolidatorAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2013, 10, 7)
- self.set_end_date(2013, 10, 11)
- self.set_cash(100000)
-
- self.sma = SimpleMovingAverage(10)
- self.tick_consolidated = False
-
- self.spy = self.add_equity("SPY", Resolution.MINUTE).symbol
- self.tradebar_volume_consolidator = VolumeRenkoConsolidator(1000000)
- self.tradebar_volume_consolidator.data_consolidated += self.on_spy_data_consolidated
-
- self.ibm = self.add_equity("IBM", Resolution.TICK).symbol
- self.tick_volume_consolidator = VolumeRenkoConsolidator(1000000)
- self.tick_volume_consolidator.data_consolidated += self.on_ibm_data_consolidated
-
- history = self.history[TradeBar](self.spy, 1000, Resolution.MINUTE)
- for bar in history:
- self.tradebar_volume_consolidator.update(bar)
-
- def on_spy_data_consolidated(self, sender, bar):
- self.sma.update(bar.end_time, bar.value)
- self.debug(f"SPY {bar.time} to {bar.end_time} :: O:{bar.open} H:{bar.high} L:{bar.low} C:{bar.close} V:{bar.volume}")
- if bar.volume != 1000000:
- raise Exception("Volume of consolidated bar does not match set value!")
-
- def on_ibm_data_consolidated(self, sender, bar):
- self.debug(f"IBM {bar.time} to {bar.end_time} :: O:{bar.open} H:{bar.high} L:{bar.low} C:{bar.close} V:{bar.volume}")
- if bar.volume != 1000000:
- raise Exception("Volume of consolidated bar does not match set value!")
- self.tick_consolidated = True
-
- def on_data(self, slice):
- # Update by TradeBar
- if slice.bars.contains_key(self.spy):
- self.tradebar_volume_consolidator.update(slice.bars[self.spy])
-
- # Update by Tick
- if slice.ticks.contains_key(self.ibm):
- for tick in slice.ticks[self.ibm]:
- self.tick_volume_consolidator.update(tick)
-
- if self.sma.is_ready and self.sma.current.value < self.securities[self.spy].price:
- self.set_holdings(self.spy, 1)
- else:
- self.set_holdings(self.spy, 0)
-
- def on_end_of_algorithm(self):
- if not self.tick_consolidated:
- raise Exception("Tick consolidator was never been called")
\ No newline at end of file
diff --git a/fincept-qt/scripts/strategies/VolumeShareSlippageModelAlgorithm.py b/fincept-qt/scripts/strategies/VolumeShareSlippageModelAlgorithm.py
deleted file mode 100644
index c3fb0674a..000000000
--- a/fincept-qt/scripts/strategies/VolumeShareSlippageModelAlgorithm.py
+++ /dev/null
@@ -1,51 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-8D857005
-# Category: General Strategy
-# Description: Example algorithm implementing VolumeShareSlippageModel
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-from Orders.Slippage.VolumeShareSlippageModel import VolumeShareSlippageModel
-
-### <summary>
-### Example algorithm implementing VolumeShareSlippageModel.
-### </summary>
-class VolumeShareSlippageModelAlgorithm(QCAlgorithm):
- longs = []
- shorts = []
-
- def initialize(self) -> None:
- self.set_start_date(2020, 11, 29)
- self.set_end_date(2020, 12, 2)
- # To set the slippage model to limit to fill only 30% volume of the historical volume, with 5% slippage impact.
- self.set_security_initializer(lambda security: security.set_slippage_model(VolumeShareSlippageModel(0.3, 0.05)))
-
- # Create SPY symbol to explore its constituents.
- spy = Symbol.create("SPY", SecurityType.EQUITY, Market.USA)
-
- self.universe_settings.resolution = Resolution.DAILY
- # Add universe to trade on the most and least weighted stocks among SPY constituents.
- self.add_universe(self.universe.etf(spy, universe_filter_func=self.selection))
-
- def selection(self, constituents: List[ETFConstituentUniverse]) -> List[Symbol]:
- sorted_by_weight = sorted(constituents, key=lambda c: c.weight)
- # Add the 10 most weighted stocks to the universe to long later.
- self.longs = [c.symbol for c in sorted_by_weight[-10:]]
- # Add the 10 least weighted stocks to the universe to short later.
- self.shorts = [c.symbol for c in sorted_by_weight[:10]]
-
- return self.longs + self.shorts
-
- def on_data(self, slice: Slice) -> None:
- # Equally invest into the selected stocks to evenly dissipate capital risk.
- # Dollar neutral of long and short stocks to eliminate systematic risk, only capitalize the popularity gap.
- targets = [PortfolioTarget(symbol, 0.05) for symbol in self.longs]
- targets += [PortfolioTarget(symbol, -0.05) for symbol in self.shorts]
-
- # Liquidate the ones not being the most and least popularity stocks to release fund for higher expected return trades.
- self.set_holdings(targets, liquidate_existing_holdings=True)
diff --git a/fincept-qt/scripts/strategies/VolumeWeightedAveragePriceExecutionModelRegressionAlgorithm.py b/fincept-qt/scripts/strategies/VolumeWeightedAveragePriceExecutionModelRegressionAlgorithm.py
deleted file mode 100644
index 888d74fd7..000000000
--- a/fincept-qt/scripts/strategies/VolumeWeightedAveragePriceExecutionModelRegressionAlgorithm.py
+++ /dev/null
@@ -1,56 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-2D03F945
-# Category: Execution Model
-# Description: Regression algorithm for the VolumeWeightedAveragePriceExecutionModel. This algorithm shows how the execution model w...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-from Alphas.RsiAlphaModel import RsiAlphaModel
-from Portfolio.EqualWeightingPortfolioConstructionModel import EqualWeightingPortfolioConstructionModel
-from Execution.VolumeWeightedAveragePriceExecutionModel import VolumeWeightedAveragePriceExecutionModel
-
-### <summary>
-### Regression algorithm for the VolumeWeightedAveragePriceExecutionModel.
-### This algorithm shows how the execution model works to split up orders and
-### submit them only when the price is on the favorable side of the intraday VWAP.
-### </summary>
-### <meta name="tag" content="using data" />
-### <meta name="tag" content="using quantconnect" />
-### <meta name="tag" content="trading and orders" />
-class VolumeWeightedAveragePriceExecutionModelRegressionAlgorithm(QCAlgorithm):
- '''Regression algorithm for the VolumeWeightedAveragePriceExecutionModel.
- This algorithm shows how the execution model works to split up orders and
- submit them only when the price is on the favorable side of the intraday VWAP.'''
-
- def initialize(self):
-
- self.universe_settings.resolution = Resolution.MINUTE
-
- self.set_start_date(2013,10,7)
- self.set_end_date(2013,10,11)
- self.set_cash(1000000)
-
- self.set_universe_selection(ManualUniverseSelectionModel([
- Symbol.create('AIG', SecurityType.EQUITY, Market.USA),
- Symbol.create('BAC', SecurityType.EQUITY, Market.USA),
- Symbol.create('IBM', SecurityType.EQUITY, Market.USA),
- Symbol.create('SPY', SecurityType.EQUITY, Market.USA)
- ]))
-
- # using hourly rsi to generate more insights
- self.set_alpha(RsiAlphaModel(14, Resolution.HOUR))
- self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())
- self.set_execution(VolumeWeightedAveragePriceExecutionModel())
-
- self.insights_generated += self.on_insights_generated
-
- def on_insights_generated(self, algorithm, data):
- self.log(f"{self.time}: {', '.join(str(x) for x in data.insights)}")
-
- def on_order_event(self, orderEvent):
- self.log(f"{self.time}: {orderEvent}")
diff --git a/fincept-qt/scripts/strategies/WarmupAlgorithm.py b/fincept-qt/scripts/strategies/WarmupAlgorithm.py
deleted file mode 100644
index ada5b9252..000000000
--- a/fincept-qt/scripts/strategies/WarmupAlgorithm.py
+++ /dev/null
@@ -1,52 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-DB342081
-# Category: Warmup
-# Description: Demonstration algorithm for the Warm Up feature with basic indicators
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Demonstration algorithm for the Warm Up feature with basic indicators.
-### </summary>
-### <meta name="tag" content="indicators" />
-### <meta name="tag" content="warm up" />
-### <meta name="tag" content="history and warm up" />
-### <meta name="tag" content="using data" />
-class WarmupAlgorithm(QCAlgorithm):
-
- def initialize(self):
- '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
-
- self.set_start_date(2013,10,8) #Set Start Date
- self.set_end_date(2013,10,11) #Set End Date
- self.set_cash(100000) #Set Strategy Cash
- # Fincept Terminal Strategy Engine - Symbol Configuration
- self.add_equity("SPY", Resolution.SECOND)
-
- fast_period = 60
- slow_period = 3600
-
- self.fast = self.EMA("SPY", fast_period)
- self.slow = self.EMA("SPY", slow_period)
-
- self.set_warmup(slow_period)
- self.first = True
-
-
- def on_data(self, data):
- '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.'''
- if self.first and not self.is_warming_up:
- self.first = False
- self.log("Fast: {0}".format(self.fast.samples))
- self.log("Slow: {0}".format(self.slow.samples))
-
- if self.fast.current.value > self.slow.current.value:
- self.set_holdings("SPY", 1)
- else:
- self.set_holdings("SPY", -1)
diff --git a/fincept-qt/scripts/strategies/WarmupHistoryAlgorithm.py b/fincept-qt/scripts/strategies/WarmupHistoryAlgorithm.py
deleted file mode 100644
index b9921154e..000000000
--- a/fincept-qt/scripts/strategies/WarmupHistoryAlgorithm.py
+++ /dev/null
@@ -1,61 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-E048C42D
-# Category: Warmup
-# Description: This algorithm demonstrates using the history provider to retrieve data to warm up indicators before data is received
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### This algorithm demonstrates using the history provider to retrieve data
-### to warm up indicators before data is received.
-### </summary>
-### <meta name="tag" content="indicators" />
-### <meta name="tag" content="history" />
-### <meta name="tag" content="history and warm up" />
-### <meta name="tag" content="using data" />
-class WarmupHistoryAlgorithm(QCAlgorithm):
-
- def initialize(self):
- '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
-
- self.set_start_date(2014,5,2) #Set Start Date
- self.set_end_date(2014,5,2) #Set End Date
- self.set_cash(100000) #Set Strategy Cash
- # Fincept Terminal Strategy Engine - Symbol Configuration
- forex = self.add_forex("EURUSD", Resolution.SECOND)
- forex = self.add_forex("NZDUSD", Resolution.SECOND)
-
- fast_period = 60
- slow_period = 3600
- self.fast = self.ema("EURUSD", fast_period)
- self.slow = self.ema("EURUSD", slow_period)
-
- # "slow_period + 1" because rolling window waits for one to fall off the back to be considered ready
- # History method returns a dict with a pandas.data_frame
- history = self.history(["EURUSD", "NZDUSD"], slow_period + 1)
-
- # prints out the tail of the dataframe
- self.log(str(history.loc["EURUSD"].tail()))
- self.log(str(history.loc["NZDUSD"].tail()))
-
- for index, row in history.loc["EURUSD"].iterrows():
- self.fast.update(index, row["close"])
- self.slow.update(index, row["close"])
-
- self.log("FAST {0} READY. Samples: {1}".format("IS" if self.fast.is_ready else "IS NOT", self.fast.samples))
- self.log("SLOW {0} READY. Samples: {1}".format("IS" if self.slow.is_ready else "IS NOT", self.slow.samples))
-
-
- def on_data(self, data):
- '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.'''
-
- if self.fast.current.value > self.slow.current.value:
- self.set_holdings("EURUSD", 1)
- else:
- self.set_holdings("EURUSD", -1)
diff --git a/fincept-qt/scripts/strategies/WeeklyUniverseSelectionRegressionAlgorithm.py b/fincept-qt/scripts/strategies/WeeklyUniverseSelectionRegressionAlgorithm.py
deleted file mode 100644
index 535d843cf..000000000
--- a/fincept-qt/scripts/strategies/WeeklyUniverseSelectionRegressionAlgorithm.py
+++ /dev/null
@@ -1,47 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-161A4DE8
-# Category: Universe Selection
-# Description: Weekly rotation strategy inspired by universe selection. Buys
-# at the start of each week if price is above 10-day SMA, exits at the end
-# of the week. Captures weekly momentum trends.
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-class WeeklyUniverseSelectionRegressionAlgorithm(QCAlgorithm):
- """Weekly momentum rotation with SMA filter."""
-
- def initialize(self):
- self.set_start_date(2023, 1, 1)
- self.set_end_date(2024, 1, 1)
- self.set_cash(100000)
-
- self.symbol = "SPY"
- self.add_equity(self.symbol, Resolution.DAILY)
-
- self._sma = self.sma(self.symbol, 10, Resolution.DAILY)
- self._last_week = -1
-
- def on_data(self, data):
- if not self._sma.is_ready:
- return
- if self.symbol not in data:
- return
-
- price = data[self.symbol].close
- current_week = self.time.isocalendar()[1]
-
- if current_week != self._last_week:
- self._last_week = current_week
- # Weekly decision: enter if price > SMA, exit otherwise
- if price > self._sma.current.value:
- if not self.portfolio.invested:
- self.set_holdings(self.symbol, 1)
- else:
- if self.portfolio.invested:
- self.liquidate()
diff --git a/fincept-qt/scripts/strategies/ZeroedBenchmarkRegressionAlgorithm.py b/fincept-qt/scripts/strategies/ZeroedBenchmarkRegressionAlgorithm.py
deleted file mode 100644
index 812952542..000000000
--- a/fincept-qt/scripts/strategies/ZeroedBenchmarkRegressionAlgorithm.py
+++ /dev/null
@@ -1,46 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-F69688F5
-# Category: Regression Test
-# Description: Regression algorithm to test zeroed benchmark through BrokerageModel override
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Regression algorithm to test zeroed benchmark through BrokerageModel override
-### </summary>
-### <meta name="tag" content="regression test" />
-class ZeroedBenchmarkRegressionAlgorithm(QCAlgorithm):
-
- def initialize(self):
- self.set_cash(100000)
- self.set_start_date(2013,10,7)
- self.set_end_date(2013,10,8)
-
- # Add Equity
- self.add_equity("SPY", Resolution.HOUR)
-
- # Use our Test Brokerage Model with zerod default benchmark
- self.set_brokerage_model(TestBrokerageModel())
-
- def on_data(self, data):
- '''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
-
- Arguments:
- data: Slice object keyed by symbol containing the stock data
- '''
- if not self.portfolio.invested:
- self.set_holdings("SPY", 1)
-
-class TestBrokerageModel(DefaultBrokerageModel):
-
- def get_benchmark(self, securities):
- return FuncBenchmark(self.func)
-
- def func(self, datetime):
- return 0
diff --git a/fincept-qt/scripts/strategies/__init__.py b/fincept-qt/scripts/strategies/__init__.py
deleted file mode 100644
index a7c6f5f1e..000000000
--- a/fincept-qt/scripts/strategies/__init__.py
+++ /dev/null
@@ -1,2 +0,0 @@
-# Fincept Terminal - Strategy Engine
-# Auto-generated strategy package
diff --git a/fincept-qt/scripts/strategies/_registry.py b/fincept-qt/scripts/strategies/_registry.py
deleted file mode 100644
index 54f70bdc1..000000000
--- a/fincept-qt/scripts/strategies/_registry.py
+++ /dev/null
@@ -1,425 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Registry
-# Auto-generated index of all available strategies
-# ============================================================================
-
-STRATEGY_REGISTRY = {
- "FCT-19E8A564": {"name": "AccumulativeInsightPortfolioRegressionAlgorithm", "category": "Portfolio Management", "path": "AccumulativeInsightPortfolioRegressionAlgorithm.py"},
- "FCT-761339E9": {"name": "AddAlphaModelAlgorithm", "category": "Alpha Model", "path": "AddAlphaModelAlgorithm.py"},
- "FCT-3CCF5CE2": {"name": "AddFutureOptionContractDataStreamingRegressionAlgorithm", "category": "Options", "path": "AddFutureOptionContractDataStreamingRegressionAlgorithm.py"},
- "FCT-2EF41B6D": {"name": "AddFutureOptionSingleOptionChainSelectedInUniverseFilterRegressionAlgorithm", "category": "Options", "path": "AddFutureOptionSingleOptionChainSelectedInUniverseFilterRegressionAlgorithm.py"},
- "FCT-5CED3309": {"name": "AddOptionContractExpiresRegressionAlgorithm", "category": "Options", "path": "AddOptionContractExpiresRegressionAlgorithm.py"},
- "FCT-202B8187": {"name": "AddOptionContractFromUniverseRegressionAlgorithm", "category": "Options", "path": "AddOptionContractFromUniverseRegressionAlgorithm.py"},
- "FCT-DA228821": {"name": "AddRemoveSecurityRegressionAlgorithm", "category": "Regression Test", "path": "AddRemoveSecurityRegressionAlgorithm.py"},
- "FCT-9874FF18": {"name": "AddRiskManagementAlgorithm", "category": "Risk Management", "path": "AddRiskManagementAlgorithm.py"},
- "FCT-8AB253F8": {"name": "AddUniverseSelectionModelAlgorithm", "category": "Universe Selection", "path": "AddUniverseSelectionModelAlgorithm.py"},
- "FCT-D137348C": {"name": "AlgorithmModeAndDeploymentTargetAlgorithm", "category": "General Strategy", "path": "AlgorithmModeAndDeploymentTargetAlgorithm.py"},
- "FCT-6C937E43": {"name": "AllShortableSymbolsCoarseSelectionRegressionAlgorithm", "category": "Regression Test", "path": "AllShortableSymbolsCoarseSelectionRegressionAlgorithm.py"},
- "FCT-F9837218": {"name": "AsynchronousUniverseRegressionAlgorithm", "category": "Universe Selection", "path": "AsynchronousUniverseRegressionAlgorithm.py"},
- "FCT-5FF79273": {"name": "AutoRegressiveIntegratedMovingAverageRegressionAlgorithm", "category": "Regression Test", "path": "AutoRegressiveIntegratedMovingAverageRegressionAlgorithm.py"},
- "FCT-C395D1D2": {"name": "AuxiliaryDataHandlersRegressionAlgorithm", "category": "Regression Test", "path": "AuxiliaryDataHandlersRegressionAlgorithm.py"},
- "FCT-0A7F740C": {"name": "BaseFrameworkRegressionAlgorithm", "category": "Regression Test", "path": "BaseFrameworkRegressionAlgorithm.py"},
- "FCT-3B2A7C04": {"name": "BasicCSharpIntegrationTemplateAlgorithm", "category": "Template", "path": "BasicCSharpIntegrationTemplateAlgorithm.py"},
- "FCT-07DF2AB7": {"name": "BasicSetAccountCurrencyAlgorithm", "category": "General Strategy", "path": "BasicSetAccountCurrencyAlgorithm.py"},
- "FCT-9A26B9BE": {"name": "BasicSetAccountCurrencyWithAmountAlgorithm", "category": "General Strategy", "path": "BasicSetAccountCurrencyWithAmountAlgorithm.py"},
- "FCT-82A09B26": {"name": "BasicTemplateAlgorithm", "category": "Template", "path": "BasicTemplateAlgorithm.py"},
- "FCT-0FAA6BDF": {"name": "BasicTemplateAxosAlgorithm", "category": "Template", "path": "BasicTemplateAxosAlgorithm.py"},
- "FCT-07CF5BDC": {"name": "BasicTemplateCfdAlgorithm", "category": "Template", "path": "BasicTemplateCfdAlgorithm.py"},
- "FCT-CED11838": {"name": "BasicTemplateContinuousFutureAlgorithm", "category": "Futures", "path": "BasicTemplateContinuousFutureAlgorithm.py"},
- "FCT-34321EAB": {"name": "BasicTemplateContinuousFutureWithExtendedMarketAlgorithm", "category": "Futures", "path": "BasicTemplateContinuousFutureWithExtendedMarketAlgorithm.py"},
- "FCT-C45FB406": {"name": "BasicTemplateCryptoAlgorithm", "category": "Crypto", "path": "BasicTemplateCryptoAlgorithm.py"},
- "FCT-F09974A0": {"name": "BasicTemplateCryptoFutureAlgorithm", "category": "Futures", "path": "BasicTemplateCryptoFutureAlgorithm.py"},
- "FCT-E96624E8": {"name": "BasicTemplateCryptoFutureHourlyAlgorithm", "category": "Futures", "path": "BasicTemplateCryptoFutureHourlyAlgorithm.py"},
- "FCT-1ADBAC8E": {"name": "BasicTemplateDailyAlgorithm", "category": "Template", "path": "BasicTemplateDailyAlgorithm.py"},
- "FCT-59CC070D": {"name": "BasicTemplateEurexFuturesAlgorithm", "category": "Futures", "path": "BasicTemplateEurexFuturesAlgorithm.py"},
- "FCT-D7F55E8F": {"name": "BasicTemplateFillForwardAlgorithm", "category": "Template", "path": "BasicTemplateFillForwardAlgorithm.py"},
- "FCT-DBF9152F": {"name": "BasicTemplateForexAlgorithm", "category": "Forex", "path": "BasicTemplateForexAlgorithm.py"},
- "FCT-EE88AED1": {"name": "BasicTemplateFrameworkAlgorithm", "category": "Template", "path": "BasicTemplateFrameworkAlgorithm.py"},
- "FCT-2426C5B7": {"name": "BasicTemplateFutureOptionAlgorithm", "category": "Options", "path": "BasicTemplateFutureOptionAlgorithm.py"},
- "FCT-1DD3D3FC": {"name": "BasicTemplateFutureRolloverAlgorithm", "category": "Futures", "path": "BasicTemplateFutureRolloverAlgorithm.py"},
- "FCT-D9822D5B": {"name": "BasicTemplateFuturesAlgorithm", "category": "Futures", "path": "BasicTemplateFuturesAlgorithm.py"},
- "FCT-C0AB4825": {"name": "BasicTemplateFuturesConsolidationAlgorithm", "category": "Futures", "path": "BasicTemplateFuturesConsolidationAlgorithm.py"},
- "FCT-B04B5965": {"name": "BasicTemplateFuturesDailyAlgorithm", "category": "Futures", "path": "BasicTemplateFuturesDailyAlgorithm.py"},
- "FCT-3F20A848": {"name": "BasicTemplateFuturesFrameworkAlgorithm", "category": "Futures", "path": "BasicTemplateFuturesFrameworkAlgorithm.py"},
- "FCT-456D112C": {"name": "BasicTemplateFuturesFrameworkWithExtendedMarketAlgorithm", "category": "Futures", "path": "BasicTemplateFuturesFrameworkWithExtendedMarketAlgorithm.py"},
- "FCT-265D788C": {"name": "BasicTemplateFuturesHistoryAlgorithm", "category": "Futures", "path": "BasicTemplateFuturesHistoryAlgorithm.py"},
- "FCT-9713D1F5": {"name": "BasicTemplateFuturesHistoryWithExtendedMarketHoursAlgorithm", "category": "Futures", "path": "BasicTemplateFuturesHistoryWithExtendedMarketHoursAlgorithm.py"},
- "FCT-D52E449D": {"name": "BasicTemplateFuturesHourlyAlgorithm", "category": "Futures", "path": "BasicTemplateFuturesHourlyAlgorithm.py"},
- "FCT-527E38F2": {"name": "BasicTemplateFuturesWithExtendedMarketAlgorithm", "category": "Futures", "path": "BasicTemplateFuturesWithExtendedMarketAlgorithm.py"},
- "FCT-074CBF2C": {"name": "BasicTemplateFuturesWithExtendedMarketDailyAlgorithm", "category": "Futures", "path": "BasicTemplateFuturesWithExtendedMarketDailyAlgorithm.py"},
- "FCT-006DF51F": {"name": "BasicTemplateFuturesWithExtendedMarketHourlyAlgorithm", "category": "Futures", "path": "BasicTemplateFuturesWithExtendedMarketHourlyAlgorithm.py"},
- "FCT-A17DA593": {"name": "BasicTemplateIndexAlgorithm", "category": "Index", "path": "BasicTemplateIndexAlgorithm.py"},
- "FCT-A8601615": {"name": "BasicTemplateIndexDailyAlgorithm", "category": "Index", "path": "BasicTemplateIndexDailyAlgorithm.py"},
- "FCT-210273A6": {"name": "BasicTemplateIndexOptionsAlgorithm", "category": "Options", "path": "BasicTemplateIndexOptionsAlgorithm.py"},
- "FCT-CB56992B": {"name": "BasicTemplateIndiaAlgorithm", "category": "Template", "path": "BasicTemplateIndiaAlgorithm.py"},
- "FCT-77306E7F": {"name": "BasicTemplateIndiaIndexAlgorithm", "category": "Index", "path": "BasicTemplateIndiaIndexAlgorithm.py"},
- "FCT-13F865B8": {"name": "BasicTemplateIntrinioEconomicData", "category": "Template", "path": "BasicTemplateIntrinioEconomicData.py"},
- "FCT-A18CA8E6": {"name": "BasicTemplateLibrary", "category": "Template", "path": "BasicTemplateLibrary.py"},
- "FCT-3EB6E68A": {"name": "BasicTemplateOptionEquityStrategyAlgorithm", "category": "Options", "path": "BasicTemplateOptionEquityStrategyAlgorithm.py"},
- "FCT-185C6BF9": {"name": "BasicTemplateOptionStrategyAlgorithm", "category": "Options", "path": "BasicTemplateOptionStrategyAlgorithm.py"},
- "FCT-29268ED2": {"name": "BasicTemplateOptionTradesAlgorithm", "category": "Options", "path": "BasicTemplateOptionTradesAlgorithm.py"},
- "FCT-9970673F": {"name": "BasicTemplateOptionsAlgorithm", "category": "Options", "path": "BasicTemplateOptionsAlgorithm.py"},
- "FCT-48AE2A59": {"name": "BasicTemplateOptionsConsolidationAlgorithm", "category": "Options", "path": "BasicTemplateOptionsConsolidationAlgorithm.py"},
- "FCT-216E29F5": {"name": "BasicTemplateOptionsDailyAlgorithm", "category": "Options", "path": "BasicTemplateOptionsDailyAlgorithm.py"},
- "FCT-702E8C68": {"name": "BasicTemplateOptionsFilterUniverseAlgorithm", "category": "Options", "path": "BasicTemplateOptionsFilterUniverseAlgorithm.py"},
- "FCT-778FF392": {"name": "BasicTemplateOptionsFrameworkAlgorithm", "category": "Options", "path": "BasicTemplateOptionsFrameworkAlgorithm.py"},
- "FCT-9F0275D6": {"name": "BasicTemplateOptionsHistoryAlgorithm", "category": "Options", "path": "BasicTemplateOptionsHistoryAlgorithm.py"},
- "FCT-77549805": {"name": "BasicTemplateOptionsHourlyAlgorithm", "category": "Options", "path": "BasicTemplateOptionsHourlyAlgorithm.py"},
- "FCT-79BA1C77": {"name": "BasicTemplateOptionsPriceModel", "category": "Options", "path": "BasicTemplateOptionsPriceModel.py"},
- "FCT-DB3B5321": {"name": "BasicTemplateSPXWeeklyIndexOptionsAlgorithm", "category": "Options", "path": "BasicTemplateSPXWeeklyIndexOptionsAlgorithm.py"},
- "FCT-88C8DA85": {"name": "BasicTemplateTradableIndexAlgorithm", "category": "Index", "path": "BasicTemplateTradableIndexAlgorithm.py"},
- "FCT-8B86F74C": {"name": "BlackLittermanPortfolioOptimizationFrameworkAlgorithm", "category": "Portfolio Management", "path": "BlackLittermanPortfolioOptimizationFrameworkAlgorithm.py"},
- "FCT-13992977": {"name": "BrokerageActivityEventHandlingAlgorithm", "category": "Brokerage", "path": "BrokerageActivityEventHandlingAlgorithm.py"},
- "FCT-21FCDA65": {"name": "BrokerageModelAlgorithm", "category": "Brokerage", "path": "BrokerageModelAlgorithm.py"},
- "FCT-181E0A50": {"name": "BubbleAlgorithm", "category": "General Strategy", "path": "BubbleAlgorithm.py"},
- "FCT-C4535414": {"name": "BybitCryptoFuturesRegressionAlgorithm", "category": "Futures", "path": "BybitCryptoFuturesRegressionAlgorithm.py"},
- "FCT-8205EE4A": {"name": "BybitCryptoRegressionAlgorithm", "category": "Crypto", "path": "BybitCryptoRegressionAlgorithm.py"},
- "FCT-E8BBF79A": {"name": "BybitCustomDataCryptoRegressionAlgorithm", "category": "Crypto", "path": "BybitCustomDataCryptoRegressionAlgorithm.py"},
- "FCT-E8875612": {"name": "CallbackCommandRegressionAlgorithm", "category": "Regression Test", "path": "CallbackCommandRegressionAlgorithm.py"},
- "FCT-D8FB9470": {"name": "CanLiquidateWithOrderPropertiesRegressionAlgorithm", "category": "Regression Test", "path": "CanLiquidateWithOrderPropertiesRegressionAlgorithm.py"},
- "FCT-65D25230": {"name": "CapmAlphaRankingFrameworkAlgorithm", "category": "Alpha Model", "path": "CapmAlphaRankingFrameworkAlgorithm.py"},
- "FCT-F172EB67": {"name": "ClassicRangeConsolidatorAlgorithm", "category": "Data Consolidation", "path": "ClassicRangeConsolidatorAlgorithm.py"},
- "FCT-5407C44C": {"name": "ClassicRangeConsolidatorWithTickAlgorithm", "category": "Data Consolidation", "path": "ClassicRangeConsolidatorWithTickAlgorithm.py"},
- "FCT-D909F7DF": {"name": "ClassicRenkoConsolidatorAlgorithm", "category": "Data Consolidation", "path": "ClassicRenkoConsolidatorAlgorithm.py"},
- "FCT-A0A879A8": {"name": "CoarseFineAsyncUniverseRegressionAlgorithm", "category": "Universe Selection", "path": "CoarseFineAsyncUniverseRegressionAlgorithm.py"},
- "FCT-CE80899F": {"name": "CoarseFineFundamentalComboAlgorithm", "category": "General Strategy", "path": "CoarseFineFundamentalComboAlgorithm.py"},
- "FCT-BF06E7EB": {"name": "CoarseFineFundamentalRegressionAlgorithm", "category": "Regression Test", "path": "CoarseFineFundamentalRegressionAlgorithm.py"},
- "FCT-5542D978": {"name": "CoarseFineOptionUniverseChainRegressionAlgorithm", "category": "Options", "path": "CoarseFineOptionUniverseChainRegressionAlgorithm.py"},
- "FCT-F95F1806": {"name": "CoarseFundamentalTop3Algorithm", "category": "General Strategy", "path": "CoarseFundamentalTop3Algorithm.py"},
- "FCT-5600B07D": {"name": "Collective2PortfolioSignalExportDemonstrationAlgorithm", "category": "Portfolio Management", "path": "Collective2PortfolioSignalExportDemonstrationAlgorithm.py"},
- "FCT-8AEECDC1": {"name": "Collective2SignalExportDemonstrationAlgorithm", "category": "General Strategy", "path": "Collective2SignalExportDemonstrationAlgorithm.py"},
- "FCT-EB692DBC": {"name": "ComboOrderTicketDemoAlgorithm", "category": "General Strategy", "path": "ComboOrderTicketDemoAlgorithm.py"},
- "FCT-203BF5C3": {"name": "ComboOrdersFillModelAlgorithm", "category": "General Strategy", "path": "ComboOrdersFillModelAlgorithm.py"},
- "FCT-5E302074": {"name": "CompleteOrderTagUpdateAlgorithm", "category": "General Strategy", "path": "CompleteOrderTagUpdateAlgorithm.py"},
- "FCT-50C4F04D": {"name": "CompositeAlphaModelFrameworkAlgorithm", "category": "Alpha Model", "path": "CompositeAlphaModelFrameworkAlgorithm.py"},
- "FCT-5A1D14B7": {"name": "CompositeRiskManagementModelFrameworkAlgorithm", "category": "Risk Management", "path": "CompositeRiskManagementModelFrameworkAlgorithm.py"},
- "FCT-9EECE18B": {"name": "ConfidenceWeightedFrameworkAlgorithm", "category": "General Strategy", "path": "ConfidenceWeightedFrameworkAlgorithm.py"},
- "FCT-C054C3D1": {"name": "ConsolidateDifferentTickTypesRegressionAlgorithm", "category": "Data Consolidation", "path": "ConsolidateDifferentTickTypesRegressionAlgorithm.py"},
- "FCT-D4F95392": {"name": "ConsolidateHourBarsIntoDailyBarsRegressionAlgorithm", "category": "Data Consolidation", "path": "ConsolidateHourBarsIntoDailyBarsRegressionAlgorithm.py"},
- "FCT-16F5EE2E": {"name": "ConsolidateRegressionAlgorithm", "category": "Data Consolidation", "path": "ConsolidateRegressionAlgorithm.py"},
- "FCT-EFBD246D": {"name": "ConstituentsQC500GeneratorAlgorithm", "category": "General Strategy", "path": "ConstituentsQC500GeneratorAlgorithm.py"},
- "FCT-DE244AD5": {"name": "ConstituentsUniverseRegressionAlgorithm", "category": "Universe Selection", "path": "ConstituentsUniverseRegressionAlgorithm.py"},
- "FCT-E27B6A38": {"name": "ContinuousFutureModelsConsistencyRegressionAlgorithm", "category": "Futures", "path": "ContinuousFutureModelsConsistencyRegressionAlgorithm.py"},
- "FCT-C573FB46": {"name": "ContinuousFutureRegressionAlgorithm", "category": "Futures", "path": "ContinuousFutureRegressionAlgorithm.py"},
- "FCT-E9C47E95": {"name": "ConvertToFrameworkAlgorithm", "category": "General Strategy", "path": "ConvertToFrameworkAlgorithm.py"},
- "FCT-C0F56022": {"name": "CorrectConsolidatedBarTypeForTickTypesAlgorithm", "category": "Data Consolidation", "path": "CorrectConsolidatedBarTypeForTickTypesAlgorithm.py"},
- "FCT-0AD9A342": {"name": "CoveredAndProtectiveCallStrategiesAlgorithm", "category": "General Strategy", "path": "CoveredAndProtectiveCallStrategiesAlgorithm.py"},
- "FCT-485EB46A": {"name": "CoveredAndProtectivePutStrategiesAlgorithm", "category": "General Strategy", "path": "CoveredAndProtectivePutStrategiesAlgorithm.py"},
- "FCT-B5A1B412": {"name": "CrunchDAOSignalExportDemonstrationAlgorithm", "category": "General Strategy", "path": "CrunchDAOSignalExportDemonstrationAlgorithm.py"},
- "FCT-390AE467": {"name": "CustomBenchmarkAlgorithm", "category": "Benchmark", "path": "CustomBenchmarkAlgorithm.py"},
- "FCT-F72D9CA4": {"name": "CustomBenchmarkRegressionAlgorithm", "category": "Regression Test", "path": "CustomBenchmarkRegressionAlgorithm.py"},
- "FCT-BDF6639E": {"name": "CustomBrokerageModelRegressionAlgorithm", "category": "Regression Test", "path": "CustomBrokerageModelRegressionAlgorithm.py"},
- "FCT-D2A1A24A": {"name": "CustomBrokerageSideOrderHandlingRegressionAlgorithm", "category": "Regression Test", "path": "CustomBrokerageSideOrderHandlingRegressionAlgorithm.py"},
- "FCT-335819E6": {"name": "CustomBrokerageSideOrderHandlingRegressionPartialAlgorithm", "category": "Regression Test", "path": "CustomBrokerageSideOrderHandlingRegressionPartialAlgorithm.py"},
- "FCT-DC4DC088": {"name": "CustomBuyingPowerModelAlgorithm", "category": "General Strategy", "path": "CustomBuyingPowerModelAlgorithm.py"},
- "FCT-DAAB71C9": {"name": "CustomChartingAlgorithm", "category": "General Strategy", "path": "CustomChartingAlgorithm.py"},
- "FCT-5FE7DA42": {"name": "CustomConsolidatorRegressionAlgorithm", "category": "Data Consolidation", "path": "CustomConsolidatorRegressionAlgorithm.py"},
- "FCT-23C6E607": {"name": "CustomDataBenchmarkRegressionAlgorithm", "category": "Regression Test", "path": "CustomDataBenchmarkRegressionAlgorithm.py"},
- "FCT-0D7003A5": {"name": "CustomDataBitcoinAlgorithm", "category": "Custom Data", "path": "CustomDataBitcoinAlgorithm.py"},
- "FCT-52D9893F": {"name": "CustomDataIconicTypesAddDataRegressionAlgorithm", "category": "Regression Test", "path": "CustomDataIconicTypesAddDataRegressionAlgorithm.py"},
- "FCT-0021591C": {"name": "CustomDataIndicatorExtensionsAlgorithm", "category": "Indicators", "path": "CustomDataIndicatorExtensionsAlgorithm.py"},
- "FCT-3EE829AC": {"name": "CustomDataLinkedIconicTypeAddDataCoarseSelectionRegressionAlgorithm", "category": "Regression Test", "path": "CustomDataLinkedIconicTypeAddDataCoarseSelectionRegressionAlgorithm.py"},
- "FCT-BAD0C3B3": {"name": "CustomDataLinkedIconicTypeAddDataOnSecuritiesChangedRegressionAlgorithm", "category": "Regression Test", "path": "CustomDataLinkedIconicTypeAddDataOnSecuritiesChangedRegressionAlgorithm.py"},
- "FCT-EA427FD2": {"name": "CustomDataMultiFileObjectStoreRegressionAlgorithm", "category": "Regression Test", "path": "CustomDataMultiFileObjectStoreRegressionAlgorithm.py"},
- "FCT-8C140F85": {"name": "CustomDataNIFTYAlgorithm", "category": "Custom Data", "path": "CustomDataNIFTYAlgorithm.py"},
- "FCT-675A0EC6": {"name": "CustomDataObjectStoreRegressionAlgorithm", "category": "Regression Test", "path": "CustomDataObjectStoreRegressionAlgorithm.py"},
- "FCT-9147ECE5": {"name": "CustomDataPropertiesRegressionAlgorithm", "category": "Regression Test", "path": "CustomDataPropertiesRegressionAlgorithm.py"},
- "FCT-67CFD0CD": {"name": "CustomDataRegressionAlgorithm", "category": "Regression Test", "path": "CustomDataRegressionAlgorithm.py"},
- "FCT-1A4DBA47": {"name": "CustomDataTypeHistoryAlgorithm", "category": "Custom Data", "path": "CustomDataTypeHistoryAlgorithm.py"},
- "FCT-A032E1EE": {"name": "CustomDataUniverseAlgorithm", "category": "Universe Selection", "path": "CustomDataUniverseAlgorithm.py"},
- "FCT-FC1DA597": {"name": "CustomDataUniverseRegressionAlgorithm", "category": "Universe Selection", "path": "CustomDataUniverseRegressionAlgorithm.py"},
- "FCT-72626C25": {"name": "CustomDataUniverseScheduledRegressionAlgorithm", "category": "Universe Selection", "path": "CustomDataUniverseScheduledRegressionAlgorithm.py"},
- "FCT-BEF6D76E": {"name": "CustomDataUsingMapFileRegressionAlgorithm", "category": "Regression Test", "path": "CustomDataUsingMapFileRegressionAlgorithm.py"},
- "FCT-95644B6E": {"name": "CustomDataZippedObjectStoreRegressionAlgorithm", "category": "Regression Test", "path": "CustomDataZippedObjectStoreRegressionAlgorithm.py"},
- "FCT-0B5CD58B": {"name": "CustomIndicatorAlgorithm", "category": "Indicators", "path": "CustomIndicatorAlgorithm.py"},
- "FCT-E42C0F2D": {"name": "CustomIndicatorWithExtensionAlgorithm", "category": "Indicators", "path": "CustomIndicatorWithExtensionAlgorithm.py"},
- "FCT-F06C15CD": {"name": "CustomMarginInterestRateModelAlgorithm", "category": "Margin", "path": "CustomMarginInterestRateModelAlgorithm.py"},
- "FCT-C77A7B18": {"name": "CustomModelsAlgorithm", "category": "General Strategy", "path": "CustomModelsAlgorithm.py"},
- "FCT-3555D255": {"name": "CustomModelsPEP8Algorithm", "category": "General Strategy", "path": "CustomModelsPEP8Algorithm.py"},
- "FCT-8C620280": {"name": "CustomOptionAssignmentRegressionAlgorithm", "category": "Options", "path": "CustomOptionAssignmentRegressionAlgorithm.py"},
- "FCT-A7E25D46": {"name": "CustomOptionExerciseModelRegressionAlgorithm", "category": "Options", "path": "CustomOptionExerciseModelRegressionAlgorithm.py"},
- "FCT-3E3DC670": {"name": "CustomPartialFillModelAlgorithm", "category": "General Strategy", "path": "CustomPartialFillModelAlgorithm.py"},
- "FCT-9C9C9891": {"name": "CustomPortfolioOptimizerRegressionAlgorithm", "category": "Portfolio Management", "path": "CustomPortfolioOptimizerRegressionAlgorithm.py"},
- "FCT-2F0E8AB5": {"name": "CustomSecurityDataFilterRegressionAlgorithm", "category": "Regression Test", "path": "CustomSecurityDataFilterRegressionAlgorithm.py"},
- "FCT-C15813B3": {"name": "CustomSecurityInitializerAlgorithm", "category": "General Strategy", "path": "CustomSecurityInitializerAlgorithm.py"},
- "FCT-3D3166AE": {"name": "CustomSettlementModelRegressionAlgorithm", "category": "Regression Test", "path": "CustomSettlementModelRegressionAlgorithm.py"},
- "FCT-324DD834": {"name": "CustomShortableProviderRegressionAlgorithm", "category": "Regression Test", "path": "CustomShortableProviderRegressionAlgorithm.py"},
- "FCT-CB434E24": {"name": "CustomUniverseSelectionModelRegressionAlgorithm", "category": "Universe Selection", "path": "CustomUniverseSelectionModelRegressionAlgorithm.py"},
- "FCT-57E3FCCE": {"name": "CustomVolatilityModelAlgorithm", "category": "General Strategy", "path": "CustomVolatilityModelAlgorithm.py"},
- "FCT-223472B2": {"name": "CustomWarmUpPeriodIndicatorAlgorithm", "category": "Indicators", "path": "CustomWarmUpPeriodIndicatorAlgorithm.py"},
- "FCT-DCA92403": {"name": "DailyAlgorithm", "category": "General Strategy", "path": "DailyAlgorithm.py"},
- "FCT-5DD0A982": {"name": "DataConsolidationAlgorithm", "category": "Data Consolidation", "path": "DataConsolidationAlgorithm.py"},
- "FCT-2D323EF8": {"name": "DelistingEventsAlgorithm", "category": "Corporate Actions", "path": "DelistingEventsAlgorithm.py"},
- "FCT-6513B96C": {"name": "DescendingCustomDataObjectStoreRegressionAlgorithm", "category": "Regression Test", "path": "DescendingCustomDataObjectStoreRegressionAlgorithm.py"},
- "FCT-E476428A": {"name": "DisplacedMovingAverageRibbon", "category": "General Strategy", "path": "DisplacedMovingAverageRibbon.py"},
- "FCT-3A64A758": {"name": "DividendAlgorithm", "category": "Corporate Actions", "path": "DividendAlgorithm.py"},
- "FCT-FFA7AD77": {"name": "DropboxBaseDataUniverseSelectionAlgorithm", "category": "Universe Selection", "path": "DropboxBaseDataUniverseSelectionAlgorithm.py"},
- "FCT-43A9D681": {"name": "DropboxCoarseFineAlgorithm", "category": "General Strategy", "path": "DropboxCoarseFineAlgorithm.py"},
- "FCT-C02B7DE9": {"name": "DropboxUniverseSelectionAlgorithm", "category": "Universe Selection", "path": "DropboxUniverseSelectionAlgorithm.py"},
- "FCT-D86D36A8": {"name": "DynamicSecurityDataRegressionAlgorithm", "category": "Regression Test", "path": "DynamicSecurityDataRegressionAlgorithm.py"},
- "FCT-2A9A1A33": {"name": "ETFConstituentUniverseCompositeDelistingRegressionAlgorithm", "category": "ETF", "path": "ETFConstituentUniverseCompositeDelistingRegressionAlgorithm.py"},
- "FCT-D7673A55": {"name": "ETFConstituentUniverseCompositeDelistingRegressionAlgorithmNoAddEquityETF", "category": "ETF", "path": "ETFConstituentUniverseCompositeDelistingRegressionAlgorithmNoAddEquityETF.py"},
- "FCT-9E29F41C": {"name": "ETFConstituentUniverseFilterFunctionRegressionAlgorithm", "category": "ETF", "path": "ETFConstituentUniverseFilterFunctionRegressionAlgorithm.py"},
- "FCT-D46C4922": {"name": "ETFConstituentUniverseFrameworkRegressionAlgorithm", "category": "ETF", "path": "ETFConstituentUniverseFrameworkRegressionAlgorithm.py"},
- "FCT-B97EAA99": {"name": "ETFConstituentUniverseMappedCompositeRegressionAlgorithm", "category": "ETF", "path": "ETFConstituentUniverseMappedCompositeRegressionAlgorithm.py"},
- "FCT-4249AE56": {"name": "ETFConstituentUniverseRSIAlphaModelAlgorithm", "category": "ETF", "path": "ETFConstituentUniverseRSIAlphaModelAlgorithm.py"},
- "FCT-A8E104E5": {"name": "ETFConstituentsFrameworkAlgorithm", "category": "ETF", "path": "ETFConstituentsFrameworkAlgorithm.py"},
- "FCT-A7B56E18": {"name": "ETFConstituentsFrameworkWithDifferentSelectionModelAlgorithm", "category": "ETF", "path": "ETFConstituentsFrameworkWithDifferentSelectionModelAlgorithm.py"},
- "FCT-D3112758": {"name": "ETFGlobalRotationAlgorithm", "category": "ETF", "path": "ETFGlobalRotationAlgorithm.py"},
- "FCT-A3A4BE5B": {"name": "EmaCrossAlphaModelFrameworkRegressionAlgorithm", "category": "Alpha Model", "path": "EmaCrossAlphaModelFrameworkRegressionAlgorithm.py"},
- "FCT-EE365736": {"name": "EmaCrossFuturesFrontMonthAlgorithm", "category": "Futures", "path": "EmaCrossFuturesFrontMonthAlgorithm.py"},
- "FCT-E66F50F9": {"name": "EmaCrossUniverseSelectionAlgorithm", "category": "Universe Selection", "path": "EmaCrossUniverseSelectionAlgorithm.py"},
- "FCT-AE32C215": {"name": "EmaCrossUniverseSelectionFrameworkAlgorithm", "category": "Universe Selection", "path": "EmaCrossUniverseSelectionFrameworkAlgorithm.py"},
- "FCT-62C5A2BF": {"name": "ExpiryHelperAlphaModelFrameworkAlgorithm", "category": "Alpha Model", "path": "ExpiryHelperAlphaModelFrameworkAlgorithm.py"},
- "FCT-47C778A4": {"name": "ExtendedMarketTradingRegressionAlgorithm", "category": "Regression Test", "path": "ExtendedMarketTradingRegressionAlgorithm.py"},
- "FCT-E75184B8": {"name": "FilterUniverseRegressionAlgorithm", "category": "Universe Selection", "path": "FilterUniverseRegressionAlgorithm.py"},
- "FCT-F0179E57": {"name": "FilteredIdentityAlgorithm", "category": "General Strategy", "path": "FilteredIdentityAlgorithm.py"},
- "FCT-29D656ED": {"name": "FinancialAdvisorDemoAlgorithm", "category": "General Strategy", "path": "FinancialAdvisorDemoAlgorithm.py"},
- "FCT-BB3C695A": {"name": "FineFundamentalFilteredUniverseRegressionAlgorithm", "category": "Universe Selection", "path": "FineFundamentalFilteredUniverseRegressionAlgorithm.py"},
- "FCT-0212DBCD": {"name": "ForwardDataOnlyFillModelAlgorithm", "category": "General Strategy", "path": "ForwardDataOnlyFillModelAlgorithm.py"},
- "FCT-BA248F90": {"name": "FractionalQuantityRegressionAlgorithm", "category": "Regression Test", "path": "FractionalQuantityRegressionAlgorithm.py"},
- "FCT-1C8EF029": {"name": "FuncRiskFreeRateInterestRateModelWithPythonLambda", "category": "Risk Management", "path": "FuncRiskFreeRateInterestRateModelWithPythonLambda.py"},
- "FCT-874367FD": {"name": "FundamentalCustomSelectionTimeRegressionAlgorithm", "category": "Regression Test", "path": "FundamentalCustomSelectionTimeRegressionAlgorithm.py"},
- "FCT-4A7607D6": {"name": "FundamentalRegressionAlgorithm", "category": "Regression Test", "path": "FundamentalRegressionAlgorithm.py"},
- "FCT-0A8C8781": {"name": "FundamentalUniverseSelectionAlgorithm", "category": "Universe Selection", "path": "FundamentalUniverseSelectionAlgorithm.py"},
- "FCT-19976618": {"name": "FundamentalUniverseSelectionRegressionAlgorithm", "category": "Universe Selection", "path": "FundamentalUniverseSelectionRegressionAlgorithm.py"},
- "FCT-E85797B9": {"name": "FutureContractsExtendedMarketHoursRegressionAlgorithm", "category": "Futures", "path": "FutureContractsExtendedMarketHoursRegressionAlgorithm.py"},
- "FCT-1855F876": {"name": "FutureOptionBuySellCallIntradayRegressionAlgorithm", "category": "Options", "path": "FutureOptionBuySellCallIntradayRegressionAlgorithm.py"},
- "FCT-DE2ACA2C": {"name": "FutureOptionCallITMExpiryRegressionAlgorithm", "category": "Options", "path": "FutureOptionCallITMExpiryRegressionAlgorithm.py"},
- "FCT-B4342086": {"name": "FutureOptionCallOTMExpiryRegressionAlgorithm", "category": "Options", "path": "FutureOptionCallOTMExpiryRegressionAlgorithm.py"},
- "FCT-16536530": {"name": "FutureOptionDailyRegressionAlgorithm", "category": "Options", "path": "FutureOptionDailyRegressionAlgorithm.py"},
- "FCT-BC31D77F": {"name": "FutureOptionHourlyRegressionAlgorithm", "category": "Options", "path": "FutureOptionHourlyRegressionAlgorithm.py"},
- "FCT-AA93FB6A": {"name": "FutureOptionMultipleContractsInDifferentContractMonthsWithSameUnderlyingFutureRegressionAlgorithm", "category": "Options", "path": "FutureOptionMultipleContractsInDifferentContractMonthsWithSameUnderlyingFutureRegressionAlgorithm.py"},
- "FCT-88F9D2E8": {"name": "FutureOptionPutITMExpiryRegressionAlgorithm", "category": "Options", "path": "FutureOptionPutITMExpiryRegressionAlgorithm.py"},
- "FCT-ADF65A2F": {"name": "FutureOptionPutOTMExpiryRegressionAlgorithm", "category": "Options", "path": "FutureOptionPutOTMExpiryRegressionAlgorithm.py"},
- "FCT-129041A8": {"name": "FutureOptionShortCallITMExpiryRegressionAlgorithm", "category": "Options", "path": "FutureOptionShortCallITMExpiryRegressionAlgorithm.py"},
- "FCT-68DA46AE": {"name": "FutureOptionShortCallOTMExpiryRegressionAlgorithm", "category": "Options", "path": "FutureOptionShortCallOTMExpiryRegressionAlgorithm.py"},
- "FCT-97BFC0D6": {"name": "FutureOptionShortPutITMExpiryRegressionAlgorithm", "category": "Options", "path": "FutureOptionShortPutITMExpiryRegressionAlgorithm.py"},
- "FCT-470C1BB3": {"name": "FutureOptionShortPutOTMExpiryRegressionAlgorithm", "category": "Options", "path": "FutureOptionShortPutOTMExpiryRegressionAlgorithm.py"},
- "FCT-119E482D": {"name": "FutureStopMarketOrderOnExtendedHoursRegressionAlgorithm", "category": "Futures", "path": "FutureStopMarketOrderOnExtendedHoursRegressionAlgorithm.py"},
- "FCT-2549D577": {"name": "FuturesAndFuturesOptionsExpiryTimeAndLiquidationRegressionAlgorithm", "category": "Options", "path": "FuturesAndFuturesOptionsExpiryTimeAndLiquidationRegressionAlgorithm.py"},
- "FCT-4EE8D5FD": {"name": "FuturesExtendedMarketHoursRegressionAlgorithm", "category": "Futures", "path": "FuturesExtendedMarketHoursRegressionAlgorithm.py"},
- "FCT-CA7ACD88": {"name": "FuturesMomentumAlgorithm", "category": "Futures", "path": "FuturesMomentumAlgorithm.py"},
- "FCT-7CAB8ED5": {"name": "G10CurrencySelectionModelFrameworkAlgorithm", "category": "General Strategy", "path": "G10CurrencySelectionModelFrameworkAlgorithm.py"},
- "FCT-4F55CFD9": {"name": "GetParameterRegressionAlgorithm", "category": "Regression Test", "path": "GetParameterRegressionAlgorithm.py"},
- "FCT-649F439A": {"name": "HistoricalReturnsAlphaModelFrameworkRegressionAlgorithm", "category": "Alpha Model", "path": "HistoricalReturnsAlphaModelFrameworkRegressionAlgorithm.py"},
- "FCT-4F051700": {"name": "HistoryAlgorithm", "category": "Historical Data", "path": "HistoryAlgorithm.py"},
- "FCT-17047AD3": {"name": "HistoryAuxiliaryDataRegressionAlgorithm", "category": "Regression Test", "path": "HistoryAuxiliaryDataRegressionAlgorithm.py"},
- "FCT-5077EFC4": {"name": "HistoryTickRegressionAlgorithm", "category": "Regression Test", "path": "HistoryTickRegressionAlgorithm.py"},
- "FCT-D55B4B0F": {"name": "HistoryWithCustomDataSourceRegressionAlgorithm", "category": "Regression Test", "path": "HistoryWithCustomDataSourceRegressionAlgorithm.py"},
- "FCT-52E3A84A": {"name": "HistoryWithDifferentContinuousContractDepthOffsetsRegressionAlgorithm", "category": "Regression Test", "path": "HistoryWithDifferentContinuousContractDepthOffsetsRegressionAlgorithm.py"},
- "FCT-8CB7F1CC": {"name": "HistoryWithDifferentDataMappingModeRegressionAlgorithm", "category": "Regression Test", "path": "HistoryWithDifferentDataMappingModeRegressionAlgorithm.py"},
- "FCT-25201E5E": {"name": "HistoryWithDifferentDataNormalizationModeRegressionAlgorithm", "category": "Regression Test", "path": "HistoryWithDifferentDataNormalizationModeRegressionAlgorithm.py"},
- "FCT-690AD750": {"name": "HourReverseSplitRegressionAlgorithm", "category": "Regression Test", "path": "HourReverseSplitRegressionAlgorithm.py"},
- "FCT-ADDA18D4": {"name": "HourSplitRegressionAlgorithm", "category": "Regression Test", "path": "HourSplitRegressionAlgorithm.py"},
- "FCT-5C005A63": {"name": "ImmediateExecutionModelWorksWithBinanceFeeModel", "category": "Execution Model", "path": "ImmediateExecutionModelWorksWithBinanceFeeModel.py"},
- "FCT-BDFB56F1": {"name": "InceptionDateSelectionRegressionAlgorithm", "category": "Regression Test", "path": "InceptionDateSelectionRegressionAlgorithm.py"},
- "FCT-5B348FD6": {"name": "IndexOptionBearCallSpreadAlgorithm", "category": "Options", "path": "IndexOptionBearCallSpreadAlgorithm.py"},
- "FCT-F75EB8E2": {"name": "IndexOptionBearPutSpreadAlgorithm", "category": "Options", "path": "IndexOptionBearPutSpreadAlgorithm.py"},
- "FCT-82E65BB4": {"name": "IndexOptionBullCallSpreadAlgorithm", "category": "Options", "path": "IndexOptionBullCallSpreadAlgorithm.py"},
- "FCT-1D8349B6": {"name": "IndexOptionBullPutSpreadAlgorithm", "category": "Options", "path": "IndexOptionBullPutSpreadAlgorithm.py"},
- "FCT-C204FEB8": {"name": "IndexOptionBuySellCallIntradayRegressionAlgorithm", "category": "Options", "path": "IndexOptionBuySellCallIntradayRegressionAlgorithm.py"},
- "FCT-DC3B31DA": {"name": "IndexOptionCallButterflyAlgorithm", "category": "Options", "path": "IndexOptionCallButterflyAlgorithm.py"},
- "FCT-C629FC42": {"name": "IndexOptionCallCalendarSpreadAlgorithm", "category": "Options", "path": "IndexOptionCallCalendarSpreadAlgorithm.py"},
- "FCT-EA1D90BB": {"name": "IndexOptionCallITMExpiryRegressionAlgorithm", "category": "Options", "path": "IndexOptionCallITMExpiryRegressionAlgorithm.py"},
- "FCT-32C0EE95": {"name": "IndexOptionCallITMGreeksExpiryRegressionAlgorithm", "category": "Options", "path": "IndexOptionCallITMGreeksExpiryRegressionAlgorithm.py"},
- "FCT-6AE00A81": {"name": "IndexOptionCallOTMExpiryRegressionAlgorithm", "category": "Options", "path": "IndexOptionCallOTMExpiryRegressionAlgorithm.py"},
- "FCT-F859111A": {"name": "IndexOptionChainApisConsistencyRegressionAlgorithm", "category": "Options", "path": "IndexOptionChainApisConsistencyRegressionAlgorithm.py"},
- "FCT-F5FE9B32": {"name": "IndexOptionIronCondorAlgorithm", "category": "Options", "path": "IndexOptionIronCondorAlgorithm.py"},
- "FCT-02F5AEAE": {"name": "IndexOptionModelsConsistencyRegressionAlgorithm", "category": "Options", "path": "IndexOptionModelsConsistencyRegressionAlgorithm.py"},
- "FCT-BFEF2627": {"name": "IndexOptionPutButterflyAlgorithm", "category": "Options", "path": "IndexOptionPutButterflyAlgorithm.py"},
- "FCT-E0220F96": {"name": "IndexOptionPutCalendarSpreadAlgorithm", "category": "Options", "path": "IndexOptionPutCalendarSpreadAlgorithm.py"},
- "FCT-48BF5359": {"name": "IndexOptionPutITMExpiryRegressionAlgorithm", "category": "Options", "path": "IndexOptionPutITMExpiryRegressionAlgorithm.py"},
- "FCT-4666C54E": {"name": "IndexOptionPutOTMExpiryRegressionAlgorithm", "category": "Options", "path": "IndexOptionPutOTMExpiryRegressionAlgorithm.py"},
- "FCT-300B9FC2": {"name": "IndexOptionShortCallITMExpiryRegressionAlgorithm", "category": "Options", "path": "IndexOptionShortCallITMExpiryRegressionAlgorithm.py"},
- "FCT-57548DAA": {"name": "IndexOptionShortCallOTMExpiryRegressionAlgorithm", "category": "Options", "path": "IndexOptionShortCallOTMExpiryRegressionAlgorithm.py"},
- "FCT-D0643727": {"name": "IndexOptionShortPutITMExpiryRegressionAlgorithm", "category": "Options", "path": "IndexOptionShortPutITMExpiryRegressionAlgorithm.py"},
- "FCT-905BC971": {"name": "IndexOptionShortPutOTMExpiryRegressionAlgorithm", "category": "Options", "path": "IndexOptionShortPutOTMExpiryRegressionAlgorithm.py"},
- "FCT-EB8CE077": {"name": "IndiaDataRegressionAlgorithm", "category": "Regression Test", "path": "IndiaDataRegressionAlgorithm.py"},
- "FCT-31D18328": {"name": "IndicatorExtensionsSMAWithCustomIndicatorsRegressionAlgorithm", "category": "Indicators", "path": "IndicatorExtensionsSMAWithCustomIndicatorsRegressionAlgorithm.py"},
- "FCT-2BC353A9": {"name": "IndicatorHistoryAlgorithm", "category": "Indicators", "path": "IndicatorHistoryAlgorithm.py"},
- "FCT-B3C67AEA": {"name": "IndicatorHistoryRegressionAlgorithm", "category": "Indicators", "path": "IndicatorHistoryRegressionAlgorithm.py"},
- "FCT-9EF0798B": {"name": "IndicatorSelectorsWorkWithDifferentOptions", "category": "Options", "path": "IndicatorSelectorsWorkWithDifferentOptions.py"},
- "FCT-71C08CCA": {"name": "IndicatorSuiteAlgorithm", "category": "Indicators", "path": "IndicatorSuiteAlgorithm.py"},
- "FCT-935D3B5D": {"name": "IndicatorWarmupAlgorithm", "category": "Indicators", "path": "IndicatorWarmupAlgorithm.py"},
- "FCT-B8EB6886": {"name": "IndicatorWithRenkoBarsRegressionAlgorithm", "category": "Indicators", "path": "IndicatorWithRenkoBarsRegressionAlgorithm.py"},
- "FCT-77C48AE3": {"name": "IndustryStandardSecurityIdentifiersRegressionAlgorithm", "category": "Regression Test", "path": "IndustryStandardSecurityIdentifiersRegressionAlgorithm.py"},
- "FCT-E8E10658": {"name": "InsightScoringRegressionAlgorithm", "category": "Regression Test", "path": "InsightScoringRegressionAlgorithm.py"},
- "FCT-15D6B08D": {"name": "InsightTagAlphaRegressionAlgorithm", "category": "Alpha Model", "path": "InsightTagAlphaRegressionAlgorithm.py"},
- "FCT-955EB562": {"name": "InsightWeightingFrameworkAlgorithm", "category": "General Strategy", "path": "InsightWeightingFrameworkAlgorithm.py"},
- "FCT-FD19D095": {"name": "IronCondorStrategyAlgorithm", "category": "General Strategy", "path": "IronCondorStrategyAlgorithm.py"},
- "FCT-8863BE2D": {"name": "KerasNeuralNetworkAlgorithm", "category": "Machine Learning", "path": "KerasNeuralNetworkAlgorithm.py"},
- "FCT-C37858CB": {"name": "LimitFillRegressionAlgorithm", "category": "Regression Test", "path": "LimitFillRegressionAlgorithm.py"},
- "FCT-78D0ECA0": {"name": "LimitIfTouchedRegressionAlgorithm", "category": "Regression Test", "path": "LimitIfTouchedRegressionAlgorithm.py"},
- "FCT-1E792B32": {"name": "LiquidETFUniverseFrameworkAlgorithm", "category": "ETF", "path": "LiquidETFUniverseFrameworkAlgorithm.py"},
- "FCT-C5F5B3E0": {"name": "LiveFeaturesAlgorithm", "category": "General Strategy", "path": "LiveFeaturesAlgorithm.py"},
- "FCT-EC39F086": {"name": "LongAndShortButterflyCallStrategiesAlgorithm", "category": "General Strategy", "path": "LongAndShortButterflyCallStrategiesAlgorithm.py"},
- "FCT-812F2B68": {"name": "LongAndShortButterflyPutStrategiesAlgorithm", "category": "General Strategy", "path": "LongAndShortButterflyPutStrategiesAlgorithm.py"},
- "FCT-8F4CCF9F": {"name": "LongAndShortCallCalendarSpreadStrategiesAlgorithm", "category": "General Strategy", "path": "LongAndShortCallCalendarSpreadStrategiesAlgorithm.py"},
- "FCT-27A6F4AF": {"name": "LongAndShortPutCalendarSpreadStrategiesAlgorithm", "category": "General Strategy", "path": "LongAndShortPutCalendarSpreadStrategiesAlgorithm.py"},
- "FCT-9BF2DDCB": {"name": "LongAndShortStraddleStrategiesAlgorithm", "category": "General Strategy", "path": "LongAndShortStraddleStrategiesAlgorithm.py"},
- "FCT-73CA6D31": {"name": "LongAndShortStrangleStrategiesAlgorithm", "category": "General Strategy", "path": "LongAndShortStrangleStrategiesAlgorithm.py"},
- "FCT-BEFEB617": {"name": "LongOnlyAlphaStreamAlgorithm", "category": "Alpha Model", "path": "LongOnlyAlphaStreamAlgorithm.py"},
- "FCT-F328066F": {"name": "MACDTrendAlgorithm", "category": "Momentum", "path": "MACDTrendAlgorithm.py"},
- "FCT-EABA6096": {"name": "MacdAlphaModelFrameworkRegressionAlgorithm", "category": "Alpha Model", "path": "MacdAlphaModelFrameworkRegressionAlgorithm.py"},
- "FCT-C0569D9C": {"name": "ManuallyRemovedConsolidatorsAlgorithm", "category": "Data Consolidation", "path": "ManuallyRemovedConsolidatorsAlgorithm.py"},
- "FCT-A4B98519": {"name": "ManuallySetMarketHoursAndSymbolPropertiesDatabaseEntriesAlgorithm", "category": "General Strategy", "path": "ManuallySetMarketHoursAndSymbolPropertiesDatabaseEntriesAlgorithm.py"},
- "FCT-FB2B7755": {"name": "MarginCallEventsAlgorithm", "category": "Margin", "path": "MarginCallEventsAlgorithm.py"},
- "FCT-26E2B07B": {"name": "MarketImpactSlippageModelRegressionAlgorithm", "category": "Regression Test", "path": "MarketImpactSlippageModelRegressionAlgorithm.py"},
- "FCT-F8893107": {"name": "MarketOnCloseOrderBufferExtendedMarketHoursRegressionAlgorithm", "category": "Regression Test", "path": "MarketOnCloseOrderBufferExtendedMarketHoursRegressionAlgorithm.py"},
- "FCT-74AD11AC": {"name": "MarketOnCloseOrderBufferRegressionAlgorithm", "category": "Regression Test", "path": "MarketOnCloseOrderBufferRegressionAlgorithm.py"},
- "FCT-A5E1134A": {"name": "MarketOnOpenOnCloseAlgorithm", "category": "General Strategy", "path": "MarketOnOpenOnCloseAlgorithm.py"},
- "FCT-791ECD54": {"name": "MaximumDrawdownPercentPerSecurityFrameworkRegressionAlgorithm", "category": "Regression Test", "path": "MaximumDrawdownPercentPerSecurityFrameworkRegressionAlgorithm.py"},
- "FCT-7A279BE5": {"name": "MaximumDrawdownPercentPortfolioFrameworkRegressionAlgorithm", "category": "Portfolio Management", "path": "MaximumDrawdownPercentPortfolioFrameworkRegressionAlgorithm.py"},
- "FCT-C143732F": {"name": "MaximumSectorExposureRiskManagementModelFrameworkRegressionAlgorithm", "category": "Risk Management", "path": "MaximumSectorExposureRiskManagementModelFrameworkRegressionAlgorithm.py"},
- "FCT-7E35ADAA": {"name": "MaximumUnrealizedProfitPercentPerSecurityFrameworkRegressionAlgorithm", "category": "Regression Test", "path": "MaximumUnrealizedProfitPercentPerSecurityFrameworkRegressionAlgorithm.py"},
- "FCT-98AE653C": {"name": "MeanReversionPortfolioAlgorithm", "category": "Portfolio Management", "path": "MeanReversionPortfolioAlgorithm.py"},
- "FCT-C42B3790": {"name": "MeanVarianceOptimizationFrameworkAlgorithm", "category": "General Strategy", "path": "MeanVarianceOptimizationFrameworkAlgorithm.py"},
- "FCT-B8F7654B": {"name": "MovingAverageCrossAlgorithm", "category": "General Strategy", "path": "MovingAverageCrossAlgorithm.py"},
- "FCT-CFDE4C40": {"name": "MultipleSymbolConsolidationAlgorithm", "category": "Data Consolidation", "path": "MultipleSymbolConsolidationAlgorithm.py"},
- "FCT-D2180B48": {"name": "NLTKSentimentTradingAlgorithm", "category": "General Strategy", "path": "NLTKSentimentTradingAlgorithm.py"},
- "FCT-AE6C825A": {"name": "NakedCallStrategyAlgorithm", "category": "General Strategy", "path": "NakedCallStrategyAlgorithm.py"},
- "FCT-82AD115E": {"name": "NakedPutStrategyAlgorithm", "category": "General Strategy", "path": "NakedPutStrategyAlgorithm.py"},
- "FCT-94DBB773": {"name": "NamedArgumentsRegression", "category": "Regression Test", "path": "NamedArgumentsRegression.py"},
- "FCT-994B4750": {"name": "NoUniverseSelectorRegressionAlgorithm", "category": "Universe Selection", "path": "NoUniverseSelectorRegressionAlgorithm.py"},
- "FCT-7F8D7895": {"name": "NullBuyingPowerOptionBullCallSpreadAlgorithm", "category": "Options", "path": "NullBuyingPowerOptionBullCallSpreadAlgorithm.py"},
- "FCT-B9E54A12": {"name": "NullMarginMultipleOrdersRegressionAlgorithm", "category": "Regression Test", "path": "NullMarginMultipleOrdersRegressionAlgorithm.py"},
- "FCT-16C48497": {"name": "NullOptionAssignmentRegressionAlgorithm", "category": "Options", "path": "NullOptionAssignmentRegressionAlgorithm.py"},
- "FCT-F5080AAC": {"name": "NumeraiSignalExportDemonstrationAlgorithm", "category": "General Strategy", "path": "NumeraiSignalExportDemonstrationAlgorithm.py"},
- "FCT-6A2A6B6A": {"name": "ObjectStoreExampleAlgorithm", "category": "General Strategy", "path": "ObjectStoreExampleAlgorithm.py"},
- "FCT-5B1C96E9": {"name": "OnEndOfDayRegressionAlgorithm", "category": "Regression Test", "path": "OnEndOfDayRegressionAlgorithm.py"},
- "FCT-7E0FD2EB": {"name": "OnWarmupFinishedNoWarmup", "category": "Warmup", "path": "OnWarmupFinishedNoWarmup.py"},
- "FCT-BA4498F3": {"name": "OnWarmupFinishedRegressionAlgorithm", "category": "Regression Test", "path": "OnWarmupFinishedRegressionAlgorithm.py"},
- "FCT-370B9F0E": {"name": "OpenInterestFuturesRegressionAlgorithm", "category": "Futures", "path": "OpenInterestFuturesRegressionAlgorithm.py"},
- "FCT-A5BE1849": {"name": "OptionChainApisConsistencyRegressionAlgorithm", "category": "Options", "path": "OptionChainApisConsistencyRegressionAlgorithm.py"},
- "FCT-98E14661": {"name": "OptionChainConsistencyRegressionAlgorithm", "category": "Options", "path": "OptionChainConsistencyRegressionAlgorithm.py"},
- "FCT-A05E4856": {"name": "OptionChainFullDataRegressionAlgorithm", "category": "Options", "path": "OptionChainFullDataRegressionAlgorithm.py"},
- "FCT-662DC1F1": {"name": "OptionChainProviderAlgorithm", "category": "Options", "path": "OptionChainProviderAlgorithm.py"},
- "FCT-1D2112EA": {"name": "OptionChainedUniverseSelectionModelRegressionAlgorithm", "category": "Options", "path": "OptionChainedUniverseSelectionModelRegressionAlgorithm.py"},
- "FCT-90DAF80B": {"name": "OptionChainsMultipleFullDataRegressionAlgorithm", "category": "Options", "path": "OptionChainsMultipleFullDataRegressionAlgorithm.py"},
- "FCT-4E7CF48A": {"name": "OptionDataNullReferenceRegressionAlgorithm", "category": "Options", "path": "OptionDataNullReferenceRegressionAlgorithm.py"},
- "FCT-A9A9EB72": {"name": "OptionExerciseAssignRegressionAlgorithm", "category": "Options", "path": "OptionExerciseAssignRegressionAlgorithm.py"},
- "FCT-CFC8C48B": {"name": "OptionIndicatorsMirrorContractsRegressionAlgorithm", "category": "Options", "path": "OptionIndicatorsMirrorContractsRegressionAlgorithm.py"},
- "FCT-707335FB": {"name": "OptionIndicatorsRegressionAlgorithm", "category": "Options", "path": "OptionIndicatorsRegressionAlgorithm.py"},
- "FCT-62B73DDD": {"name": "OptionModelsConsistencyRegressionAlgorithm", "category": "Options", "path": "OptionModelsConsistencyRegressionAlgorithm.py"},
- "FCT-0FFCB469": {"name": "OptionOpenInterestRegressionAlgorithm", "category": "Options", "path": "OptionOpenInterestRegressionAlgorithm.py"},
- "FCT-9520559C": {"name": "OptionPriceModelForOptionStylesBaseRegressionAlgorithm", "category": "Options", "path": "OptionPriceModelForOptionStylesBaseRegressionAlgorithm.py"},
- "FCT-9884C10F": {"name": "OptionPriceModelForSupportedAmericanOptionRegressionAlgorithm", "category": "Options", "path": "OptionPriceModelForSupportedAmericanOptionRegressionAlgorithm.py"},
- "FCT-B34DCB29": {"name": "OptionPriceModelForSupportedAmericanOptionTimeSpanWarmupRegressionAlgorithm", "category": "Options", "path": "OptionPriceModelForSupportedAmericanOptionTimeSpanWarmupRegressionAlgorithm.py"},
- "FCT-B6D1CB41": {"name": "OptionPriceModelForSupportedEuropeanOptionRegressionAlgorithm", "category": "Options", "path": "OptionPriceModelForSupportedEuropeanOptionRegressionAlgorithm.py"},
- "FCT-6812E1E8": {"name": "OptionPriceModelForSupportedEuropeanOptionTimeSpanWarmupRegressionAlgorithm", "category": "Options", "path": "OptionPriceModelForSupportedEuropeanOptionTimeSpanWarmupRegressionAlgorithm.py"},
- "FCT-03E734EA": {"name": "OptionPriceModelForUnsupportedAmericanOptionRegressionAlgorithm", "category": "Options", "path": "OptionPriceModelForUnsupportedAmericanOptionRegressionAlgorithm.py"},
- "FCT-850F1B89": {"name": "OptionPriceModelForUnsupportedAmericanOptionTimeSpanWarmupRegressionAlgorithm", "category": "Options", "path": "OptionPriceModelForUnsupportedAmericanOptionTimeSpanWarmupRegressionAlgorithm.py"},
- "FCT-C99DFC04": {"name": "OptionPriceModelForUnsupportedEuropeanOptionRegressionAlgorithm", "category": "Options", "path": "OptionPriceModelForUnsupportedEuropeanOptionRegressionAlgorithm.py"},
- "FCT-6FBD513A": {"name": "OptionPriceModelForUnsupportedEuropeanOptionTimeSpanWarmupRegressionAlgorithm", "category": "Options", "path": "OptionPriceModelForUnsupportedEuropeanOptionTimeSpanWarmupRegressionAlgorithm.py"},
- "FCT-8E5F0BE5": {"name": "OptionRenameRegressionAlgorithm", "category": "Options", "path": "OptionRenameRegressionAlgorithm.py"},
- "FCT-D07A1F27": {"name": "OptionSplitRegressionAlgorithm", "category": "Options", "path": "OptionSplitRegressionAlgorithm.py"},
- "FCT-CB64E8E9": {"name": "OptionStrategyFactoryMethodsBaseAlgorithm", "category": "Options", "path": "OptionStrategyFactoryMethodsBaseAlgorithm.py"},
- "FCT-876722D3": {"name": "OptionUniverseFilterGreeksRegressionAlgorithm", "category": "Options", "path": "OptionUniverseFilterGreeksRegressionAlgorithm.py"},
- "FCT-AED01B14": {"name": "OptionUniverseFilterGreeksShortcutsRegressionAlgorithm", "category": "Options", "path": "OptionUniverseFilterGreeksShortcutsRegressionAlgorithm.py"},
- "FCT-62274EA6": {"name": "OptionUniverseFilterOptionsDataRegressionAlgorithm", "category": "Options", "path": "OptionUniverseFilterOptionsDataRegressionAlgorithm.py"},
- "FCT-61D659F8": {"name": "OptionUniverseHistoryRegressionAlgorithm", "category": "Options", "path": "OptionUniverseHistoryRegressionAlgorithm.py"},
- "FCT-D1943028": {"name": "OrderTicketAssignmentDemoAlgorithm", "category": "General Strategy", "path": "OrderTicketAssignmentDemoAlgorithm.py"},
- "FCT-4AD7FFC0": {"name": "OrderTicketDemoAlgorithm", "category": "General Strategy", "path": "OrderTicketDemoAlgorithm.py"},
- "FCT-73AEBCB1": {"name": "PEP8StyleBasicAlgorithm", "category": "General Strategy", "path": "PEP8StyleBasicAlgorithm.py"},
- "FCT-69B21AF4": {"name": "PandasDataFrameFromMultipleTickTypeTickHistoryRegressionAlgorithm", "category": "Regression Test", "path": "PandasDataFrameFromMultipleTickTypeTickHistoryRegressionAlgorithm.py"},
- "FCT-C16FBA05": {"name": "PandasDataFrameHistoryAlgorithm", "category": "Historical Data", "path": "PandasDataFrameHistoryAlgorithm.py"},
- "FCT-3D4D4FC7": {"name": "ParameterizedAlgorithm", "category": "General Strategy", "path": "ParameterizedAlgorithm.py"},
- "FCT-6689DBF5": {"name": "PearsonCorrelationPairsTradingAlphaModelFrameworkAlgorithm", "category": "Alpha Model", "path": "PearsonCorrelationPairsTradingAlphaModelFrameworkAlgorithm.py"},
- "FCT-B9E58D2A": {"name": "PeriodBasedHistoryRequestNotAllowedWithTickResolutionRegressionAlgorithm", "category": "Regression Test", "path": "PeriodBasedHistoryRequestNotAllowedWithTickResolutionRegressionAlgorithm.py"},
- "FCT-B4A28E80": {"name": "PortfolioRebalanceOnCustomFuncRegressionAlgorithm", "category": "Portfolio Management", "path": "PortfolioRebalanceOnCustomFuncRegressionAlgorithm.py"},
- "FCT-53259B36": {"name": "PortfolioRebalanceOnDateRulesRegressionAlgorithm", "category": "Portfolio Management", "path": "PortfolioRebalanceOnDateRulesRegressionAlgorithm.py"},
- "FCT-1D170EBB": {"name": "PortfolioTargetTagsRegressionAlgorithm", "category": "Portfolio Management", "path": "PortfolioTargetTagsRegressionAlgorithm.py"},
- "FCT-3E91D425": {"name": "PythonDictionaryFeatureRegressionAlgorithm", "category": "Regression Test", "path": "PythonDictionaryFeatureRegressionAlgorithm.py"},
- "FCT-3BE1BA87": {"name": "PytorchNeuralNetworkAlgorithm", "category": "Machine Learning", "path": "PytorchNeuralNetworkAlgorithm.py"},
- "FCT-0CB9D7FA": {"name": "QuitAfterInitializationRegressionAlgorithm", "category": "Regression Test", "path": "QuitAfterInitializationRegressionAlgorithm.py"},
- "FCT-87512128": {"name": "QuitInInitializationRegressionAlgorithm", "category": "Regression Test", "path": "QuitInInitializationRegressionAlgorithm.py"},
- "FCT-052CED9D": {"name": "RangeConsolidatorAlgorithm", "category": "Data Consolidation", "path": "RangeConsolidatorAlgorithm.py"},
- "FCT-0761902F": {"name": "RangeConsolidatorWithTickAlgorithm", "category": "Data Consolidation", "path": "RangeConsolidatorWithTickAlgorithm.py"},
- "FCT-4C4ACA6D": {"name": "RawDataRegressionAlgorithm", "category": "Regression Test", "path": "RawDataRegressionAlgorithm.py"},
- "FCT-8426823A": {"name": "RawPricesCoarseUniverseAlgorithm", "category": "Universe Selection", "path": "RawPricesCoarseUniverseAlgorithm.py"},
- "FCT-EEE07C98": {"name": "RawPricesUniverseRegressionAlgorithm", "category": "Universe Selection", "path": "RawPricesUniverseRegressionAlgorithm.py"},
- "FCT-0D15187F": {"name": "RegisterIndicatorRegressionAlgorithm", "category": "Indicators", "path": "RegisterIndicatorRegressionAlgorithm.py"},
- "FCT-D350E387": {"name": "RegressionAlgorithm", "category": "Regression Test", "path": "RegressionAlgorithm.py"},
- "FCT-CB76FD5F": {"name": "RegressionChannelAlgorithm", "category": "Regression Test", "path": "RegressionChannelAlgorithm.py"},
- "FCT-4F8A816B": {"name": "RiskParityPortfolioAlgorithm", "category": "Risk Management", "path": "RiskParityPortfolioAlgorithm.py"},
- "FCT-5A71E57F": {"name": "RollingWindowAlgorithm", "category": "General Strategy", "path": "RollingWindowAlgorithm.py"},
- "FCT-2CBD0408": {"name": "RsiAlphaModelFrameworkRegressionAlgorithm", "category": "Alpha Model", "path": "RsiAlphaModelFrameworkRegressionAlgorithm.py"},
- "FCT-9781F28A": {"name": "ScheduledEventsAlgorithm", "category": "Scheduled Events", "path": "ScheduledEventsAlgorithm.py"},
- "FCT-BC10DFCE": {"name": "ScheduledQueuingAlgorithm", "category": "Scheduled Events", "path": "ScheduledQueuingAlgorithm.py"},
- "FCT-AE6D38CF": {"name": "ScheduledUniverseRegressionAlgorithm", "category": "Universe Selection", "path": "ScheduledUniverseRegressionAlgorithm.py"},
- "FCT-3F154B00": {"name": "ScheduledUniverseSelectionModelRegressionAlgorithm", "category": "Universe Selection", "path": "ScheduledUniverseSelectionModelRegressionAlgorithm.py"},
- "FCT-1244BB8B": {"name": "ScikitLearnLinearRegressionAlgorithm", "category": "Regression Test", "path": "ScikitLearnLinearRegressionAlgorithm.py"},
- "FCT-9159A849": {"name": "SectorExposureRiskFrameworkAlgorithm", "category": "Risk Management", "path": "SectorExposureRiskFrameworkAlgorithm.py"},
- "FCT-F578C144": {"name": "SectorWeightingFrameworkAlgorithm", "category": "General Strategy", "path": "SectorWeightingFrameworkAlgorithm.py"},
- "FCT-B0B2E65B": {"name": "SecurityCustomPropertiesAlgorithm", "category": "General Strategy", "path": "SecurityCustomPropertiesAlgorithm.py"},
- "FCT-B2BE2584": {"name": "SecurityDynamicPropertyPythonClassAlgorithm", "category": "General Strategy", "path": "SecurityDynamicPropertyPythonClassAlgorithm.py"},
- "FCT-79957FB5": {"name": "SecuritySeederRegressionAlgorithm", "category": "Regression Test", "path": "SecuritySeederRegressionAlgorithm.py"},
- "FCT-BCEB1931": {"name": "SelectUniverseSymbolsFromIDRegressionAlgorithm", "category": "Universe Selection", "path": "SelectUniverseSymbolsFromIDRegressionAlgorithm.py"},
- "FCT-86D91C89": {"name": "SetCustomSettlementModelRegressionAlgorithm", "category": "Regression Test", "path": "SetCustomSettlementModelRegressionAlgorithm.py"},
- "FCT-D64ED04F": {"name": "SetEquityDataNormalizationModeOnAddEquity", "category": "General Strategy", "path": "SetEquityDataNormalizationModeOnAddEquity.py"},
- "FCT-36FF2819": {"name": "SetHoldingsLiquidateExistingHoldingsMultipleTargetsRegressionAlgorithm", "category": "Regression Test", "path": "SetHoldingsLiquidateExistingHoldingsMultipleTargetsRegressionAlgorithm.py"},
- "FCT-5A449593": {"name": "SetHoldingsMultipleTargetsRegressionAlgorithm", "category": "Regression Test", "path": "SetHoldingsMultipleTargetsRegressionAlgorithm.py"},
- "FCT-58C330FF": {"name": "SetHoldingsRegressionAlgorithm", "category": "Regression Test", "path": "SetHoldingsRegressionAlgorithm.py"},
- "FCT-EFDED6A6": {"name": "ShortableProviderOrdersRejectedRegressionAlgorithm", "category": "Regression Test", "path": "ShortableProviderOrdersRejectedRegressionAlgorithm.py"},
- "FCT-198E83AF": {"name": "SliceGetByTypeRegressionAlgorithm", "category": "Regression Test", "path": "SliceGetByTypeRegressionAlgorithm.py"},
- "FCT-9D3D6D8F": {"name": "SmaCrossUniverseSelectionAlgorithm", "category": "Universe Selection", "path": "SmaCrossUniverseSelectionAlgorithm.py"},
- "FCT-E4FEA7D1": {"name": "SpreadExecutionModelRegressionAlgorithm", "category": "Execution Model", "path": "SpreadExecutionModelRegressionAlgorithm.py"},
- "FCT-5C2FCFA1": {"name": "StableCoinsRegressionAlgorithm", "category": "Regression Test", "path": "StableCoinsRegressionAlgorithm.py"},
- "FCT-C7F868BA": {"name": "StandardDeviationExecutionModelRegressionAlgorithm", "category": "Execution Model", "path": "StandardDeviationExecutionModelRegressionAlgorithm.py"},
- "FCT-99B5F510": {"name": "StatisticsResultsAlgorithm", "category": "General Strategy", "path": "StatisticsResultsAlgorithm.py"},
- "FCT-1A300907": {"name": "StochasticIndicatorWarmsUpProperlyRegressionAlgorithm", "category": "Indicators", "path": "StochasticIndicatorWarmsUpProperlyRegressionAlgorithm.py"},
- "FCT-58C9B30E": {"name": "StopLimitOrderRegressionAlgorithm", "category": "Regression Test", "path": "StopLimitOrderRegressionAlgorithm.py"},
- "FCT-8FAFCC5D": {"name": "StringToSymbolImplicitConversionRegressionAlgorithm", "category": "Regression Test", "path": "StringToSymbolImplicitConversionRegressionAlgorithm.py"},
- "FCT-D0F1B141": {"name": "TalibIndicatorsAlgorithm", "category": "Indicators", "path": "TalibIndicatorsAlgorithm.py"},
- "FCT-42FC8E69": {"name": "TensorFlowNeuralNetworkAlgorithm", "category": "Machine Learning", "path": "TensorFlowNeuralNetworkAlgorithm.py"},
- "FCT-84B15249": {"name": "TickDataFilteringAlgorithm", "category": "General Strategy", "path": "TickDataFilteringAlgorithm.py"},
- "FCT-824A47D1": {"name": "TickHistoryRequestWithoutTickSubscriptionRegressionAlgorithm", "category": "Regression Test", "path": "TickHistoryRequestWithoutTickSubscriptionRegressionAlgorithm.py"},
- "FCT-B0BD73CA": {"name": "TiingoPriceAlgorithm", "category": "General Strategy", "path": "TiingoPriceAlgorithm.py"},
- "FCT-F8E8016B": {"name": "TimeInForceAlgorithm", "category": "General Strategy", "path": "TimeInForceAlgorithm.py"},
- "FCT-76B63DA7": {"name": "TrailingStopOrderRegressionAlgorithm", "category": "Regression Test", "path": "TrailingStopOrderRegressionAlgorithm.py"},
- "FCT-DD7ECCB4": {"name": "TrailingStopRiskFrameworkRegressionAlgorithm", "category": "Risk Management", "path": "TrailingStopRiskFrameworkRegressionAlgorithm.py"},
- "FCT-4F56A3E5": {"name": "TrainingExampleAlgorithm", "category": "General Strategy", "path": "TrainingExampleAlgorithm.py"},
- "FCT-95DFEFEB": {"name": "TrainingInitializeRegressionAlgorithm", "category": "Regression Test", "path": "TrainingInitializeRegressionAlgorithm.py"},
- "FCT-FED4E182": {"name": "TwoLegCurrencyConversionRegressionAlgorithm", "category": "Regression Test", "path": "TwoLegCurrencyConversionRegressionAlgorithm.py"},
- "FCT-953A6967": {"name": "UniverseOnlyRegressionAlgorithm", "category": "Universe Selection", "path": "UniverseOnlyRegressionAlgorithm.py"},
- "FCT-BAF35694": {"name": "UniverseSelectedRegressionAlgorithm", "category": "Universe Selection", "path": "UniverseSelectedRegressionAlgorithm.py"},
- "FCT-DBD4926F": {"name": "UniverseSelectionDefinitionsAlgorithm", "category": "Universe Selection", "path": "UniverseSelectionDefinitionsAlgorithm.py"},
- "FCT-E51F70E4": {"name": "UniverseSelectionRegressionAlgorithm", "category": "Universe Selection", "path": "UniverseSelectionRegressionAlgorithm.py"},
- "FCT-91035E43": {"name": "UniverseUnchangedRegressionAlgorithm", "category": "Universe Selection", "path": "UniverseUnchangedRegressionAlgorithm.py"},
- "FCT-D8849489": {"name": "UnregisterIndicatorRegressionAlgorithm", "category": "Indicators", "path": "UnregisterIndicatorRegressionAlgorithm.py"},
- "FCT-BFC09E5D": {"name": "UpdateOrderRegressionAlgorithm", "category": "Regression Test", "path": "UpdateOrderRegressionAlgorithm.py"},
- "FCT-90E557F4": {"name": "UserDefinedUniverseAlgorithm", "category": "Universe Selection", "path": "UserDefinedUniverseAlgorithm.py"},
- "FCT-253853F6": {"name": "VolumeRenkoConsolidatorAlgorithm", "category": "Data Consolidation", "path": "VolumeRenkoConsolidatorAlgorithm.py"},
- "FCT-8D857005": {"name": "VolumeShareSlippageModelAlgorithm", "category": "General Strategy", "path": "VolumeShareSlippageModelAlgorithm.py"},
- "FCT-2D03F945": {"name": "VolumeWeightedAveragePriceExecutionModelRegressionAlgorithm", "category": "Execution Model", "path": "VolumeWeightedAveragePriceExecutionModelRegressionAlgorithm.py"},
- "FCT-DB342081": {"name": "WarmupAlgorithm", "category": "Warmup", "path": "WarmupAlgorithm.py"},
- "FCT-E048C42D": {"name": "WarmupHistoryAlgorithm", "category": "Warmup", "path": "WarmupHistoryAlgorithm.py"},
- "FCT-161A4DE8": {"name": "WeeklyUniverseSelectionRegressionAlgorithm", "category": "Universe Selection", "path": "WeeklyUniverseSelectionRegressionAlgorithm.py"},
- "FCT-F69688F5": {"name": "ZeroedBenchmarkRegressionAlgorithm", "category": "Regression Test", "path": "ZeroedBenchmarkRegressionAlgorithm.py"},
- "FCT-FAD58DE7": {"name": "main", "category": "General Strategy", "path": "main.py"},
- "FCT-70CBDC3D": {"name": "ContingentClaimsAnalysisDefaultPredictionAlpha", "category": "Alpha Model", "path": "alphas/ContingentClaimsAnalysisDefaultPredictionAlpha.py"},
- "FCT-9D7FFCA4": {"name": "GasAndCrudeOilEnergyCorrelationAlpha", "category": "Alpha Model", "path": "alphas/GasAndCrudeOilEnergyCorrelationAlpha.py"},
- "FCT-C3B2CF90": {"name": "GlobalEquityMeanReversionIBSAlpha", "category": "Alpha Model", "path": "alphas/GlobalEquityMeanReversionIBSAlpha.py"},
- "FCT-46661FE6": {"name": "GreenblattMagicFormulaAlpha", "category": "Alpha Model", "path": "alphas/GreenblattMagicFormulaAlpha.py"},
- "FCT-5596A325": {"name": "IntradayReversalCurrencyMarketsAlpha", "category": "Alpha Model", "path": "alphas/IntradayReversalCurrencyMarketsAlpha.py"},
- "FCT-EAEEE69C": {"name": "MeanReversionLunchBreakAlpha", "category": "Alpha Model", "path": "alphas/MeanReversionLunchBreakAlpha.py"},
- "FCT-B86663BE": {"name": "MortgageRateVolatilityAlpha", "category": "Alpha Model", "path": "alphas/MortgageRateVolatilityAlpha.py"},
- "FCT-899805AE": {"name": "PriceGapMeanReversionAlpha", "category": "Alpha Model", "path": "alphas/PriceGapMeanReversionAlpha.py"},
- "FCT-41404465": {"name": "RebalancingLeveragedETFAlpha", "category": "Alpha Model", "path": "alphas/RebalancingLeveragedETFAlpha.py"},
- "FCT-B44500AA": {"name": "ShareClassMeanReversionAlpha", "category": "Alpha Model", "path": "alphas/ShareClassMeanReversionAlpha.py"},
- "FCT-EEAA6B87": {"name": "SykesShortMicroCapAlpha", "category": "Alpha Model", "path": "alphas/SykesShortMicroCapAlpha.py"},
- "FCT-217A291D": {"name": "TriangleExchangeRateArbitrageAlpha", "category": "Alpha Model", "path": "alphas/TriangleExchangeRateArbitrageAlpha.py"},
- "FCT-A6C1E2B9": {"name": "TripleLeverageETFPairVolatilityDecayAlpha", "category": "Alpha Model", "path": "alphas/TripleLeverageETFPairVolatilityDecayAlpha.py"},
- "FCT-7DFAE1BB": {"name": "VIXDualThrustAlpha", "category": "Alpha Model", "path": "alphas/VIXDualThrustAlpha.py"},
- "FCT-B103DBA0": {"name": "BasicTemplateBenchmark", "category": "Benchmark", "path": "benchmarks/BasicTemplateBenchmark.py"},
- "FCT-5B90E12B": {"name": "CoarseFineUniverseSelectionBenchmark", "category": "Benchmark", "path": "benchmarks/CoarseFineUniverseSelectionBenchmark.py"},
- "FCT-9C878F2C": {"name": "EmptyEquityAndOptions400Benchmark", "category": "Benchmark", "path": "benchmarks/EmptyEquityAndOptions400Benchmark.py"},
- "FCT-1E0D28D7": {"name": "EmptyMinute400EquityBenchmark", "category": "Benchmark", "path": "benchmarks/EmptyMinute400EquityBenchmark.py"},
- "FCT-9BA28BE5": {"name": "EmptySingleSecuritySecondEquityBenchmark", "category": "Benchmark", "path": "benchmarks/EmptySingleSecuritySecondEquityBenchmark.py"},
- "FCT-0C67D5F6": {"name": "HistoryRequestBenchmark", "category": "Benchmark", "path": "benchmarks/HistoryRequestBenchmark.py"},
- "FCT-D5F0AB7B": {"name": "IndicatorRibbonBenchmark", "category": "Benchmark", "path": "benchmarks/IndicatorRibbonBenchmark.py"},
- "FCT-5F7C7101": {"name": "ScheduledEventsBenchmark", "category": "Benchmark", "path": "benchmarks/ScheduledEventsBenchmark.py"},
- "FCT-FA9F3E6A": {"name": "StatefulCoarseUniverseSelectionBenchmark", "category": "Benchmark", "path": "benchmarks/StatefulCoarseUniverseSelectionBenchmark.py"},
- "FCT-D12D8ED1": {"name": "StatelessCoarseUniverseSelectionBenchmark", "category": "Benchmark", "path": "benchmarks/StatelessCoarseUniverseSelectionBenchmark.py"},
-}
diff --git a/fincept-qt/scripts/strategies/alphas/ContingentClaimsAnalysisDefaultPredictionAlpha.py b/fincept-qt/scripts/strategies/alphas/ContingentClaimsAnalysisDefaultPredictionAlpha.py
deleted file mode 100644
index 563f3992b..000000000
--- a/fincept-qt/scripts/strategies/alphas/ContingentClaimsAnalysisDefaultPredictionAlpha.py
+++ /dev/null
@@ -1,177 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-70CBDC3D
-# Category: Alpha Model
-# Description: Contingent Claim Analysis is put forth by Robert Merton, recepient of the Noble Prize in Economics in 1997 for his wo...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-import scipy.stats as sp
-from Risk.NullRiskManagementModel import NullRiskManagementModel
-from Portfolio.EqualWeightingPortfolioConstructionModel import EqualWeightingPortfolioConstructionModel
-from Execution.ImmediateExecutionModel import ImmediateExecutionModel
-
-class ContingentClaimsAnalysisDefaultPredictionAlpha(QCAlgorithm):
- ''' Contingent Claim Analysis is put forth by Robert Merton, recepient of the Noble Prize in Economics in 1997 for his work in contributing to
- Black-Scholes option pricing theory, which says that the equity market value of stockholders’ equity is given by the Black-Scholes solution
- for a European call option. This equation takes into account Debt, which in CCA is the equivalent to a strike price in the BS solution. The probability
- of default on corporate debt can be calculated as the N(-d2) term, where d2 is a function of the interest rate on debt(µ), face value of the debt (B), value of the firm's assets (V),
- standard deviation of the change in a firm's asset value (σ), the dividend and interest payouts due (D), and the time to maturity of the firm's debt(τ). N(*) is the cumulative
- distribution function of a standard normal distribution, and calculating N(-d2) gives us the probability of the firm's assets being worth less
- than the debt of the company at the time that the debt reaches maturity -- that is, the firm doesn't have enough in assets to pay off its debt and defaults.
-
- We use a Fine/Coarse Universe Selection model to select small cap stocks, who we postulate are more likely to default
- on debt in general than blue-chip companies, and extract Fundamental data to plug into the CCA formula.
- This Alpha emits insights based on whether or not a company is likely to default given its probability of default vs a default probability threshold that we set arbitrarily.
-
- Prob. default (on principal B at maturity T) = Prob(VT < B) = 1 - N(d2) = N(-d2) where -d2(µ) = -{ln(V/B) + [(µ - D) - ½σ2]τ}/ σ √τ.
- N(d) = (univariate) cumulative standard normal distribution function (from -inf to d)
- B = face value (principal) of the debt
- D = dividend + interest payout
- V = value of firm’s assets
- σ (sigma) = standard deviation of firm value changes (returns in V)
- τ (tau) = time to debt’s maturity
- µ (mu) = interest rate
-
- This alpha is part of the Benchmark Alpha Series created by QuantConnect which are open
- sourced so the community and client funds can see an example of an alpha.'''
-
- def initialize(self):
-
- ## Set requested data resolution and variables to help with Universe Selection control
- self.universe_settings.resolution = Resolution.DAILY
- self.month = -1
-
- ## Declare single variable to be passed in multiple places -- prevents issue with conflicting start dates declared in different places
- self.set_start_date(2018,1,1)
- self.set_cash(100000)
-
- ## SPDR Small Cap ETF is a better benchmark than the default SP500
- self.set_benchmark('IJR')
-
- ## Set Universe Selection Model
- self.set_universe_selection(FineFundamentalUniverseSelectionModel(self.coarse_selection_function, self.fine_selection_function))
- self.set_security_initializer(lambda security: security.set_fee_model(ConstantFeeModel(0)))
- ## Set CCA Alpha Model
- self.set_alpha(ContingentClaimsAnalysisAlphaModel())
-
- ## Set Portfolio Construction Model
- self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())
-
- ## Set Execution Model
- self.set_execution(ImmediateExecutionModel())
-
- ## Set Risk Management Model
- self.set_risk_management(NullRiskManagementModel())
-
-
- def coarse_selection_function(self, coarse):
- ## Boolean controls so that our symbol universe is only updated once per month
- if self.time.month == self.month:
- return Universe.UNCHANGED
- self.month = self.time.month
-
- ## Sort by dollar volume, lowest to highest
- sorted_by_dollar_volume = sorted([x for x in coarse if x.has_fundamental_data],
- key=lambda x: x.dollar_volume, reverse=True)
-
- ## Return smallest 750 -- idea is that smaller companies are most likely to go bankrupt than blue-chip companies
- ## Filter for assets with fundamental data
- return [x.symbol for x in sorted_by_dollar_volume[:750]]
-
- def fine_selection_function(self, fine):
-
- def is_valid(x):
- statement = x.financial_statements
- sheet = statement.balance_sheet
- total_assets = sheet.total_assets
- ratios = x.operation_ratios
-
- return total_assets.one_month > 0 and \
- total_assets.three_months > 0 and \
- total_assets.six_months > 0 and \
- total_assets.twelve_months > 0 and \
- sheet.current_liabilities.twelve_months > 0 and \
- sheet.interest_payable.twelve_months > 0 and \
- ratios.total_assets_growth.one_year > 0 and \
- statement.income_statement.gross_dividend_payment.twelve_months > 0 and \
- ratios.roa.one_year > 0
-
- return [x.symbol for x in sorted(fine, key=lambda x: is_valid(x))]
-
-
-class ContingentClaimsAnalysisAlphaModel:
-
- def __init__(self, *args, **kwargs):
- self.probability_of_default_by_symbol = {}
- self.default_threshold = kwargs['default_threshold'] if 'default_threshold' in kwargs else 0.25
-
- def update(self, algorithm, data):
- '''Updates this alpha model with the latest data from the algorithm.
- This is called each time the algorithm receives data for subscribed securities
- Args:
- algorithm: The algorithm instance
- data: The new data available
- Returns:
- The new insights generated'''
-
- ## Build a list to hold our insights
- insights = []
-
- for symbol, pod in self.probability_of_default_by_symbol.items():
-
- ## If Prob. of Default is greater than our set threshold, then emit an insight indicating that this asset is trending downward
- if pod >= self.default_threshold and pod != 1.0:
- insights.append(Insight.price(symbol, timedelta(30), InsightDirection.DOWN, pod, None))
-
- return insights
-
- def on_securities_changed(self, algorithm, changes):
-
- for removed in changes.removed_securities:
- self.probability_of_default_by_symbol.pop(removed.symbol, None)
-
- # initialize data for added securities
- symbols = [ x.symbol for x in changes.added_securities ]
-
- for symbol in symbols:
- if symbol not in self.probability_of_default_by_symbol:
- ## CCA valuation
- pod = self.get_probability_of_default(algorithm, symbol)
- if pod is not None:
- self.probability_of_default_by_symbol[symbol] = pod
-
- def get_probability_of_default(self, algorithm, symbol):
- '''This model applies options pricing theory, Black-Scholes specifically,
- to fundamental data to give the probability of a default'''
- security = algorithm.securities[symbol]
- if security.fundamentals is None or security.fundamentals.financial_statements is None or security.fundamentals.operation_ratios is None:
- return None
-
- statement = security.fundamentals.financial_statements
- sheet = statement.balance_sheet
- total_assets = sheet.total_assets
-
- tau = 360 ## Days
- mu = security.fundamentals.operation_ratios.roa.one_year
- V = total_assets.twelve_months
- B = sheet.current_liabilities.twelve_months
- D = statement.income_statement.gross_dividend_payment.twelve_months + sheet.interest_payable.twelve_months
-
- series = pd.Series(
- [
- total_assets.one_month,
- total_assets.three_months,
- total_assets.six_months,
- V
- ])
- sigma = series.iloc[series.nonzero()[0]]
- sigma = np.std(sigma.pct_change()[1:len(sigma)])
-
- d2 = ((np.log(V) - np.log(B)) + ((mu - D) - 0.5*sigma**2.0)*tau)/ (sigma*np.sqrt(tau))
- return sp.norm.cdf(-d2)
diff --git a/fincept-qt/scripts/strategies/alphas/GasAndCrudeOilEnergyCorrelationAlpha.py b/fincept-qt/scripts/strategies/alphas/GasAndCrudeOilEnergyCorrelationAlpha.py
deleted file mode 100644
index 2b7f88c57..000000000
--- a/fincept-qt/scripts/strategies/alphas/GasAndCrudeOilEnergyCorrelationAlpha.py
+++ /dev/null
@@ -1,217 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-9D7FFCA4
-# Category: Alpha Model
-# Description: Energy prices, especially Oil and Natural Gas, are in general fairly correlated,
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-'''
- Energy prices, especially Oil and Natural Gas, are in general fairly correlated,
- meaning they typically move in the same direction as an overall trend. This Alpha
- uses this idea and implements an Alpha Model that takes Natural Gas ETF price
- movements as a leading indicator for Crude Oil ETF price movements. We take the
- Natural Gas/Crude Oil ETF pair with the highest historical price correlation and
- then create insights for Crude Oil depending on whether or not the Natural Gas ETF price change
- is above/below a certain threshold that we set (arbitrarily).
-
-
-
- This alpha is part of the Benchmark Alpha Series created by QuantConnect which are open
- sourced so the community and client funds can see an example of an alpha.
-'''
-
-from AlgorithmImports import *
-
-class GasAndCrudeOilEnergyCorrelationAlpha(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2018, 1, 1) #Set Start Date
- self.set_cash(100000) #Set Strategy Cash
-
- natural_gas = [Symbol.create(x, SecurityType.EQUITY, Market.USA) for x in ['UNG','BOIL','FCG']]
- crude_oil = [Symbol.create(x, SecurityType.EQUITY, Market.USA) for x in ['USO','UCO','DBO']]
-
- ## Set Universe Selection
- self.universe_settings.resolution = Resolution.MINUTE
- self.set_universe_selection( ManualUniverseSelectionModel(natural_gas + crude_oil) )
- self.set_security_initializer(lambda security: security.set_fee_model(ConstantFeeModel(0)))
-
- ## Custom Alpha Model
- self.set_alpha(PairsAlphaModel(leading = natural_gas, following = crude_oil, history_days = 90, resolution = Resolution.MINUTE))
-
- ## Equal-weight our positions, in this case 100% in USO
- self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel(resolution = Resolution.MINUTE))
-
- ## Immediate Execution Fill Model
- self.set_execution(CustomExecutionModel())
-
- ## Null Risk-Management Model
- self.set_risk_management(NullRiskManagementModel())
-
- def on_order_event(self, order_event):
- if order_event.status == OrderStatus.FILLED:
- self.debug(f'Purchased Stock: {order_event.symbol}')
-
- def on_end_of_algorithm(self):
- for kvp in self.portfolio:
- if kvp.value.invested:
- self.log(f'Invested in: {kvp.key}')
-
-
-class PairsAlphaModel:
- '''This Alpha model assumes that the ETF for natural gas is a good leading-indicator
- of the price of the crude oil ETF. The model will take in arguments for a threshold
- at which the model triggers an insight, the length of the look-back period for evaluating
- rate-of-change of UNG prices, and the duration of the insight'''
-
- def __init__(self, *args, **kwargs):
- self.leading = kwargs.get('leading', [])
- self.following = kwargs.get('following', [])
- self.history_days = kwargs.get('history_days', 90) ## In days
- self.lookback = kwargs.get('lookback', 5)
- self.resolution = kwargs.get('resolution', Resolution.HOUR)
- self.prediction_interval = Time.multiply(Extensions.to_time_span(self.resolution), 5) ## Arbitrary
- self.difference_trigger = kwargs.get('difference_trigger', 0.75)
- self._symbol_data_by_symbol = {}
- self.next_update = None
-
- def update(self, algorithm, data):
-
- if (self.next_update is None) or (algorithm.time > self.next_update):
- self.correlation_pairs_selection()
- self.next_update = algorithm.time + timedelta(30)
-
- magnitude = round(self.pairs[0].rate_of_return / 100, 6)
-
- ## Check if Natural Gas returns are greater than the threshold we've set
- if self.pairs[0].rate_of_return > self.difference_trigger:
- return [Insight.price(self.pairs[1].symbol, self.prediction_interval, InsightDirection.UP, magnitude)]
- if self.pairs[0].rate_of_return < -self.difference_trigger:
- return [Insight.price(self.pairs[1].symbol, self.prediction_interval, InsightDirection.DOWN, magnitude)]
-
- return []
-
- def correlation_pairs_selection(self):
- ## Get returns for each natural gas/oil ETF
- daily_return = {}
- for symbol, symbol_data in self._symbol_data_by_symbol.items():
- daily_return[symbol] = symbol_data.daily_return_array
-
- ## Estimate coefficients of different correlation measures
- tau = pd.DataFrame.from_dict(daily_return).corr(method='kendall')
-
- ## Calculate the pair with highest historical correlation
- max_corr = -1
- for x in self.leading:
- df = tau[[x]].loc[self.following]
- corr = float(df.max())
- if corr > max_corr:
- self.pairs = (
- self._symbol_data_by_symbol[x],
- self._symbol_data_by_symbol[df.idxmax()[0]])
- max_corr = corr
-
- def on_securities_changed(self, algorithm, changes):
- '''Event fired each time the we add/remove securities from the data feed
- Args:
- algorithm: The algorithm instance that experienced the change in securities
- changes: The security additions and removals from the algorithm'''
- for removed in changes.removed_securities:
- symbol_data = self._symbol_data_by_symbol.pop(removed.symbol, None)
- if symbol_data is not None:
- symbol_data.remove_consolidators(algorithm)
-
- # initialize data for added securities
- symbols = [ x.symbol for x in changes.added_securities ]
- history = algorithm.history(symbols, self.history_days + 1, Resolution.DAILY)
- if history.empty: return
-
- tickers = history.index.levels[0]
- for ticker in tickers:
- symbol = SymbolCache.get_symbol(ticker)
- if symbol not in self._symbol_data_by_symbol:
- symbol_data = SymbolData(symbol, self.history_days, self.lookback, self.resolution, algorithm)
- self._symbol_data_by_symbol[symbol] = symbol_data
- symbol_data.update_daily_rate_of_change(history.loc[ticker])
-
- history = algorithm.history(symbols, self.lookback, self.resolution)
- if history.empty: return
- for ticker in tickers:
- symbol = SymbolCache.get_symbol(ticker)
- if symbol in self._symbol_data_by_symbol:
- self._symbol_data_by_symbol[symbol].update_rate_of_change(history.loc[ticker])
-
-class SymbolData:
- '''Contains data specific to a symbol required by this model'''
- def __init__(self, symbol, daily_lookback, lookback, resolution, algorithm):
- self.symbol = symbol
-
- self.daily_return = RateOfChangePercent(f'{symbol}.daily_rocp({1})', 1)
- self.daily_consolidator = algorithm.resolve_consolidator(symbol, Resolution.DAILY)
- self.daily_return_history = RollingWindow[IndicatorDataPoint](daily_lookback)
-
- def updatedaily_return_history(s, e):
- self.daily_return_history.add(e)
-
- self.daily_return.updated += updatedaily_return_history
- algorithm.register_indicator(symbol, self.daily_return, self.daily_consolidator)
-
- self.rocp = RateOfChangePercent(f'{symbol}.rocp({lookback})', lookback)
- self.consolidator = algorithm.resolve_consolidator(symbol, resolution)
- algorithm.register_indicator(symbol, self.rocp, self.consolidator)
-
- def remove_consolidators(self, algorithm):
- algorithm.subscription_manager.remove_consolidator(self.symbol, self.consolidator)
- algorithm.subscription_manager.remove_consolidator(self.symbol, self.daily_consolidator)
-
- def update_rate_of_change(self, history):
- for tuple in history.itertuples():
- self.rocp.update(tuple.Index, tuple.close)
-
- def update_daily_rate_of_change(self, history):
- for tuple in history.itertuples():
- self.daily_return.update(tuple.Index, tuple.close)
-
- @property
- def rate_of_return(self):
- return float(self.rocp.current.value)
-
- @property
- def daily_return_array(self):
- return pd.Series({x.end_time: x.value for x in self.daily_return_history})
-
- def __repr__(self):
- return f"{self.rocp.name} - {Return}"
-
-
-class CustomExecutionModel(ExecutionModel):
- '''Provides an implementation of IExecutionModel that immediately submits market orders to achieve the desired portfolio targets'''
-
- def __init__(self):
- '''Initializes a new instance of the ImmediateExecutionModel class'''
- self.targets_collection = PortfolioTargetCollection()
- self.previous_symbol = None
-
- def execute(self, algorithm, targets):
- '''Immediately submits orders for the specified portfolio targets.
- Args:
- algorithm: The algorithm instance
- targets: The portfolio targets to be ordered'''
-
- self.targets_collection.add_range(targets)
-
- for target in self.targets_collection.order_by_margin_impact(algorithm):
- open_quantity = sum([x.quantity for x in algorithm.transactions.get_open_orders(target.symbol)])
- existing = algorithm.securities[target.symbol].holdings.quantity + open_quantity
- quantity = target.quantity - existing
- ## Liquidate positions in Crude Oil ETF that is no longer part of the highest-correlation pair
- if (str(target.symbol) != str(self.previous_symbol)) and (self.previous_symbol is not None):
- algorithm.liquidate(self.previous_symbol)
- if quantity != 0:
- algorithm.market_order(target.symbol, quantity)
- self.previous_symbol = target.symbol
- self.targets_collection.clear_fulfilled(algorithm)
diff --git a/fincept-qt/scripts/strategies/alphas/GlobalEquityMeanReversionIBSAlpha.py b/fincept-qt/scripts/strategies/alphas/GlobalEquityMeanReversionIBSAlpha.py
deleted file mode 100644
index fdff9a101..000000000
--- a/fincept-qt/scripts/strategies/alphas/GlobalEquityMeanReversionIBSAlpha.py
+++ /dev/null
@@ -1,109 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-C3B2CF90
-# Category: Alpha Model
-# Description: Uses ranking of Internal Bar Strength (IBS) to create direction prediction for insights
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-#
-# Equity indices exhibit mean reversion in daily returns. The Internal Bar Strength indicator (IBS),
-# which relates the closing price of a security to its daily range can be used to identify overbought
-# and oversold securities.
-#
-# This alpha ranks 33 global equity ETFs on its IBS value the previous day and predicts for the following day
-# that the ETF with the highest IBS value will decrease in price, and the ETF with the lowest IBS value
-# will increase in price.
-#
-# Source: Kakushadze, Zura, and Juan Andrés Serur. “4. Exchange-Traded Funds (ETFs).” 151 Trading Strategies, Palgrave Macmillan, 2018, pp. 90–91.
-#
-# This alpha is part of the Benchmark Alpha Series created by QuantConnect which are open sourced so the community and client funds can see an example of an alpha.
-#
-
-class GlobalEquityMeanReversionIBSAlpha(QCAlgorithm):
-
- def initialize(self):
-
- self.set_start_date(2018, 1, 1)
-
- self.set_cash(100000)
-
- # Set zero transaction fees
- self.set_security_initializer(lambda security: security.set_fee_model(ConstantFeeModel(0)))
-
- # Global Equity ETF tickers
- tickers = ["ECH","EEM","EFA","EPHE","EPP","EWA","EWC","EWG",
- "EWH","EWI","EWJ","EWL","EWM","EWM","EWO","EWP",
- "EWQ","EWS","EWT","EWU","EWY","EWZ","EZA","FXI",
- "GXG","IDX","ILF","EWM","QQQ","RSX","SPY","THD"]
-
- symbols = [Symbol.create(ticker, SecurityType.EQUITY, Market.USA) for ticker in tickers]
-
- # Manually curated universe
- self.universe_settings.resolution = Resolution.DAILY
- self.set_universe_selection(ManualUniverseSelectionModel(symbols))
-
- # Use GlobalEquityMeanReversionAlphaModel to establish insights
- self.set_alpha(MeanReversionIBSAlphaModel())
-
- # Equally weigh securities in portfolio, based on insights
- self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())
-
- # Set Immediate Execution Model
- self.set_execution(ImmediateExecutionModel())
-
- # Set Null Risk Management Model
- self.set_risk_management(NullRiskManagementModel())
-
-
-class MeanReversionIBSAlphaModel(AlphaModel):
- '''Uses ranking of Internal Bar Strength (IBS) to create direction prediction for insights'''
-
- def __init__(self, *args, **kwargs):
- lookback = kwargs['lookback'] if 'lookback' in kwargs else 1
- resolution = kwargs['resolution'] if 'resolution' in kwargs else Resolution.DAILY
- self.prediction_interval = Time.multiply(Extensions.to_time_span(resolution), lookback)
- self.number_of_stocks = kwargs['number_of_stocks'] if 'number_of_stocks' in kwargs else 2
-
- def update(self, algorithm, data):
-
- insights = []
- symbols_ibs = dict()
- returns = dict()
-
- for security in algorithm.active_securities.values:
- if security.has_data:
- high = security.high
- low = security.low
- hilo = high - low
-
- # Do not consider symbol with zero open and avoid division by zero
- if security.open * hilo != 0:
- # Internal bar strength (IBS)
- symbols_ibs[security.symbol] = (security.close - low)/hilo
- returns[security.symbol] = security.close/security.open-1
-
- # Number of stocks cannot be higher than half of symbols_ibs length
- number_of_stocks = min(int(len(symbols_ibs)/2), self.number_of_stocks)
- if number_of_stocks == 0:
- return []
-
- # Rank securities with the highest IBS value
- ordered = sorted(symbols_ibs.items(), key=lambda kv: (round(kv[1], 6), kv[0]), reverse=True)
- high_ibs = dict(ordered[0:number_of_stocks]) # Get highest IBS
- low_ibs = dict(ordered[-number_of_stocks:]) # Get lowest IBS
-
- # Emit "down" insight for the securities with the highest IBS value
- for key,value in high_ibs.items():
- insights.append(Insight.price(key, self.prediction_interval, InsightDirection.DOWN, abs(returns[key]), None))
-
- # Emit "up" insight for the securities with the lowest IBS value
- for key,value in low_ibs.items():
- insights.append(Insight.price(key, self.prediction_interval, InsightDirection.UP, abs(returns[key]), None))
-
- return insights
diff --git a/fincept-qt/scripts/strategies/alphas/GreenblattMagicFormulaAlpha.py b/fincept-qt/scripts/strategies/alphas/GreenblattMagicFormulaAlpha.py
deleted file mode 100644
index 06a43cccb..000000000
--- a/fincept-qt/scripts/strategies/alphas/GreenblattMagicFormulaAlpha.py
+++ /dev/null
@@ -1,209 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-46661FE6
-# Category: Alpha Model
-# Description: Alpha Streams: Benchmark Alpha: Pick stocks according to Joel Greenblatt's Magic Formula
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-from Selection.FundamentalUniverseSelectionModel import FundamentalUniverseSelectionModel
-
-from math import ceil
-from itertools import chain
-
-class GreenblattMagicFormulaAlpha(QCAlgorithm):
- ''' Alpha Streams: Benchmark Alpha: Pick stocks according to Joel Greenblatt's Magic Formula
- This alpha picks stocks according to Joel Greenblatt's Magic Formula.
- First, each stock is ranked depending on the relative value of the ratio EV/EBITDA. For example, a stock
- that has the lowest EV/EBITDA ratio in the security universe receives a score of one while a stock that has
- the tenth lowest EV/EBITDA score would be assigned 10 points.
-
- Then, each stock is ranked and given a score for the second valuation ratio, Return on Capital (ROC).
- Similarly, a stock that has the highest ROC value in the universe gets one score point.
- The stocks that receive the lowest combined score are chosen for insights.
-
- Source: Greenblatt, J. (2010) The Little Book That Beats the Market
-
- This alpha is part of the Benchmark Alpha Series created by QuantConnect which are open
- sourced so the community and client funds can see an example of an alpha.'''
-
- def initialize(self):
-
- self.set_start_date(2018, 1, 1)
- self.set_cash(100000)
-
- #Set zero transaction fees
- self.set_security_initializer(lambda security: security.set_fee_model(ConstantFeeModel(0)))
-
- # select stocks using MagicFormulaUniverseSelectionModel
- self.set_universe_selection(GreenBlattMagicFormulaUniverseSelectionModel())
-
- # Use MagicFormulaAlphaModel to establish insights
- self.set_alpha(RateOfChangeAlphaModel())
-
- # Equally weigh securities in portfolio, based on insights
- self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())
-
- ## Set Immediate Execution Model
- self.set_execution(ImmediateExecutionModel())
-
- ## Set Null Risk Management Model
- self.set_risk_management(NullRiskManagementModel())
-
-class RateOfChangeAlphaModel(AlphaModel):
- '''Uses Rate of Change (ROC) to create magnitude prediction for insights.'''
-
- def __init__(self, *args, **kwargs):
- self.lookback = kwargs.get('lookback', 1)
- self.resolution = kwargs.get('resolution', Resolution.DAILY)
- self.prediction_interval = Time.multiply(Extensions.to_time_span(self.resolution), self.lookback)
- self._symbol_data_by_symbol = {}
-
- def update(self, algorithm, data):
- insights = []
- for symbol, symbol_data in self._symbol_data_by_symbol.items():
- if symbol_data.can_emit:
- insights.append(Insight.price(symbol, self.prediction_interval, InsightDirection.UP, symbol_data.returns, None))
- return insights
-
- def on_securities_changed(self, algorithm, changes):
-
- # clean up data for removed securities
- for removed in changes.removed_securities:
- symbol_data = self._symbol_data_by_symbol.pop(removed.symbol, None)
- if symbol_data is not None:
- symbol_data.remove_consolidators(algorithm)
-
- # initialize data for added securities
- symbols = [ x.symbol for x in changes.added_securities
- if x.symbol not in self._symbol_data_by_symbol]
-
- history = algorithm.history(symbols, self.lookback, self.resolution)
- if history.empty: return
-
- for symbol in symbols:
- symbol_data = SymbolData(algorithm, symbol, self.lookback, self.resolution)
- self._symbol_data_by_symbol[symbol] = symbol_data
- symbol_data.warm_up_indicators(history.loc[symbol])
-
-
-class SymbolData:
- '''Contains data specific to a symbol required by this model'''
- def __init__(self, algorithm, symbol, lookback, resolution):
- self.previous = 0
- self._symbol = symbol
- self.roc = RateOfChange(f'{symbol}.roc({lookback})', lookback)
- self.consolidator = algorithm.resolve_consolidator(symbol, resolution)
- algorithm.register_indicator(symbol, self.roc, self.consolidator)
-
- def remove_consolidators(self, algorithm):
- algorithm.subscription_manager.remove_consolidator(self._symbol, self.consolidator)
-
- def warm_up_indicators(self, history):
- for tuple in history.itertuples():
- self.roc.update(tuple.Index, tuple.close)
-
- @property
- def returns(self):
- return self.roc.current.value
-
- @property
- def can_emit(self):
- if self.previous == self.roc.samples:
- return False
-
- self.previous = self.roc.samples
- return self.roc.is_ready
-
- def __str__(self, **kwargs):
- return f'{self.roc.name}: {(1 + self.returns)**252 - 1:.2%}'
-
-
-class GreenBlattMagicFormulaUniverseSelectionModel(FundamentalUniverseSelectionModel):
- '''Defines a universe according to Joel Greenblatt's Magic Formula, as a universe selection model for the framework algorithm.
- From the universe QC500, stocks are ranked using the valuation ratios, Enterprise Value to EBITDA (EV/EBITDA) and Return on Assets (ROA).
- '''
-
- def __init__(self,
- filter_fine_data = True,
- universe_settings = None):
- '''Initializes a new default instance of the MagicFormulaUniverseSelectionModel'''
- super().__init__(filter_fine_data, universe_settings)
-
- # Number of stocks in Coarse Universe
- self.number_of_symbols_coarse = 500
- # Number of sorted stocks in the fine selection subset using the valuation ratio, EV to EBITDA (EV/EBITDA)
- self.number_of_symbols_fine = 20
- # Final number of stocks in security list, after sorted by the valuation ratio, Return on Assets (ROA)
- self.number_of_symbols_in_portfolio = 10
-
- self.last_month = -1
- self.dollar_volume_by_symbol = {}
-
- def select_coarse(self, algorithm, coarse):
- '''Performs coarse selection for constituents.
- The stocks must have fundamental data'''
- month = algorithm.time.month
- if month == self.last_month:
- return Universe.UNCHANGED
- self.last_month = month
-
- # sort the stocks by dollar volume and take the top 1000
- top = sorted([x for x in coarse if x.has_fundamental_data],
- key=lambda x: x.dollar_volume, reverse=True)[:self.number_of_symbols_coarse]
-
- self.dollar_volume_by_symbol = { i.symbol: i.dollar_volume for i in top }
-
- return list(self.dollar_volume_by_symbol.keys())
-
-
- def select_fine(self, algorithm, fine):
- '''QC500: Performs fine selection for the coarse selection constituents
- The company's headquarter must in the U.S.
- The stock must be traded on either the NYSE or NASDAQ
- At least half a year since its initial public offering
- The stock's market cap must be greater than 500 million
-
- Magic Formula: Rank stocks by Enterprise Value to EBITDA (EV/EBITDA)
- Rank subset of previously ranked stocks (EV/EBITDA), using the valuation ratio Return on Assets (ROA)'''
-
- # QC500:
- ## The company's headquarter must in the U.S.
- ## The stock must be traded on either the NYSE or NASDAQ
- ## At least half a year since its initial public offering
- ## The stock's market cap must be greater than 500 million
- filtered_fine = [x for x in fine if x.company_reference.country_id == "USA"
- and (x.company_reference.primary_exchange_id == "NYS" or x.company_reference.primary_exchange_id == "NAS")
- and (algorithm.time - x.security_reference.ipo_date).days > 180
- and x.earning_reports.basic_average_shares.three_months * x.earning_reports.basic_eps.twelve_months * x.valuation_ratios.pe_ratio > 5e8]
- count = len(filtered_fine)
- if count == 0: return []
-
- my_dict = dict()
- percent = self.number_of_symbols_fine / count
-
- # select stocks with top dollar volume in every single sector
- for key in ["N", "M", "U", "T", "B", "I"]:
- value = [x for x in filtered_fine if x.company_reference.industry_template_code == key]
- value = sorted(value, key=lambda x: self.dollar_volume_by_symbol[x.symbol], reverse = True)
- my_dict[key] = value[:ceil(len(value) * percent)]
-
- # stocks in QC500 universe
- top_fine = chain.from_iterable(my_dict.values())
-
- # Magic Formula:
- ## Rank stocks by Enterprise Value to EBITDA (EV/EBITDA)
- ## Rank subset of previously ranked stocks (EV/EBITDA), using the valuation ratio Return on Assets (ROA)
-
- # sort stocks in the security universe of QC500 based on Enterprise Value to EBITDA valuation ratio
- sorted_by_ev_to_ebitda = sorted(top_fine, key=lambda x: x.valuation_ratios.ev_to_ebitda , reverse=True)
-
- # sort subset of stocks that have been sorted by Enterprise Value to EBITDA, based on the valuation ratio Return on Assets (ROA)
- sorted_by_roa = sorted(sorted_by_ev_to_ebitda[:self.number_of_symbols_fine], key=lambda x: x.valuation_ratios.forward_roa, reverse=False)
-
- # retrieve list of securites in portfolio
- return [f.symbol for f in sorted_by_roa[:self.number_of_symbols_in_portfolio]]
diff --git a/fincept-qt/scripts/strategies/alphas/IntradayReversalCurrencyMarketsAlpha.py b/fincept-qt/scripts/strategies/alphas/IntradayReversalCurrencyMarketsAlpha.py
deleted file mode 100644
index 082027db5..000000000
--- a/fincept-qt/scripts/strategies/alphas/IntradayReversalCurrencyMarketsAlpha.py
+++ /dev/null
@@ -1,120 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-5596A325
-# Category: Alpha Model
-# Description: Alpha model that uses a Price/SMA Crossover to create insights on Hourly Frequency.
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-#
-# Reversal strategy that goes long when price crosses below SMA and Short when price crosses above SMA.
-# The trading strategy is implemented only between 10AM - 3PM (NY time). Research suggests this is due to
-# institutional trades during market hours which need hedging with the USD. Source paper:
-# LeBaron, Zhao: Intraday Foreign Exchange Reversals
-# http://people.brandeis.edu/~blebaron/wps/fxnyc.pdf
-# http://www.fma.org/Reno/Papers/ForeignExchangeReversalsinNewYorkTime.PDF
-#
-# This alpha is part of the Benchmark Alpha Series created by QuantConnect which are open sourced so the community and client funds can see an example of an alpha.
-#
-
-class IntradayReversalCurrencyMarketsAlpha(QCAlgorithm):
-
- def initialize(self):
-
- self.set_start_date(2015, 1, 1)
- self.set_cash(100000)
-
- # Set zero transaction fees
- self.set_security_initializer(lambda security: security.set_fee_model(ConstantFeeModel(0)))
-
- # Select resolution
- resolution = Resolution.HOUR
-
- # Reversion on the USD.
- symbols = [Symbol.create("EURUSD", SecurityType.FOREX, Market.OANDA)]
-
- # Set requested data resolution
- self.universe_settings.resolution = resolution
- self.set_universe_selection(ManualUniverseSelectionModel(symbols))
- self.set_alpha(IntradayReversalAlphaModel(5, resolution))
-
- # Equally weigh securities in portfolio, based on insights
- self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())
-
- # Set Immediate Execution Model
- self.set_execution(ImmediateExecutionModel())
-
- # Set Null Risk Management Model
- self.set_risk_management(NullRiskManagementModel())
-
- #Set WarmUp for Indicators
- self.set_warm_up(20)
-
-
-class IntradayReversalAlphaModel(AlphaModel):
- '''Alpha model that uses a Price/SMA Crossover to create insights on Hourly Frequency.
- Frequency: Hourly data with 5-hour simple moving average.
- Strategy:
- Reversal strategy that goes Long when price crosses below SMA and Short when price crosses above SMA.
- The trading strategy is implemented only between 10AM - 3PM (NY time)'''
-
- # Initialize variables
- def __init__(self, period_sma = 5, resolution = Resolution.HOUR):
- self.period_sma = period_sma
- self.resolution = resolution
- self.cache = {} # Cache for SymbolData
- self.name = 'IntradayReversalAlphaModel'
-
- def update(self, algorithm, data):
- # Set the time to close all positions at 3PM
- time_to_close = algorithm.time.replace(hour=15, minute=1, second=0)
-
- insights = []
- for kvp in algorithm.active_securities:
-
- symbol = kvp.key
-
- if self.should_emit_insight(algorithm, symbol) and symbol in self.cache:
-
- price = kvp.value.price
- symbol_data = self.cache[symbol]
-
- direction = InsightDirection.UP if symbol_data.is_uptrend(price) else InsightDirection.DOWN
-
- # Ignore signal for same direction as previous signal (when no crossover)
- if direction == symbol_data.previous_direction:
- continue
-
- # Save the current Insight Direction to check when the crossover happens
- symbol_data.previous_direction = direction
-
- # Generate insight
- insights.append(Insight.price(symbol, time_to_close, direction))
-
- return insights
-
- def on_securities_changed(self, algorithm, changes):
- '''Handle creation of the new security and its cache class.
- Simplified in this example as there is 1 asset.'''
- for security in changes.added_securities:
- self.cache[security.symbol] = SymbolData(algorithm, security.symbol, self.period_sma, self.resolution)
-
- def should_emit_insight(self, algorithm, symbol):
- '''Time to control when to start and finish emitting (10AM to 3PM)'''
- time_of_day = algorithm.time.time()
- return algorithm.securities[symbol].has_data and time_of_day >= time(10) and time_of_day <= time(15)
-
-
-class SymbolData:
-
- def __init__(self, algorithm, symbol, period_sma, resolution):
- self.previous_direction = InsightDirection.FLAT
- self.price_sma = algorithm.sma(symbol, period_sma, resolution)
-
- def is_uptrend(self, price):
- return self.price_sma.is_ready and price < round(self.price_sma.current.value * 1.001, 6)
diff --git a/fincept-qt/scripts/strategies/alphas/MeanReversionLunchBreakAlpha.py b/fincept-qt/scripts/strategies/alphas/MeanReversionLunchBreakAlpha.py
deleted file mode 100644
index 8c7ad2e59..000000000
--- a/fincept-qt/scripts/strategies/alphas/MeanReversionLunchBreakAlpha.py
+++ /dev/null
@@ -1,121 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-EAEEE69C
-# Category: Alpha Model
-# Description: Uses the price return between the close of previous day to 12:00 the day after to
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-#
-# Academic research suggests that stock market participants generally place their orders at the market open and close.
-# Intraday trading volume is J-Shaped, where the minimum trading volume of the day is during lunch-break. Stocks become
-# more volatile as order flow is reduced and tend to mean-revert during lunch-break.
-#
-# This alpha aims to capture the mean-reversion effect of ETFs during lunch-break by ranking 20 ETFs
-# on their return between the close of the previous day to 12:00 the day after and predicting mean-reversion
-# in price during lunch-break.
-#
-# Source: Lunina, V. (June 2011). The Intraday Dynamics of Stock Returns and Trading Activity: Evidence from OMXS 30 (Master's Essay, Lund University).
-# Retrieved from http://lup.lub.lu.se/luur/download?func=downloadFile&recordOId=1973850&fileOId=1973852
-#
-# This alpha is part of the Benchmark Alpha Series created by QuantConnect which are open sourced so the community and client funds can see an example of an alpha.
-#
-
-class MeanReversionLunchBreakAlpha(QCAlgorithm):
-
- def initialize(self):
-
- self.set_start_date(2018, 1, 1)
-
- self.set_cash(100000)
-
- # Set zero transaction fees
- self.set_security_initializer(lambda security: security.set_fee_model(ConstantFeeModel(0)))
-
- # Use Hourly Data For Simplicity
- self.universe_settings.resolution = Resolution.HOUR
- self.set_universe_selection(CoarseFundamentalUniverseSelectionModel(self.coarse_selection_function))
-
- # Use MeanReversionLunchBreakAlphaModel to establish insights
- self.set_alpha(MeanReversionLunchBreakAlphaModel())
-
- # Equally weigh securities in portfolio, based on insights
- self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())
-
- # Set Immediate Execution Model
- self.set_execution(ImmediateExecutionModel())
-
- # Set Null Risk Management Model
- self.set_risk_management(NullRiskManagementModel())
-
- # Sort the data by daily dollar volume and take the top '20' ETFs
- def coarse_selection_function(self, coarse):
- sorted_by_dollar_volume = sorted(coarse, key=lambda x: x.dollar_volume, reverse=True)
- filtered = [ x.symbol for x in sorted_by_dollar_volume if not x.has_fundamental_data ]
- return filtered[:20]
-
-
-class MeanReversionLunchBreakAlphaModel(AlphaModel):
- '''Uses the price return between the close of previous day to 12:00 the day after to
- predict mean-reversion of stock price during lunch break and creates direction prediction
- for insights accordingly.'''
-
- def __init__(self, *args, **kwargs):
- lookback = kwargs['lookback'] if 'lookback' in kwargs else 1
- self.resolution = Resolution.HOUR
- self.prediction_interval = Time.multiply(Extensions.to_time_span(self.resolution), lookback)
- self._symbol_data_by_symbol = dict()
-
- def update(self, algorithm, data):
-
- for symbol, symbol_data in self._symbol_data_by_symbol.items():
- if data.bars.contains_key(symbol):
- bar = data.bars.get_value(symbol)
- symbol_data.update(bar.end_time, bar.close)
-
- return [] if algorithm.time.hour != 12 else \
- [x.insight for x in self._symbol_data_by_symbol.values()]
-
- def on_securities_changed(self, algorithm, changes):
- for security in changes.removed_securities:
- self._symbol_data_by_symbol.pop(security.symbol, None)
-
- # Retrieve price history for all securities in the security universe
- # and update the indicators in the SymbolData object
- symbols = [x.symbol for x in changes.added_securities]
- history = algorithm.history(symbols, 1, self.resolution)
- if history.empty:
- algorithm.debug(f"No data on {algorithm.time}")
- return
- history = history.close.unstack(level = 0)
-
- for ticker, values in history.items():
- symbol = next((x for x in symbols if str(x) == ticker ), None)
- if symbol in self._symbol_data_by_symbol or symbol is None: continue
- self._symbol_data_by_symbol[symbol] = self.SymbolData(symbol, self.prediction_interval)
- self._symbol_data_by_symbol[symbol].update(values.index[0], values[0])
-
-
- class SymbolData:
- def __init__(self, symbol, period):
- self._symbol = symbol
- self.period = period
- # Mean value of returns for magnitude prediction
- self.mean_of_price_change = IndicatorExtensions.sma(RateOfChangePercent(1),3)
- # Price change from close price the previous day
- self.price_change = RateOfChangePercent(3)
-
- def update(self, time, value):
- return self.mean_of_price_change.update(time, value) and \
- self.price_change.update(time, value)
-
- @property
- def insight(self):
- direction = InsightDirection.DOWN if self.price_change.current.value > 0 else InsightDirection.UP
- margnitude = abs(self.mean_of_price_change.current.value)
- return Insight.price(self._symbol, self.period, direction, margnitude, None)
diff --git a/fincept-qt/scripts/strategies/alphas/MortgageRateVolatilityAlpha.py b/fincept-qt/scripts/strategies/alphas/MortgageRateVolatilityAlpha.py
deleted file mode 100644
index 85625ccaa..000000000
--- a/fincept-qt/scripts/strategies/alphas/MortgageRateVolatilityAlpha.py
+++ /dev/null
@@ -1,107 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-B86663BE
-# Category: Alpha Model
-# Description: This Alpha Model uses Wells Fargo 30-year Fixed Rate Mortgage data from Quandl to
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-'''
- This Alpha Model uses Wells Fargo 30-year Fixed Rate Mortgage data from Quandl to
- generate Insights about the movement of Real Estate ETFs. Mortgage rates can provide information
- regarding the general price trend of real estate, and ETFs provide good continuous-time instruments
- to measure the impact against. Volatility in mortgage rates tends to put downward pressure on real
- estate prices, whereas stable mortgage rates, regardless of true rate, lead to stable or higher real
- estate prices. This Alpha model seeks to take advantage of this correlation by emitting insights
- based on volatility and rate deviation from its historic mean.
-
- This alpha is part of the Benchmark Alpha Series created by QuantConnect which are open
- sourced so the community and client funds can see an example of an alpha.
-'''
-
-from AlgorithmImports import *
-
-class MortgageRateVolatilityAlpha(QCAlgorithmFramework):
-
- def initialize(self):
-
- # Set requested data resolution
- self.set_start_date(2017, 1, 1) #Set Start Date
- self.set_cash(100000) #Set Strategy Cash
-
- self.universe_settings.resolution = Resolution.DAILY
-
- ## Universe of six liquid real estate ETFs
- etfs = ['VNQ', 'REET', 'TAO', 'FREL', 'SRET', 'HIPS']
- symbols = [ Symbol.create(etf, SecurityType.EQUITY, Market.USA) for etf in etfs ]
- self.set_security_initializer(lambda security: security.set_fee_model(ConstantFeeModel(0)))
- self.set_universe_selection(ManualUniverseSelectionModel(symbols) )
-
- self.set_alpha(MortgageRateVolatilityAlphaModel(self))
-
- self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())
-
- self.set_execution(ImmediateExecutionModel())
-
- self.set_risk_management(NullRiskManagementModel())
-
-
-class MortgageRateVolatilityAlphaModel(AlphaModel):
-
- def __init__(self, algorithm, indicator_period = 15, insight_magnitude = 0.005, deviations = 2):
- ## Add Quandl data for a Well's Fargo 30-year Fixed Rate mortgage
- self.mortgage_rate = algorithm.add_data(QuandlMortgagePriceColumns, 'WFC/PR_GOV_30YFIXEDVA_APR').symbol
- self.indicator_period = indicator_period
- self.insight_duration = TimeSpan.from_days(indicator_period)
- self.insight_magnitude = insight_magnitude
- self.deviations = deviations
-
- ## Add indicators for the mortgage rate -- Standard Deviation and Simple Moving Average
- self.mortgage_rate_std = algorithm.std(self.mortgage_rate, indicator_period)
- self.mortgage_rate_sma = algorithm.sma(self.mortgage_rate, indicator_period)
-
- ## Use a history call to warm-up the indicators
- self.warmup_indicators(algorithm)
-
- def update(self, algorithm, data):
- insights = []
-
- ## Return empty list if data slice doesn't contain monrtgage rate data
- if self.mortgage_rate not in data.keys():
- return []
-
- ## Extract current mortgage rate, the current STD indicator value, and current SMA value
- mortgage_rate = data[self.mortgage_rate].value
- deviation = self.deviations * self.mortgage_rate_std.current.value
- sma = self.mortgage_rate_sma.current.value
-
- ## If volatility in mortgage rates is high, then we emit an Insight to sell
- if (mortgage_rate < sma - deviation) or (mortgage_rate > sma + deviation):
- ## Emit insights for all securities that are currently in the Universe,
- ## except for the Quandl Symbol
- insights = [Insight(security, self.insight_duration, InsightType.PRICE, InsightDirection.DOWN, self.insight_magnitude, None) \
- for security in algorithm.active_securities.keys if security != self.mortgage_rate]
-
- ## If volatility in mortgage rates is low, then we emit an Insight to buy
- if (mortgage_rate < sma - deviation/2) or (mortgage_rate > sma + deviation/2):
- insights = [Insight(security, self.insight_duration, InsightType.PRICE, InsightDirection.UP, self.insight_magnitude, None) \
- for security in algorithm.active_securities.keys if security != self.mortgage_rate]
-
- return insights
-
- def warmup_indicators(self, algorithm):
- ## Make a history call and update the indicators
- history = algorithm.history(self.mortgage_rate, self.indicator_period, Resolution.DAILY)
- for index, row in history.iterrows():
- self.mortgage_rate_std.update(index[1], row['value'])
- self.mortgage_rate_sma.update(index[1], row['value'])
-
-class QuandlMortgagePriceColumns(PythonQuandl):
-
- def __init__(self):
- ## Rename the Quandl object column to the data we want, which is the 'Value' column
- ## of the CSV that our API call returns
- self.value_column_name = "Value"
diff --git a/fincept-qt/scripts/strategies/alphas/PriceGapMeanReversionAlpha.py b/fincept-qt/scripts/strategies/alphas/PriceGapMeanReversionAlpha.py
deleted file mode 100644
index 10cfcaaae..000000000
--- a/fincept-qt/scripts/strategies/alphas/PriceGapMeanReversionAlpha.py
+++ /dev/null
@@ -1,137 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-899805AE
-# Category: Alpha Model
-# Description: The motivating idea for this Alpha Model is that a large price gap (here we use true outliers --
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-class PriceGapMeanReversionAlpha(QCAlgorithm):
- '''The motivating idea for this Alpha Model is that a large price gap (here we use true outliers --
- price gaps that whose absolutely values are greater than 3 * Volatility) is due to rebound
- back to an appropriate price or at least retreat from its brief extreme. Using a Coarse Universe selection
- function, the algorithm selects the top x-companies by Dollar Volume (x can be any number you choose)
- to trade with, and then uses the Standard Deviation of the 100 most-recent closing prices to determine
- which price movements are outliers that warrant emitting insights.
-
- This alpha is part of the Benchmark Alpha Series created by QuantConnect which are open
- sourced so the community and client funds can see an example of an alpha.'''
-
- def initialize(self):
-
- self.set_start_date(2018, 1, 1) #Set Start Date
- self.set_cash(100000) #Set Strategy Cash
-
- ## Initialize variables to be used in controlling frequency of universe selection
- self.week = -1
-
- ## Manual Universe Selection
- self.universe_settings.resolution = Resolution.MINUTE
- self.set_universe_selection(CoarseFundamentalUniverseSelectionModel(self.coarse_selection_function))
-
- ## Set trading fees to $0
- self.set_security_initializer(lambda security: security.set_fee_model(ConstantFeeModel(0)))
-
- ## Set custom Alpha Model
- self.set_alpha(PriceGapMeanReversionAlphaModel())
-
- ## Set equal-weighting Portfolio Construction Model
- self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())
-
- ## Set Execution Model
- self.set_execution(ImmediateExecutionModel())
-
- ## Set Risk Management Model
- self.set_risk_management(NullRiskManagementModel())
-
-
- def coarse_selection_function(self, coarse):
- ## If it isn't a new week, return the same symbols
- current_week = self.time.isocalendar()[1]
- if current_week == self.week:
- return Universe.UNCHANGED
- self.week = current_week
-
- ## If its a new week, then re-filter stocks by Dollar Volume
- sorted_by_dollar_volume = sorted(coarse, key=lambda x: x.dollar_volume, reverse=True)
-
- return [ x.symbol for x in sorted_by_dollar_volume[:25] ]
-
-
-class PriceGapMeanReversionAlphaModel:
-
- def __init__(self, *args, **kwargs):
- ''' Initialize variables and dictionary for Symbol Data to support algorithm's function '''
- self.lookback = 100
- self.resolution = kwargs['resolution'] if 'resolution' in kwargs else Resolution.MINUTE
- self.prediction_interval = Time.multiply(Extensions.to_time_span(self.resolution), 5) ## Arbitrary
- self._symbol_data_by_symbol = {}
-
- def update(self, algorithm, data):
- insights = []
-
- ## Loop through all Symbol Data objects
- for symbol, symbol_data in self._symbol_data_by_symbol.items():
- ## Evaluate whether or not the price jump is expected to rebound
- if not symbol_data.is_trend(data):
- continue
-
- ## Emit insights accordingly to the price jump sign
- direction = InsightDirection.DOWN if symbol_data.price_jump > 0 else InsightDirection.UP
- insights.append(Insight.price(symbol, self.prediction_interval, direction, symbol_data.price_jump, None))
-
- return insights
-
- def on_securities_changed(self, algorithm, changes):
- # Clean up data for removed securities
- for removed in changes.removed_securities:
- symbol_data = self._symbol_data_by_symbol.pop(removed.symbol, None)
- if symbol_data is not None:
- symbol_data.remove_consolidators(algorithm)
-
- symbols = [x.symbol for x in changes.added_securities
- if x.symbol not in self._symbol_data_by_symbol]
-
- history = algorithm.history(symbols, self.lookback, self.resolution)
- if history.empty: return
-
- ## Create and initialize SymbolData objects
- for symbol in symbols:
- symbol_data = SymbolData(algorithm, symbol, self.lookback, self.resolution)
- symbol_data.warm_up_indicators(history.loc[symbol])
- self._symbol_data_by_symbol[symbol] = symbol_data
-
-
-class SymbolData:
- def __init__(self, algorithm, symbol, lookback, resolution):
- self._symbol = symbol
- self.close = 0
- self.last_price = 0
- self.price_jump = 0
- self.consolidator = algorithm.resolve_consolidator(symbol, resolution)
- self.volatility = StandardDeviation(f'{symbol}.std({lookback})', lookback)
- algorithm.register_indicator(symbol, self.volatility, self.consolidator)
-
- def remove_consolidators(self, algorithm):
- algorithm.subscription_manager.remove_consolidator(self._symbol, self.consolidator)
-
- def warm_up_indicators(self, history):
- self.close = history.iloc[-1].close
- for tuple in history.itertuples():
- self.volatility.update(tuple.Index, tuple.close)
-
- def is_trend(self, data):
-
- ## Check for any data events that would return a NoneBar in the Alpha Model Update() method
- if not data.bars.contains_key(self._symbol):
- return False
-
- self.last_price = self.close
- self.close = data.bars[self._symbol].close
- self.price_jump = (self.close / self.last_price) - 1
- return abs(100*self.price_jump) > 3*self.volatility.current.value
diff --git a/fincept-qt/scripts/strategies/alphas/RebalancingLeveragedETFAlpha.py b/fincept-qt/scripts/strategies/alphas/RebalancingLeveragedETFAlpha.py
deleted file mode 100644
index eee76d7b2..000000000
--- a/fincept-qt/scripts/strategies/alphas/RebalancingLeveragedETFAlpha.py
+++ /dev/null
@@ -1,111 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-41404465
-# Category: Alpha Model
-# Description: Alpha Benchmark Strategy capitalizing on ETF rebalancing causing momentum during trending markets
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Alpha Benchmark Strategy capitalizing on ETF rebalancing causing momentum during trending markets.
-### </summary>
-### <meta name="tag" content="alphastream" />
-### <meta name="tag" content="etf" />
-### <meta name="tag" content="algorithm framework" />
-class RebalancingLeveragedETFAlpha(QCAlgorithm):
- ''' Alpha Streams: Benchmark Alpha: Leveraged ETF Rebalancing
- Strategy by Prof. Shum, reposted by Ernie Chan.
- Source: http://epchan.blogspot.com/2012/10/a-leveraged-etfs-strategy.html'''
-
- def initialize(self):
-
- self.set_start_date(2017, 6, 1)
- self.set_end_date(2018, 8, 1)
- self.set_cash(100000)
-
- underlying = ["SPY","QLD","DIA","IJR","MDY","IWM","QQQ","IYE","EEM","IYW","EFA","GAZB","SLV","IEF","IYM","IYF","IYH","IYR","IYC","IBB","FEZ","USO","TLT"]
- ultra_long = ["SSO","UGL","DDM","SAA","MZZ","UWM","QLD","DIG","EET","ROM","EFO","BOIL","AGQ","UST","UYM","UYG","RXL","URE","UCC","BIB","ULE","UCO","UBT"]
- ultra_short = ["SDS","GLL","DXD","SDD","MVV","TWM","QID","DUG","EEV","REW","EFU","KOLD","ZSL","PST","SMN","SKF","RXD","SRS","SCC","BIS","EPV","SCO","TBT"]
-
- groups = []
- for i in range(len(underlying)):
- group = ETFGroup(self.add_equity(underlying[i], Resolution.MINUTE).symbol,
- self.add_equity(ultra_long[i], Resolution.MINUTE).symbol,
- self.add_equity(ultra_short[i], Resolution.MINUTE).symbol)
- groups.append(group)
-
- # Manually curated universe
- self.set_universe_selection(ManualUniverseSelectionModel())
- # Select the demonstration alpha model
- self.set_alpha(RebalancingLeveragedETFAlphaModel(groups))
-
- # Equally weigh securities in portfolio, based on insights
- self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())
-
- # Set Immediate Execution Model
- self.set_execution(ImmediateExecutionModel())
-
- # Set Null Risk Management Model
- self.set_risk_management(NullRiskManagementModel())
-
-
-class RebalancingLeveragedETFAlphaModel(AlphaModel):
-
- '''
- If the underlying ETF has experienced a return >= 1% since the previous day's close up to the current time at 14:15,
- then buy it's ultra ETF right away, and exit at the close. If the return is <= -1%, sell it's ultra-short ETF.
- '''
-
- def __init__(self, ETFgroups):
-
- self.etfgroups = ETFgroups
- self.date = datetime.min.date
- self.name = "RebalancingLeveragedETFAlphaModel"
-
- def update(self, algorithm, data):
- '''Scan to see if the returns are greater than 1% at 2.15pm to emit an insight.'''
-
- insights = []
- magnitude = 0.0005
- # Paper suggests leveraged ETF's rebalance from 2.15pm - to close
- # giving an insight period of 105 minutes.
- period = timedelta(minutes=105)
-
- # Get yesterday's close price at the market open
- if algorithm.time.date() != self.date:
- self.date = algorithm.time.date()
- # Save yesterday's price and reset the signal
- for group in self.etfgroups:
- history = algorithm.history([group.underlying], 1, Resolution.DAILY)
- group.yesterday_close = None if history.empty else history.loc[str(group.underlying)]['close'][0]
-
- # Check if the returns are > 1% at 14.15
- if algorithm.time.hour == 14 and algorithm.time.minute == 15:
- for group in self.etfgroups:
- if group.yesterday_close == 0 or group.yesterday_close is None: continue
- returns = round((algorithm.portfolio[group.underlying].price - group.yesterday_close) / group.yesterday_close, 10)
- if returns > 0.01:
- insights.append(Insight.price(group.ultra_long, period, InsightDirection.UP, magnitude))
- elif returns < -0.01:
- insights.append(Insight.price(group.ultra_short, period, InsightDirection.DOWN, magnitude))
-
- return insights
-
-class ETFGroup:
- '''
- Group the underlying ETF and it's ultra ETFs
- Args:
- underlying: The underlying index ETF
- ultra_long: The long-leveraged version of underlying ETF
- ultra_short: The short-leveraged version of the underlying ETF
- '''
- def __init__(self,underlying, ultra_long, ultra_short):
- self.underlying = underlying
- self.ultra_long = ultra_long
- self.ultra_short = ultra_short
- self.yesterday_close = 0
diff --git a/fincept-qt/scripts/strategies/alphas/ShareClassMeanReversionAlpha.py b/fincept-qt/scripts/strategies/alphas/ShareClassMeanReversionAlpha.py
deleted file mode 100644
index de1b2ef1b..000000000
--- a/fincept-qt/scripts/strategies/alphas/ShareClassMeanReversionAlpha.py
+++ /dev/null
@@ -1,150 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-B44500AA
-# Category: Alpha Model
-# Description: Initialize helper variables for the algorithm
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-#
-# A number of companies publicly trade two different classes of shares
-# in US equity markets. If both assets trade with reasonable volume, then
-# the underlying driving forces of each should be similar or the same. Given
-# this, we can create a relatively dollar-neutral long/short portfolio using
-# the dual share classes. Theoretically, any deviation of this portfolio from
-# its mean-value should be corrected, and so the motivating idea is based on
-# mean-reversion. Using a Simple Moving Average indicator, we can
-# compare the value of this portfolio against its SMA and generate insights
-# to buy the under-valued symbol and sell the over-valued symbol.
-#
-# This alpha is part of the Benchmark Alpha Series created by QuantConnect which are open
-# sourced so the community and client funds can see an example of an alpha.
-#
-
-class ShareClassMeanReversionAlpha(QCAlgorithm):
-
- def initialize(self):
-
- self.set_start_date(2019, 1, 1) #Set Start Date
- self.set_cash(100000) #Set Strategy Cash
- self.set_warm_up(20)
-
- ## Setup Universe settings and tickers to be used
- tickers = ['VIA','VIAB']
- self.universe_settings.resolution = Resolution.MINUTE
- symbols = [ Symbol.create(ticker, SecurityType.EQUITY, Market.USA) for ticker in tickers]
- self.set_security_initializer(lambda security: security.set_fee_model(ConstantFeeModel(0))) ## Set $0 fees to mimic High-Frequency Trading
-
- ## Set Manual Universe Selection
- self.set_universe_selection( ManualUniverseSelectionModel(symbols) )
-
- ## Set Custom Alpha Model
- self.set_alpha(ShareClassMeanReversionAlphaModel(tickers = tickers))
-
- ## Set Equal Weighting Portfolio Construction Model
- self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())
-
- ## Set Immediate Execution Model
- self.set_execution(ImmediateExecutionModel())
-
- ## Set Null Risk Management Model
- self.set_risk_management(NullRiskManagementModel())
-
-
-class ShareClassMeanReversionAlphaModel(AlphaModel):
- ''' Initialize helper variables for the algorithm'''
-
- def __init__(self, *args, **kwargs):
- self.sma = SimpleMovingAverage(10)
- self.position_window = RollingWindow[float](2)
- self.alpha = None
- self.beta = None
- if 'tickers' not in kwargs:
- raise Exception('ShareClassMeanReversionAlphaModel: Missing argument: "tickers"')
- self.tickers = kwargs['tickers']
- self.position_value = None
- self.invested = False
- self.liquidate = 'liquidate'
- self.long_symbol = self.tickers[0]
- self.short_symbol = self.tickers[1]
- self.resolution = kwargs['resolution'] if 'resolution' in kwargs else Resolution.MINUTE
- self.prediction_interval = Time.multiply(Extensions.to_time_span(self.resolution), 5) ## Arbitrary
- self.insight_magnitude = 0.001
-
- def update(self, algorithm, data):
- insights = []
-
- ## Check to see if either ticker will return a NoneBar, and skip the data slice if so
- for security in algorithm.securities:
- if self.data_event_occured(data, security.key):
- return insights
-
- ## If Alpha and Beta haven't been calculated yet, then do so
- if (self.alpha is None) or (self.beta is None):
- self.calculate_alpha_beta(algorithm, data)
- algorithm.log('Alpha: ' + str(self.alpha))
- algorithm.log('Beta: ' + str(self.beta))
-
- ## If the SMA isn't fully warmed up, then perform an update
- if not self.sma.is_ready:
- self.update_indicators(data)
- return insights
-
- ## Update indicator and Rolling Window for each data slice passed into Update() method
- self.update_indicators(data)
-
- ## Check to see if the portfolio is invested. If no, then perform value comparisons and emit insights accordingly
- if not self.invested:
- if self.position_value >= self.sma.current.value:
- insights.append(Insight(self.long_symbol, self.prediction_interval, InsightType.PRICE, InsightDirection.DOWN, self.insight_magnitude, None))
- insights.append(Insight(self.short_symbol, self.prediction_interval, InsightType.PRICE, InsightDirection.UP, self.insight_magnitude, None))
-
- ## Reset invested boolean
- self.invested = True
-
- elif self.position_value < self.sma.current.value:
- insights.append(Insight(self.long_symbol, self.prediction_interval, InsightType.PRICE, InsightDirection.UP, self.insight_magnitude, None))
- insights.append(Insight(self.short_symbol, self.prediction_interval, InsightType.PRICE, InsightDirection.DOWN, self.insight_magnitude, None))
-
- ## Reset invested boolean
- self.invested = True
-
- ## If the portfolio is invested and crossed back over the SMA, then emit flat insights
- elif self.invested and self.crossed_mean():
- ## Reset invested boolean
- self.invested = False
-
- return Insight.group(insights)
-
- def data_event_occured(self, data, symbol):
- ## Helper function to check to see if data slice will contain a symbol
- if data.splits.contains_key(symbol) or \
- data.dividends.contains_key(symbol) or \
- data.delistings.contains_key(symbol) or \
- data.symbol_changed_events.contains_key(symbol):
- return True
-
- def update_indicators(self, data):
- ## Calculate position value and update the SMA indicator and Rolling Window
- self.position_value = (self.alpha * data[self.long_symbol].close) - (self.beta * data[self.short_symbol].close)
- self.sma.update(data[self.long_symbol].end_time, self.position_value)
- self.position_window.add(self.position_value)
-
- def crossed_mean(self):
- ## Check to see if the position value has crossed the SMA and then return a boolean value
- if (self.position_window[0] >= self.sma.current.value) and (self.position_window[1] < self.sma.current.value):
- return True
- elif (self.position_window[0] < self.sma.current.value) and (self.position_window[1] >= self.sma.current.value):
- return True
- else:
- return False
-
- def calculate_alpha_beta(self, algorithm, data):
- ## Calculate Alpha and Beta, the initial number of shares for each security needed to achieve a 50/50 weighting
- self.alpha = algorithm.calculate_order_quantity(self.long_symbol, 0.5)
- self.beta = algorithm.calculate_order_quantity(self.short_symbol, 0.5)
diff --git a/fincept-qt/scripts/strategies/alphas/SykesShortMicroCapAlpha.py b/fincept-qt/scripts/strategies/alphas/SykesShortMicroCapAlpha.py
deleted file mode 100644
index a90b75faf..000000000
--- a/fincept-qt/scripts/strategies/alphas/SykesShortMicroCapAlpha.py
+++ /dev/null
@@ -1,97 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-EEAA6B87
-# Category: Alpha Model
-# Description: Alpha Streams: Benchmark Alpha: Identify "pumped" penny stocks and predict that the price of a "pumped" penny stock r...
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-from Selection.FundamentalUniverseSelectionModel import FundamentalUniverseSelectionModel
-
-class SykesShortMicroCapAlpha(QCAlgorithm):
- ''' Alpha Streams: Benchmark Alpha: Identify "pumped" penny stocks and predict that the price of a "pumped" penny stock reverts to mean
-
- This alpha is part of the Benchmark Alpha Series created by QuantConnect which are open
- sourced so the community and client funds can see an example of an alpha.'''
-
- def initialize(self):
-
- self.set_start_date(2018, 1, 1)
- self.set_cash(100000)
-
- # Set zero transaction fees
- self.set_security_initializer(lambda security: security.set_fee_model(ConstantFeeModel(0)))
-
- # select stocks using PennyStockUniverseSelectionModel
- self.universe_settings.resolution = Resolution.DAILY
- self.universe_settings.schedule.on(self.date_rules.month_start())
- self.set_universe_selection(PennyStockUniverseSelectionModel())
-
- # Use SykesShortMicroCapAlphaModel to establish insights
- self.set_alpha(SykesShortMicroCapAlphaModel())
-
- # Equally weigh securities in portfolio, based on insights
- self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())
-
- # Set Immediate Execution Model
- self.set_execution(ImmediateExecutionModel())
-
- # Set Null Risk Management Model
- self.set_risk_management(NullRiskManagementModel())
-
-
-class SykesShortMicroCapAlphaModel(AlphaModel):
- '''Uses ranking of intraday percentage difference between open price and close price to create magnitude and direction prediction for insights'''
-
- def __init__(self, *args, **kwargs):
- lookback = kwargs['lookback'] if 'lookback' in kwargs else 1
- resolution = kwargs['resolution'] if 'resolution' in kwargs else Resolution.DAILY
- self.prediction_interval = Time.multiply(Extensions.to_time_span(resolution), lookback)
- self.number_of_stocks = kwargs['number_of_stocks'] if 'number_of_stocks' in kwargs else 10
-
- def update(self, algorithm, data):
- insights = []
- symbols_ret = dict()
-
- for security in algorithm.active_securities.values:
- if security.has_data:
- open_ = security.open
- if open_ != 0:
- # Intraday price change for penny stocks
- symbols_ret[security.symbol] = security.close / open_ - 1
-
- # Rank penny stocks on one day price change and retrieve list of ten "pumped" penny stocks
- pumped_stocks = dict(sorted(symbols_ret.items(),
- key = lambda kv: (-round(kv[1], 6), kv[0]))[:self.number_of_stocks])
-
- # Emit "down" insight for "pumped" penny stocks
- for symbol, value in pumped_stocks.items():
- insights.append(Insight.price(symbol, self.prediction_interval, InsightDirection.DOWN, abs(value), None))
-
- return insights
-
-
-class PennyStockUniverseSelectionModel(FundamentalUniverseSelectionModel):
- '''Defines a universe of penny stocks, as a universe selection model for the framework algorithm:
- The stocks must have fundamental data
- The stock must have positive previous-day close price
- The stock must have volume between $1000000 and $10000 on the previous trading day
- The stock must cost less than $5'''
- def __init__(self):
- super().__init__()
-
- # Number of stocks in Coarse Universe
- self.number_of_symbols_coarse = 500
-
- def select(self, algorithm, fundamental):
- # sort the stocks by dollar volume and take the top 500
- top = sorted([x for x in fundamental if x.has_fundamental_data
- and 5 > x.price > 0
- and 1000000 > x.volume > 10000],
- key=lambda x: x.dollar_volume, reverse=True)[:self.number_of_symbols_coarse]
-
- return [x.symbol for x in top]
diff --git a/fincept-qt/scripts/strategies/alphas/TriangleExchangeRateArbitrageAlpha.py b/fincept-qt/scripts/strategies/alphas/TriangleExchangeRateArbitrageAlpha.py
deleted file mode 100644
index 8ea04be7d..000000000
--- a/fincept-qt/scripts/strategies/alphas/TriangleExchangeRateArbitrageAlpha.py
+++ /dev/null
@@ -1,90 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-217A291D
-# Category: Alpha Model
-# Description: Triangle Exchange Rate Arbitrage Alpha
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-#
-# In a perfect market, you could buy 100 EUR worth of USD, sell 100 EUR worth of GBP,
-# and then use the GBP to buy USD and wind up with the same amount in USD as you received when
-# you bought them with EUR. This relationship is expressed by the Triangle Exchange Rate, which is
-#
-# Triangle Exchange Rate = (A/B) * (B/C) * (C/A)
-#
-# where (A/B) is the exchange rate of A-to-B. In a perfect market, TER = 1, and so when
-# there is a mispricing in the market, then TER will not be 1 and there exists an arbitrage opportunity.
-#
-# This alpha is part of the Benchmark Alpha Series created by QuantConnect which are open sourced so the community and client funds can see an example of an alpha.
-#
-
-class TriangleExchangeRateArbitrageAlpha(QCAlgorithm):
-
- def initialize(self):
-
- self.set_start_date(2019, 2, 1) #Set Start Date
- self.set_cash(100000) #Set Strategy Cash
-
- # Set zero transaction fees
- self.set_security_initializer(lambda security: security.set_fee_model(ConstantFeeModel(0)))
-
- ## Select trio of currencies to trade where
- ## Currency A = USD
- ## Currency B = EUR
- ## Currency C = GBP
- currencies = ['EURUSD','EURGBP','GBPUSD']
- symbols = [ Symbol.create(currency, SecurityType.FOREX, Market.OANDA) for currency in currencies]
-
- ## Manual universe selection with tick-resolution data
- self.universe_settings.resolution = Resolution.MINUTE
- self.set_universe_selection( ManualUniverseSelectionModel(symbols) )
-
- self.set_alpha(ForexTriangleArbitrageAlphaModel(Resolution.MINUTE, symbols))
-
- ## Set Equal Weighting Portfolio Construction Model
- self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())
-
- ## Set Immediate Execution Model
- self.set_execution(ImmediateExecutionModel())
-
- ## Set Null Risk Management Model
- self.set_risk_management(NullRiskManagementModel())
-
-
-class ForexTriangleArbitrageAlphaModel(AlphaModel):
-
- def __init__(self, insight_resolution, symbols):
- self.insight_period = Time.multiply(Extensions.to_time_span(insight_resolution), 5)
- self._symbols = symbols
-
- def update(self, algorithm, data):
- ## Check to make sure all currency symbols are present
- if len(data.keys()) < 3:
- return []
-
- ## Extract QuoteBars for all three Forex securities
- bar_a = data[self._symbols[0]]
- bar_b = data[self._symbols[1]]
- bar_c = data[self._symbols[2]]
-
- ## Calculate the triangle exchange rate
- ## Bid(Currency A -> Currency B) * Bid(Currency B -> Currency C) * Bid(Currency C -> Currency A)
- ## If exchange rates are priced perfectly, then this yield 1. If it is different than 1, then an arbitrage opportunity exists
- triangle_rate = bar_a.ask.close / bar_b.bid.close / bar_c.ask.close
-
- ## If the triangle rate is significantly different than 1, then emit insights
- if triangle_rate > 1.0005:
- return Insight.group(
- [
- Insight.price(self._symbols[0], self.insight_period, InsightDirection.UP, 0.0001, None),
- Insight.price(self._symbols[1], self.insight_period, InsightDirection.DOWN, 0.0001, None),
- Insight.price(self._symbols[2], self.insight_period, InsightDirection.UP, 0.0001, None)
- ] )
-
- return []
diff --git a/fincept-qt/scripts/strategies/alphas/TripleLeverageETFPairVolatilityDecayAlpha.py b/fincept-qt/scripts/strategies/alphas/TripleLeverageETFPairVolatilityDecayAlpha.py
deleted file mode 100644
index 050dfd77d..000000000
--- a/fincept-qt/scripts/strategies/alphas/TripleLeverageETFPairVolatilityDecayAlpha.py
+++ /dev/null
@@ -1,79 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-A6C1E2B9
-# Category: Alpha Model
-# Description: Rebalance a pair of 3x leveraged ETFs and predict that the value of both ETFs in each pair will decrease.
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-#
-# Leveraged ETFs (LETF) promise a fixed leverage ratio with respect to an underlying asset or an index.
-# A Triple-Leveraged ETF allows speculators to amplify their exposure to the daily returns of an underlying index by a factor of 3.
-#
-# Increased volatility generally decreases the value of a LETF over an extended period of time as daily compounding is amplified.
-#
-# This alpha emits short-biased insight to capitalize on volatility decay for each listed pair of TL-ETFs, by rebalancing the
-# ETFs with equal weights each day.
-#
-# This alpha is part of the Benchmark Alpha Series created by QuantConnect which are open sourced so the community and client funds can see an example of an alpha.
-#
-
-class TripleLeverageETFPairVolatilityDecayAlpha(QCAlgorithm):
-
- def initialize(self):
-
- self.set_start_date(2018, 1, 1)
-
- self.set_cash(100000)
-
- # Set zero transaction fees
- self.set_security_initializer(lambda security: security.set_fee_model(ConstantFeeModel(0)))
-
- # 3X ETF pair tickers
- ultra_long = Symbol.create("UGLD", SecurityType.EQUITY, Market.USA)
- ultra_short = Symbol.create("DGLD", SecurityType.EQUITY, Market.USA)
-
- # Manually curated universe
- self.universe_settings.resolution = Resolution.DAILY
- self.set_universe_selection(ManualUniverseSelectionModel([ultra_long, ultra_short]))
-
- # Select the demonstration alpha model
- self.set_alpha(RebalancingTripleLeveragedETFAlphaModel(ultra_long, ultra_short))
-
- ## Set Equal Weighting Portfolio Construction Model
- self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())
-
- ## Set Immediate Execution Model
- self.set_execution(ImmediateExecutionModel())
-
- ## Set Null Risk Management Model
- self.set_risk_management(NullRiskManagementModel())
-
-
-class RebalancingTripleLeveragedETFAlphaModel(AlphaModel):
- '''
- Rebalance a pair of 3x leveraged ETFs and predict that the value of both ETFs in each pair will decrease.
- '''
-
- def __init__(self, ultra_long, ultra_short):
- # Giving an insight period 1 days.
- self.period = timedelta(1)
-
- self.magnitude = 0.001
- self.ultra_long = ultra_long
- self.ultra_short = ultra_short
-
- self.name = "RebalancingTripleLeveragedETFAlphaModel"
-
- def update(self, algorithm, data):
-
- return Insight.group(
- [
- Insight.price(self.ultra_long, self.period, InsightDirection.DOWN, self.magnitude),
- Insight.price(self.ultra_short, self.period, InsightDirection.DOWN, self.magnitude)
- ] )
diff --git a/fincept-qt/scripts/strategies/alphas/VIXDualThrustAlpha.py b/fincept-qt/scripts/strategies/alphas/VIXDualThrustAlpha.py
deleted file mode 100644
index 630c2f584..000000000
--- a/fincept-qt/scripts/strategies/alphas/VIXDualThrustAlpha.py
+++ /dev/null
@@ -1,175 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-7DFAE1BB
-# Category: Alpha Model
-# Description: Alpha model that uses dual-thrust strategy to create insights
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-#
-# This is a demonstration algorithm. It trades UVXY.
-# Dual Thrust alpha model is used to produce insights.
-# Those input parameters have been chosen that gave acceptable results on a series
-# of random backtests run for the period from Oct, 2016 till Feb, 2019.
-#
-
-class VIXDualThrustAlpha(QCAlgorithm):
-
- def initialize(self):
-
- # -- STRATEGY INPUT PARAMETERS --
- self.k1 = 0.63
- self.k2 = 0.63
- self.range_period = 20
- self.consolidator_bars = 30
-
- # Settings
- self.set_start_date(2018, 10, 1)
- self.set_security_initializer(lambda security: security.set_fee_model(ConstantFeeModel(0)))
- self.set_brokerage_model(BrokerageName.INTERACTIVE_BROKERS_BROKERAGE, AccountType.MARGIN)
-
- # Universe Selection
- self.universe_settings.resolution = Resolution.MINUTE # it's minute by default, but lets leave this param here
- symbols = [Symbol.create("SPY", SecurityType.EQUITY, Market.USA)]
- self.set_universe_selection(ManualUniverseSelectionModel(symbols))
-
- # Warming up
- resolution_in_time_span = Extensions.to_time_span(self.universe_settings.resolution)
- warm_up_time_span = Time.multiply(resolution_in_time_span, self.consolidator_bars)
- self.set_warm_up(warm_up_time_span)
-
- # Alpha Model
- self.set_alpha(DualThrustAlphaModel(self.k1, self.k2, self.range_period, self.universe_settings.resolution, self.consolidator_bars))
-
- ## Portfolio Construction
- self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())
-
- ## Execution
- self.set_execution(ImmediateExecutionModel())
-
- ## Risk Management
- self.set_risk_management(MaximumDrawdownPercentPerSecurity(0.03))
-
-
-class DualThrustAlphaModel(AlphaModel):
- '''Alpha model that uses dual-thrust strategy to create insights
- https://medium.com/@FMZ_Quant/dual-thrust-trading-strategy-2cc74101a626
- or here:
- https://www.quantconnect.com/tutorials/strategy-library/dual-thrust-trading-algorithm'''
-
- def __init__(self,
- k1,
- k2,
- range_period,
- resolution = Resolution.DAILY,
- bars_to_consolidate = 1):
- '''Initializes a new instance of the class
- Args:
- k1: Coefficient for upper band
- k2: Coefficient for lower band
- range_period: Amount of last bars to calculate the range
- resolution: The resolution of data sent into the EMA indicators
- bars_to_consolidate: If we want alpha to work on trade bars whose length is different
- from the standard resolution - 1m 1h etc. - we need to pass this parameters along
- with proper data resolution'''
-
- # coefficient that used to determine upper and lower borders of a breakout channel
- self.k1 = k1
- self.k2 = k2
-
- # period the range is calculated over
- self.range_period = range_period
-
- # initialize with empty dict.
- self._symbol_data_by_symbol = dict()
-
- # time for bars we make the calculations on
- resolution_in_time_span = Extensions.to_time_span(resolution)
- self.consolidator_time_span = Time.multiply(resolution_in_time_span, bars_to_consolidate)
-
- # in 5 days after emission an insight is to be considered expired
- self.period = timedelta(5)
-
- def update(self, algorithm, data):
- insights = []
-
- for symbol, symbol_data in self._symbol_data_by_symbol.items():
- if not symbol_data.is_ready:
- continue
-
- holding = algorithm.portfolio[symbol]
- price = algorithm.securities[symbol].price
-
- # buying condition
- # - (1) price is above upper line
- # - (2) and we are not long. this is a first time we crossed the line lately
- if price > symbol_data.upper_line and not holding.is_long:
- insight_close_time_utc = algorithm.utc_time + self.period
- insights.append(Insight.price(symbol, insight_close_time_utc, InsightDirection.UP))
-
- # selling condition
- # - (1) price is lower that lower line
- # - (2) and we are not short. this is a first time we crossed the line lately
- if price < symbol_data.lower_line and not holding.is_short:
- insight_close_time_utc = algorithm.utc_time + self.period
- insights.append(Insight.price(symbol, insight_close_time_utc, InsightDirection.DOWN))
-
- return insights
-
- def on_securities_changed(self, algorithm, changes):
- # added
- for symbol in [x.symbol for x in changes.added_securities]:
- if symbol not in self._symbol_data_by_symbol:
- # add symbol/symbol_data pair to collection
- symbol_data = self.SymbolData(symbol, self.k1, self.k2, self.range_period, self.consolidator_time_span)
- self._symbol_data_by_symbol[symbol] = symbol_data
- # register consolidator
- algorithm.subscription_manager.add_consolidator(symbol, symbol_data.get_consolidator())
-
- # removed
- for symbol in [x.symbol for x in changes.removed_securities]:
- symbol_data = self._symbol_data_by_symbol.pop(symbol, None)
- if symbol_data is None:
- algorithm.error("Unable to remove data from collection: DualThrustAlphaModel")
- else:
- # unsubscribe consolidator from data updates
- algorithm.subscription_manager.remove_consolidator(symbol, symbol_data.get_consolidator())
-
-
- class SymbolData:
- '''Contains data specific to a symbol required by this model'''
- def __init__(self, symbol, k1, k2, range_period, consolidator_resolution):
-
- self.symbol = symbol
- self.range_window = RollingWindow[TradeBar](range_period)
- self.consolidator = TradeBarConsolidator(consolidator_resolution)
-
- def on_data_consolidated(sender, consolidated):
- # add new tradebar to
- self.range_window.add(consolidated)
-
- if self.range_window.is_ready:
- hh = max([x.high for x in self.range_window])
- hc = max([x.close for x in self.range_window])
- lc = min([x.close for x in self.range_window])
- ll = min([x.low for x in self.range_window])
-
- range = max([hh - lc, hc - ll])
- self.upper_line = consolidated.close + k1 * range
- self.lower_line = consolidated.close - k2 * range
-
- # event fired at new consolidated trade bar
- self.consolidator.data_consolidated += on_data_consolidated
-
- # Returns the interior consolidator
- def get_consolidator(self):
- return self.consolidator
-
- @property
- def is_ready(self):
- return self.range_window.is_ready
diff --git a/fincept-qt/scripts/strategies/alphas/__init__.py b/fincept-qt/scripts/strategies/alphas/__init__.py
deleted file mode 100644
index 59f512603..000000000
--- a/fincept-qt/scripts/strategies/alphas/__init__.py
+++ /dev/null
@@ -1,40 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Alphas Shim
-# Re-exports from fincept_engine.framework.alphas + dynamic submodule stubs
-# ============================================================================
-
-import sys, os, types
-
-_parent = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
-if _parent not in sys.path:
- sys.path.insert(0, _parent)
-
-from fincept_engine.algorithm_imports import (
- AlphaModel, ConstantAlphaModel, CompositeAlphaModel,
- Insight, InsightDirection, InsightType, InsightScore,
- InsightCollection
-)
-from fincept_engine.framework.alphas import (
- RsiAlphaModel, HistoricalReturnsAlphaModel, EmaCrossAlphaModel,
- MacdAlphaModel, PairsTradingAlphaModel, BasePairsTradingAlphaModel,
- PearsonCorrelationPairsTradingAlphaModel
-)
-
-# Dynamic submodule stubs: enables `from Alphas.RsiAlphaModel import RsiAlphaModel`
-_submodules = {
- 'RsiAlphaModel': {'RsiAlphaModel': RsiAlphaModel},
- 'HistoricalReturnsAlphaModel': {'HistoricalReturnsAlphaModel': HistoricalReturnsAlphaModel},
- 'EmaCrossAlphaModel': {'EmaCrossAlphaModel': EmaCrossAlphaModel},
- 'MacdAlphaModel': {'MacdAlphaModel': MacdAlphaModel},
- 'ConstantAlphaModel': {'ConstantAlphaModel': ConstantAlphaModel},
- 'PairsTradingAlphaModel': {'PairsTradingAlphaModel': PairsTradingAlphaModel},
- 'BasePairsTradingAlphaModel': {'BasePairsTradingAlphaModel': BasePairsTradingAlphaModel},
- 'CompositeAlphaModel': {'CompositeAlphaModel': CompositeAlphaModel},
- 'PearsonCorrelationPairsTradingAlphaModel': {'PearsonCorrelationPairsTradingAlphaModel': PearsonCorrelationPairsTradingAlphaModel},
-}
-
-for _name, _attrs in _submodules.items():
- _mod = types.ModuleType(f'Alphas.{_name}')
- for _attr_name, _attr_val in _attrs.items():
- setattr(_mod, _attr_name, _attr_val)
- sys.modules[f'Alphas.{_name}'] = _mod
diff --git a/fincept-qt/scripts/strategies/benchmarks/BasicTemplateBenchmark.py b/fincept-qt/scripts/strategies/benchmarks/BasicTemplateBenchmark.py
deleted file mode 100644
index bab47de94..000000000
--- a/fincept-qt/scripts/strategies/benchmarks/BasicTemplateBenchmark.py
+++ /dev/null
@@ -1,31 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-B103DBA0
-# Category: Benchmark
-# Description: Benchmark Algorithm: The minimalist basic template algorithm benchmark strategy
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Benchmark Algorithm: The minimalist basic template algorithm benchmark strategy.
-### </summary>
-### <remarks>
-### All new projects in the cloud are created with the basic template algorithm. It uses a minute algorithm
-### </remarks>
-class BasicTemplateBenchmark(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2000, 1, 1)
- self.set_end_date(2022, 1, 1)
- self.set_benchmark(lambda x: 1)
- self.add_equity("SPY")
-
- def on_data(self, data):
- if not self.portfolio.invested:
- self.set_holdings("SPY", 1)
- self.debug("Purchased Stock")
diff --git a/fincept-qt/scripts/strategies/benchmarks/CoarseFineUniverseSelectionBenchmark.py b/fincept-qt/scripts/strategies/benchmarks/CoarseFineUniverseSelectionBenchmark.py
deleted file mode 100644
index 11eeee00c..000000000
--- a/fincept-qt/scripts/strategies/benchmarks/CoarseFineUniverseSelectionBenchmark.py
+++ /dev/null
@@ -1,61 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-5B90E12B
-# Category: Benchmark
-# Description: Coarse Fine Universe Selection Benchmark
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-class CoarseFineUniverseSelectionBenchmark(QCAlgorithm):
-
- def initialize(self):
-
- self.set_start_date(2017, 11, 1)
- self.set_end_date(2018, 3, 1)
- self.set_cash(50000)
-
- self.universe_settings.resolution = Resolution.MINUTE
-
- self.add_universe(self.coarse_selection_function, self.fine_selection_function)
-
- self.number_of_symbols = 150
- self.number_of_symbols_fine = 40
- self._changes = None
-
- # sort the data by daily dollar volume and take the top 'NumberOfSymbols'
- def coarse_selection_function(self, coarse):
-
- selected = [x for x in coarse if (x.has_fundamental_data)]
- # sort descending by daily dollar volume
- sorted_by_dollar_volume = sorted(selected, key=lambda x: x.dollar_volume, reverse=True)
-
- # return the symbol objects of the top entries from our sorted collection
- return [ x.symbol for x in sorted_by_dollar_volume[:self.number_of_symbols] ]
-
- # sort the data by P/E ratio and take the top 'NumberOfSymbolsFine'
- def fine_selection_function(self, fine):
- # sort descending by P/E ratio
- sorted_by_pe_ratio = sorted(fine, key=lambda x: x.valuation_ratios.pe_ratio, reverse=True)
- # take the top entries from our sorted collection
- return [ x.symbol for x in sorted_by_pe_ratio[:self.number_of_symbols_fine] ]
-
- def on_data(self, data):
- # if we have no changes, do nothing
- if self._changes is None: return
-
- # liquidate removed securities
- for security in self._changes.removed_securities:
- if security.invested:
- self.liquidate(security.symbol)
-
- for security in self._changes.added_securities:
- self.set_holdings(security.symbol, 0.02)
- self._changes = None
-
- def on_securities_changed(self, changes):
- self._changes = changes
diff --git a/fincept-qt/scripts/strategies/benchmarks/EmptyEquityAndOptions400Benchmark.py b/fincept-qt/scripts/strategies/benchmarks/EmptyEquityAndOptions400Benchmark.py
deleted file mode 100644
index 6e138fe19..000000000
--- a/fincept-qt/scripts/strategies/benchmarks/EmptyEquityAndOptions400Benchmark.py
+++ /dev/null
@@ -1,68 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-9C878F2C
-# Category: Benchmark
-# Description: Benchmark Algorithm: Loading and synchronization of 500 equity minute symbols and their options
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Benchmark Algorithm: Loading and synchronization of 500 equity minute symbols and their options.
-### </summary>
-class EmptyEquityAndOptions400Benchmark(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2022, 5, 11)
- self.set_end_date(2022, 5, 12)
- self.equity_symbols = [
-
-"MARK", "TSN", "DT", "RDW", "CVE", "NXPI", "FIVN", "CLX", "SPXL", "BKSY", "NUGT", "CF", "NEGG",
-"RH", "SIRI", "ITUB", "CSX", "AUR", "LIDR", "CMPS", "DHI", "GLW", "NTES", "CIFR", "S", "HSBC",
-"HIPO", "WTRH", "AMRN", "BIIB", "RIO", "EDIT", "TEAM", "CNK", "BUD", "MILE", "AEHR", "DOCN",
-"CLSK", "BROS", "MLCO", "SBLK", "ICLN", "OPK", "CNC", "SKX", "SESN", "VRM", "ASML", "BBAI",
-"HON", "MRIN", "BLMN", "NTNX", "POWW", "FOUR", "HOG", "GOGO", "MGNI", "GENI", "XPDI",
-"DG", "PSX", "RRC", "CORT", "MET", "UMC", "INMD", "RBAC", "ISRG", "BOX", "DVAX", "CRVS", "HLT",
-"BKNG", "BENE", "CLVS", "ESSC", "PTRA", "BE", "FPAC", "YETI", "DOCS", "DB", "EBON", "RDS.B",
-"ERIC", "BSIG", "INTU", "MNTS", "BCTX", "BLU", "FIS", "MAC", "WMB", "TTWO", "ARDX", "SWBI",
-"ELY", "INDA", "REAL", "ACI", "APRN", "BHP", "CPB", "SLQT", "ARKF", "TSP", "OKE", "NVTA", "META",
-"CSTM", "KMX", "IBB", "AGEN", "WOOF", "MJ", "HYZN", "RSI", "JCI", "EXC", "HPE", "SI", "WPM",
-"PRTY", "BBD", "FVRR", "CANO", "INDI", "MDLZ", "KOLD", "AMBA", "SOXS", "RSX", "ZEN", "PUBM",
-"VLDR", "CI", "ISEE", "GEO", "BKR", "DHR", "GRPN", "NRXP", "ACN", "MAT", "BODY", "ENDP",
-"SHPW", "AVIR", "GPN", "BILL", "BZ", "CERN", "ARVL", "DNMR", "NTR", "FSM", "BMBL", "PAAS",
-"INVZ", "ANF", "CL", "XP", "CS", "KD", "WW", "AHT", "GRTX", "XLC", "BLDP", "HTA", "APT", "BYSI",
-"ENB", "TRIT", "VTNR", "AVCT", "SLI", "CP", "CAH", "ALLY", "FIGS", "PXD", "TPX", "ZI", "BKLN", "SKIN",
-"LNG", "NU", "CX", "GSM", "NXE", "REI", "MNDT", "IP", "BLOK", "IAA", "TIP", "MCHP", "EVTL", "BIGC",
-"IGV", "LOTZ", "EWC", "DRI", "PSTG", "APLS", "KIND", "BBIO", "APPH", "FIVE", "LSPD", "SHAK",
-"COMM", "NAT", "VFC", "AMT", "VRTX", "RGS", "DD", "GBIL", "LICY", "ACHR", "FLR", "HGEN", "TECL",
-"SEAC", "NVS", "NTAP", "ML", "SBSW", "XRX", "UA", "NNOX", "SFT", "FE", "APP", "KEY", "CDEV",
-"DPZ", "BARK", "SPR", "CNQ", "XL", "AXSM", "ECH", "RNG", "AMLP", "ENG", "BTI", "REKR",
-"STZ", "BK", "HEAR", "LEV", "SKT", "HBI", "ALB", "CAG", "MNKD", "NMM", "BIRD", "CIEN", "SILJ",
-"STNG", "GUSH", "GIS", "PRPL", "SDOW", "GNRC", "ERX", "GES", "CPE", "FBRX", "WM", "ESTC",
-"GOED", "STLD", "LILM", "JNK", "BOIL", "ALZN", "IRBT", "KOPN", "AU", "TPR", "RWLK", "TROX",
-"TMO", "AVDL", "XSPA", "JKS", "PACB", "LOGI", "BLK", "REGN", "CFVI", "EGHT", "ATNF", "PRU",
-"URBN", "KMB", "SIX", "CME", "ENVX", "NVTS", "CELH", "CSIQ", "GSL", "PAA", "WU", "MOMO",
-"TOL", "WEN", "GTE", "EXAS", "GDRX", "PVH", "BFLY", "SRTY", "UDOW", "NCR", "ALTO", "CRTD",
-"GOCO", "ALK", "TTM", "DFS", "VFF", "ANTM", "FREY", "WY", "ACWI", "PNC", "SYY", "SNY", "CRK",
-"SO", "XXII", "PBF", "AER", "RKLY", "SOL", "CND", "MPLX", "JNPR", "FTCV", "CLR", "XHB", "YY",
-"POSH", "HIMS", "LIFE", "XENE", "ADM", "ROST", "MIR", "NRG", "AAP", "SSYS", "KBH", "KKR", "PLAN",
-"DUK", "WIMI", "DBRG", "WSM", "LTHM", "OVV", "CFLT", "EWT", "UNFI", "TX", "EMR", "IMGN", "K",
-"ONON", "UNIT", "LEVI", "ADTX", "UPWK", "DBA", "VOO", "FATH", "URI", "MPW", "JNUG", "RDFN",
-"OSCR", "WOLF", "SYF", "GOGL", "HES", "PHM", "CWEB", "ALDX", "BTWN", "AFL", "PPL", "CIM"
-
- ]
-
- self.set_warm_up(TimeSpan.from_days(1))
- for ticker in self.equity_symbols:
- option = self.add_option(ticker)
- option.set_filter(1, 7, timedelta(0), timedelta(90))
-
- self.add_equity("SPY")
-
- def on_data(self, slice):
- if self.is_warming_up: return
- self.quit("The end!")
diff --git a/fincept-qt/scripts/strategies/benchmarks/EmptyMinute400EquityBenchmark.py b/fincept-qt/scripts/strategies/benchmarks/EmptyMinute400EquityBenchmark.py
deleted file mode 100644
index 75f0dfcb8..000000000
--- a/fincept-qt/scripts/strategies/benchmarks/EmptyMinute400EquityBenchmark.py
+++ /dev/null
@@ -1,381 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-1E0D28D7
-# Category: Benchmark
-# Description: Empty Minute400 Equity Benchmark
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-class EmptyMinute400EquityBenchmark(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2015, 9, 1)
- self.set_end_date(2015, 12, 1)
-
- for symbol in Symbols().equity.all()[:400]:
- self.add_security(SecurityType.EQUITY, symbol)
-
- def on_data(self, data):
- pass
-
-class Symbols(object):
-
- def __init__(self):
- self.equity = self.Equity()
-
- class Equity(object):
- def all(self):
- return [
- "SPY",
- "AAPL",
- "FB",
- "VXX",
- "VRX",
- "NFLX",
- "UVXY",
- "QQQ",
- "IWM",
- "BABA",
- "GILD",
- "XIV",
- "XOM",
- "CVX",
- "MSFT",
- "GE",
- "SLB",
- "JPM",
- "XLE",
- "DIS",
- "AMZN",
- "TWTR",
- "PFE",
- "C",
- "BAC",
- "ABBV",
- "JNJ",
- "HAL",
- "XLV",
- "INTC",
- "WFC",
- "V",
- "YHOO",
- "COP",
- "MYL",
- "AGN",
- "WMT",
- "KMI",
- "MRK",
- "TSLA",
- "GDX",
- "LLY",
- "FCX",
- "CAT",
- "CELG",
- "QCOM",
- "MCD",
- "CMCSA",
- "XOP",
- "CVS",
- "AMGN",
- "DOW",
- "AAL",
- "APC",
- "SUNE",
- "MU",
- "VLO",
- "SBUX",
- "WMB",
- "PG",
- "EOG",
- "DVN",
- "BMY",
- "APA",
- "UNH",
- "EEM",
- "IBM",
- "NKE",
- "T",
- "HD",
- "UNP",
- "DAL",
- "ENDP",
- "CSCO",
- "OXY",
- "MRO",
- "MDT",
- "TXN",
- "WLL",
- "ORCL",
- "GOOGL",
- "UAL",
- "WYNN",
- "MS",
- "HZNP",
- "BIIB",
- "VZ",
- "GM",
- "NBL",
- "TWX",
- "SWKS",
- "JD",
- "HCA",
- "AVGO",
- "YUM",
- "KO",
- "GOOG",
- "GS",
- "PEP",
- "AIG",
- "EMC",
- "BIDU",
- "CLR",
- "PYPL",
- "LVS",
- "SWN",
- "AXP",
- "ATVI",
- "RRC",
- "WBA",
- "MPC",
- "NXPI",
- "ETE",
- "NOV",
- "FOXA",
- "SNDK",
- "DIA",
- "UTX",
- "DD",
- "WDC",
- "AA",
- "M",
- "FXI",
- "RIG",
- "MA",
- "DUST",
- "TGT",
- "AET",
- "EBAY",
- "LUV",
- "EFA",
- "BRK.B",
- "BA",
- "MET",
- "LYB",
- "SVXY",
- "UWTI",
- "HON",
- "HPQ",
- "OAS",
- "ABT",
- "MO",
- "ESRX",
- "TEVA",
- "STX",
- "IBB",
- "F",
- "CBS",
- "TLT",
- "PM",
- "ESV",
- "NE",
- "PSX",
- "SCHW",
- "MON",
- "HES",
- "GPRO",
- "TVIX",
- "MNK",
- "NVDA",
- "NFX",
- "USO",
- "NUGT",
- "EWZ",
- "LOW",
- "UA",
- "TNA",
- "XLY",
- "MMM",
- "PXD",
- "VIAB",
- "MDLZ",
- "NEM",
- "USB",
- "MUR",
- "ETN",
- "FEYE",
- "PTEN",
- "OIH",
- "UPS",
- "CHK",
- "DHR",
- "RAI",
- "TQQQ",
- "CCL",
- "BRCM",
- "DG",
- "JBLU",
- "CRM",
- "ADBE",
- "COG",
- "PBR",
- "HP",
- "BHI",
- "BK",
- "TJX",
- "DE",
- "COF",
- "INCY",
- "DHI",
- "ABC",
- "XLI",
- "ZTS",
- "BP",
- "IYR",
- "PNC",
- "CNX",
- "XLF",
- "LRCX",
- "GG",
- "RDS.A",
- "WFM",
- "TSO",
- "ANTM",
- "KSS",
- "EA",
- "PRU",
- "RAD",
- "WFT",
- "XBI",
- "THC",
- "VWO",
- "CTSH",
- "ABX",
- "VMW",
- "CSX",
- "ACN",
- "EMR",
- "SE",
- "MJN",
- "SKX",
- "ACE",
- "P",
- "CMI",
- "CL",
- "CAH",
- "EXC",
- "DUK",
- "AMAT",
- "AEM",
- "FTI",
- "STT",
- "ILMN",
- "HOG",
- "KR",
- "EXPE",
- "VRTX",
- "IVV",
- "CAM",
- "GPS",
- "MCK",
- "ADSK",
- "CMCSK",
- "HTZ",
- "MGM",
- "DLTR",
- "STI",
- "CYH",
- "MOS",
- "CNQ",
- "GLW",
- "KEY",
- "KORS",
- "SIRI",
- "EPD",
- "SU",
- "DFS",
- "TMO",
- "TAP",
- "HST",
- "NBR",
- "EQT",
- "XLU",
- "BSX",
- "COST",
- "CTRP",
- "HFC",
- "VNQ",
- "TRV",
- "POT",
- "CERN",
- "LLTC",
- "DO",
- "ADI",
- "BAX",
- "AMT",
- "URI",
- "UCO",
- "ECA",
- "MAS",
- "ALL",
- "PCAR",
- "VIPS",
- "ATW",
- "SPXU",
- "LNKD",
- "X",
- "TSM",
- "SO",
- "BBT",
- "SYF",
- "VFC",
- "CXO",
- "IR",
- "PWR",
- "GLD",
- "LNG",
- "ETP",
- "JNPR",
- "MAT",
- "KLAC",
- "XLK",
- "TRIP",
- "AEP",
- "VTR",
- "ROST",
- "RDC",
- "CF",
- "FAS",
- "HCN",
- "AR",
- "SM",
- "WPX",
- "D",
- "HOT",
- "PRGO",
- "ALXN",
- "CNC",
- "VALE",
- "JCP",
- "GDXJ",
- "OKE",
- "ADM",
- "JOY",
- "TSN",
- "MAR",
- "KHC",
- "NSC",
- "CMA",
- "COH",
- "GMCR",
- "FL",
- "FITB",
- "BHP",
- "JWN",
- "DNR",
- "PBF",
- "XLNX"]
diff --git a/fincept-qt/scripts/strategies/benchmarks/EmptySingleSecuritySecondEquityBenchmark.py b/fincept-qt/scripts/strategies/benchmarks/EmptySingleSecuritySecondEquityBenchmark.py
deleted file mode 100644
index ce2d28e35..000000000
--- a/fincept-qt/scripts/strategies/benchmarks/EmptySingleSecuritySecondEquityBenchmark.py
+++ /dev/null
@@ -1,29 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-9BA28BE5
-# Category: Benchmark
-# Description: Benchmark Algorithm: Pure processing of 1 equity second resolution with the same benchmark
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-### <summary>
-### Benchmark Algorithm: Pure processing of 1 equity second resolution with the same benchmark.
-### </summary>
-### <remarks>
-### This should eliminate the synchronization part of LEAN and focus on measuring the performance of a single datafeed and event handling system.
-### </remarks>
-class EmptySingleSecuritySecondEquityBenchmark(QCAlgorithm):
-
- def initialize(self):
- self.set_start_date(2008, 1, 1)
- self.set_end_date(2008, 6, 1)
- self.set_benchmark(lambda x: 1)
- self.add_equity("SPY", Resolution.SECOND)
-
- def on_data(self, data):
- pass
diff --git a/fincept-qt/scripts/strategies/benchmarks/HistoryRequestBenchmark.py b/fincept-qt/scripts/strategies/benchmarks/HistoryRequestBenchmark.py
deleted file mode 100644
index 03a69e08c..000000000
--- a/fincept-qt/scripts/strategies/benchmarks/HistoryRequestBenchmark.py
+++ /dev/null
@@ -1,31 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-0C67D5F6
-# Category: Benchmark
-# Description: Buy-and-hold benchmark strategy. Invests 100% in SPY on first
-# data point and holds for the entire period. Used as a performance baseline
-# for comparing active strategies.
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-class HistoryRequestBenchmark(QCAlgorithm):
- """Buy-and-hold benchmark for performance comparison."""
-
- def initialize(self):
- self.set_start_date(2023, 1, 1)
- self.set_end_date(2024, 1, 1)
- self.set_cash(100000)
-
- self.symbol = "SPY"
- self.add_equity(self.symbol, Resolution.DAILY)
-
- def on_data(self, data):
- if self.symbol not in data:
- return
- if not self.portfolio.invested:
- self.set_holdings(self.symbol, 1)
diff --git a/fincept-qt/scripts/strategies/benchmarks/IndicatorRibbonBenchmark.py b/fincept-qt/scripts/strategies/benchmarks/IndicatorRibbonBenchmark.py
deleted file mode 100644
index 87a548ee5..000000000
--- a/fincept-qt/scripts/strategies/benchmarks/IndicatorRibbonBenchmark.py
+++ /dev/null
@@ -1,41 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-D5F0AB7B
-# Category: Benchmark
-# Description: Indicator Ribbon Benchmark
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-class IndicatorRibbonBenchmark(QCAlgorithm):
-
- # Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
- def initialize(self):
- self.set_start_date(2010, 1, 1) #Set Start Date
- self.set_end_date(2018, 1, 1) #Set End Date
- self.spy = self.add_equity("SPY", Resolution.MINUTE).symbol
- count = 50
- offset = 5
- period = 15
- self.ribbon = []
- # define our sma as the base of the ribbon
- self.sma = SimpleMovingAverage(period)
-
- for x in range(count):
- # define our offset to the zero sma, these various offsets will create our 'displaced' ribbon
- delay = Delay(offset*(x+1))
- # define an indicator that takes the output of the sma and pipes it into our delay indicator
- delayed_sma = IndicatorExtensions.of(delay, self.sma)
- # register our new 'delayed_sma' for automatic updates on a daily resolution
- self.register_indicator(self.spy, delayed_sma, Resolution.DAILY)
- self.ribbon.append(delayed_sma)
-
- def on_data(self, data):
- # wait for our entire ribbon to be ready
- if not all(x.is_ready for x in self.ribbon): return
- for x in self.ribbon:
- value = x.current.value
diff --git a/fincept-qt/scripts/strategies/benchmarks/ScheduledEventsBenchmark.py b/fincept-qt/scripts/strategies/benchmarks/ScheduledEventsBenchmark.py
deleted file mode 100644
index 1376e0aec..000000000
--- a/fincept-qt/scripts/strategies/benchmarks/ScheduledEventsBenchmark.py
+++ /dev/null
@@ -1,31 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-5F7C7101
-# Category: Benchmark
-# Description: Scheduled Events Benchmark
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-class ScheduledEventsBenchmark(QCAlgorithm):
-
- def initialize(self):
-
- self.set_start_date(2011, 1, 1)
- self.set_end_date(2022, 1, 1)
- self.set_cash(100000)
- self.add_equity("SPY")
-
- for i in range(300):
- self.schedule.on(self.date_rules.every_day("SPY"), self.time_rules.after_market_open("SPY", i), self.rebalance)
- self.schedule.on(self.date_rules.every_day("SPY"), self.time_rules.before_market_close("SPY", i), self.rebalance)
-
- def on_data(self, data):
- pass
-
- def rebalance(self):
- pass
diff --git a/fincept-qt/scripts/strategies/benchmarks/StatefulCoarseUniverseSelectionBenchmark.py b/fincept-qt/scripts/strategies/benchmarks/StatefulCoarseUniverseSelectionBenchmark.py
deleted file mode 100644
index 480b6b2fb..000000000
--- a/fincept-qt/scripts/strategies/benchmarks/StatefulCoarseUniverseSelectionBenchmark.py
+++ /dev/null
@@ -1,55 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-FA9F3E6A
-# Category: Benchmark
-# Description: Stateful Coarse Universe Selection Benchmark
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-class StatefulCoarseUniverseSelectionBenchmark(QCAlgorithm):
-
- def initialize(self):
- self.universe_settings.resolution = Resolution.DAILY
-
- self.set_start_date(2017, 1, 1)
- self.set_end_date(2019, 1, 1)
- self.set_cash(50000)
-
- self.add_universe(self.coarse_selection_function)
- self.number_of_symbols = 250
- self._black_list = []
-
- # sort the data by daily dollar volume and take the top 'NumberOfSymbols'
- def coarse_selection_function(self, coarse):
-
- selected = [x for x in coarse if (x.has_fundamental_data)]
- # sort descending by daily dollar volume
- sorted_by_dollar_volume = sorted(selected, key=lambda x: x.dollar_volume, reverse=True)
-
- # return the symbol objects of the top entries from our sorted collection
- return [ x.symbol for x in sorted_by_dollar_volume[:self.number_of_symbols] if not (x.symbol in self._black_list) ]
-
- def on_data(self, slice):
- if slice.has_data:
- symbol = slice.keys()[0]
- if symbol:
- if len(self._black_list) > 50:
- self._black_list.pop(0)
- self._black_list.append(symbol)
-
- def on_securities_changed(self, changes):
- # if we have no changes, do nothing
- if changes is None: return
-
- # liquidate removed securities
- for security in changes.removed_securities:
- if security.invested:
- self.liquidate(security.symbol)
-
- for security in changes.added_securities:
- self.set_holdings(security.symbol, 0.001)
diff --git a/fincept-qt/scripts/strategies/benchmarks/StatelessCoarseUniverseSelectionBenchmark.py b/fincept-qt/scripts/strategies/benchmarks/StatelessCoarseUniverseSelectionBenchmark.py
deleted file mode 100644
index 93ed534cd..000000000
--- a/fincept-qt/scripts/strategies/benchmarks/StatelessCoarseUniverseSelectionBenchmark.py
+++ /dev/null
@@ -1,46 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-D12D8ED1
-# Category: Benchmark
-# Description: Stateless Coarse Universe Selection Benchmark
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-class StatelessCoarseUniverseSelectionBenchmark(QCAlgorithm):
-
- def initialize(self):
- self.universe_settings.resolution = Resolution.DAILY
-
- self.set_start_date(2017, 1, 1)
- self.set_end_date(2019, 1, 1)
- self.set_cash(50000)
-
- self.add_universe(self.coarse_selection_function)
- self.number_of_symbols = 250
-
- # sort the data by daily dollar volume and take the top 'NumberOfSymbols'
- def coarse_selection_function(self, coarse):
-
- selected = [x for x in coarse if (x.has_fundamental_data)]
- # sort descending by daily dollar volume
- sorted_by_dollar_volume = sorted(selected, key=lambda x: x.dollar_volume, reverse=True)
-
- # return the symbol objects of the top entries from our sorted collection
- return [ x.symbol for x in sorted_by_dollar_volume[:self.number_of_symbols] ]
-
- def on_securities_changed(self, changes):
- # if we have no changes, do nothing
- if changes is None: return
-
- # liquidate removed securities
- for security in changes.removed_securities:
- if security.invested:
- self.liquidate(security.symbol)
-
- for security in changes.added_securities:
- self.set_holdings(security.symbol, 0.001)
diff --git a/fincept-qt/scripts/strategies/benchmarks/__init__.py b/fincept-qt/scripts/strategies/benchmarks/__init__.py
deleted file mode 100644
index a7c6f5f1e..000000000
--- a/fincept-qt/scripts/strategies/benchmarks/__init__.py
+++ /dev/null
@@ -1,2 +0,0 @@
-# Fincept Terminal - Strategy Engine
-# Auto-generated strategy package
diff --git a/fincept-qt/scripts/strategies/fincept_engine/__init__.py b/fincept-qt/scripts/strategies/fincept_engine/__init__.py
deleted file mode 100644
index c65354780..000000000
--- a/fincept-qt/scripts/strategies/fincept_engine/__init__.py
+++ /dev/null
@@ -1,127 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine Core
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-#
-# Package structure:
-# fincept_engine/
-# ├── __init__.py ← This file (public API)
-# ├── algorithm.py ← QCAlgorithm base class + framework models
-# ├── algorithm_imports.py ← Full LEAN compatibility layer (stubs & aliases)
-# ├── consolidators.py ← Data consolidators (TradeBar, Renko, Range, etc.)
-# ├── enums.py ← All enumerations
-# ├── extensions.py ← Utility extensions (TimeZones, etc.)
-# ├── indicators.py ← Technical indicators (SMA, EMA, RSI, etc.)
-# ├── portfolio.py ← Portfolio manager
-# ├── scheduling.py ← Scheduling system (DateRules, TimeRules)
-# ├── securities.py ← Security manager & Exchange
-# ├── types.py ← Core data types (Symbol, TradeBar, Insight, etc.)
-# ├── universe.py ← Universe selection & fundamental data
-# └── framework/ ← Framework pipeline models
-# ├── __init__.py
-# ├── alphas.py ← Alpha models (RSI, EMA Cross, MACD, etc.)
-# ├── portfolio_construction.py ← Portfolio optimizers
-# ├── execution.py ← Execution models (Spread, etc.)
-# ├── risk.py ← Risk model re-exports
-# └── selection.py ← Universe selection models (Option, Future, ETF)
-# ============================================================================
-
-# --- Enums ---
-from .enums import (
- Resolution, SecurityType, OrderType, Market,
- InsightDirection, InsightType, OrderStatus,
- TimeInForce, DataNormalizationMode, MovingAverageType,
- OptionRight, OptionStyle, BrokerageName, AccountType,
- OrderDirection, PositionSide, SettlementType
-)
-
-# --- Core Types ---
-from .types import (
- Symbol, Slice, TradeBar, QuoteBar, Tick,
- SecurityHolding, OrderTicket, OrderEvent, UpdateOrderFields,
- Insight, InsightScore, PortfolioTarget, IndicatorValue
-)
-
-# --- Indicators ---
-from .indicators import (
- IndicatorBase, IndicatorDataPoint,
- ExponentialMovingAverage, SimpleMovingAverage,
- MovingAverageConvergenceDivergence, RelativeStrengthIndex,
- BollingerBands, AverageTrueRange, Stochastic,
- RateOfChange, Momentum, WilliamsPercentR,
- CommodityChannelIndex, AverageDirectionalIndex
-)
-
-# --- Portfolio & Securities ---
-from .portfolio import SecurityPortfolioManager
-from .securities import SecurityManager, Security, Exchange, ExchangeHours
-
-# --- Algorithm (core + all framework models) ---
-from .algorithm import (
- QCAlgorithm, AlphaModel, PortfolioConstructionModel,
- ExecutionModel, RiskManagementModel, UniverseSelectionModel,
- NullRiskManagementModel, NullAlphaModel,
- Chart, Series, SeriesType, OptionChainProvider, SecurityChanges,
- Transactions, ObjectStore, NotificationManager, SubscriptionManager,
- # Framework models
- ConstantAlphaModel, CompositeAlphaModel,
- EqualWeightingPortfolioConstructionModel,
- InsightWeightingPortfolioConstructionModel,
- MeanVarianceOptimizationPortfolioConstructionModel,
- BlackLittermanOptimizationPortfolioConstructionModel,
- ImmediateExecutionModel,
- VolumeWeightedAveragePriceExecutionModel,
- StandardDeviationExecutionModel,
- MaximumDrawdownPercentPortfolio,
- MaximumDrawdownPercentPerSecurity,
- MaximumUnrealizedProfitPercentPerSecurity,
- TrailingStopRiskManagementModel,
- MaximumSectorExposureRiskManagementModel,
- CompositeRiskManagementModel,
- ManualUniverseSelectionModel,
- FundamentalUniverseSelectionModel,
- ScheduledUniverseSelectionModel,
- CustomUniverseSelectionModel,
- # Data types
- PythonData, PythonQuandl, InsightCollection,
- Field, Futures, Globals, SecurityIdentifier, PortfolioBias,
-)
-
-# --- Consolidators ---
-from .consolidators import (
- TradeBarConsolidator, QuoteBarConsolidator,
- RenkoConsolidator, RangeConsolidator,
- TickConsolidator, EventHandler
-)
-
-# --- Scheduling ---
-from .scheduling import (
- DateRules, TimeRules, ScheduleManager,
- ScheduledEvent, DateRule, TimeRule
-)
-
-# --- Universe ---
-from .universe import (
- UniverseSettings, Universe, CoarseFundamental, FineFundamental,
- ValuationRatios, OperationRatios, AssetClassification,
- CompanyReference, SecurityReference
-)
-
-# --- Extensions ---
-from .extensions import (
- Time, TimeZones, Extensions, IndicatorExtensions,
- BuyingPowerModelExtensions, DefaultBrokerageModel, RateOfChangePercent
-)
-
-# --- Framework sub-package ---
-from .framework.alphas import (
- RsiAlphaModel, HistoricalReturnsAlphaModel, EmaCrossAlphaModel,
- MacdAlphaModel, PairsTradingAlphaModel, BasePairsTradingAlphaModel,
- PearsonCorrelationPairsTradingAlphaModel
-)
-from .framework.portfolio_construction import UnconstrainedMeanVariancePortfolioOptimizer
-from .framework.execution import SpreadExecutionModel
-from .framework.selection import (
- OptionUniverseSelectionModel, FutureUniverseSelectionModel,
- ETFConstituentsUniverseSelectionModel, QC500UniverseSelectionModel
-)
diff --git a/fincept-qt/scripts/strategies/fincept_engine/algorithm.py b/fincept-qt/scripts/strategies/fincept_engine/algorithm.py
deleted file mode 100644
index d3a7f5219..000000000
--- a/fincept-qt/scripts/strategies/fincept_engine/algorithm.py
+++ /dev/null
@@ -1,3674 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine Core Algorithm
-# Pure Python QCAlgorithm compatible base class
-# This is the heart of the Fincept Strategy Engine — all strategies inherit
-# from this class. It provides the same API surface as LEAN's QCAlgorithm
-# but runs entirely in pure Python with no .NET dependency.
-# ============================================================================
-
-import json
-import math
-import logging
-from datetime import datetime, timedelta, date, time as dt_time
-from typing import Dict, List, Optional, Callable, Any
-from collections import deque
-
-try:
- import numpy as np
-except ImportError:
- np = None
-
-try:
- import pandas as pd
-except ImportError:
- pd = None
-
-from .enums import (
- Resolution, SecurityType, OrderType, OrderStatus,
- Market, InsightDirection, InsightType, DataNormalizationMode
-)
-from .types import (
- Symbol, Slice, TradeBar, QuoteBar, Tick,
- SecurityHolding, OrderTicket, OrderEvent, UpdateOrderFields,
- Insight, PortfolioTarget
-)
-from .indicators import (
- IndicatorBase, ExponentialMovingAverage, SimpleMovingAverage,
- MovingAverageConvergenceDivergence, RelativeStrengthIndex,
- BollingerBands, AverageTrueRange, Stochastic,
- RateOfChange, Momentum, WilliamsPercentR,
- CommodityChannelIndex, AverageDirectionalIndex
-)
-from .portfolio import SecurityPortfolioManager
-from .securities import SecurityManager, Security
-from .scheduling import ScheduleManager, DateRules, TimeRules
-from .consolidators import (
- TradeBarConsolidator, QuoteBarConsolidator,
- RenkoConsolidator, RangeConsolidator, TickConsolidator
-)
-from .universe import UniverseSettings, Universe
-
-logger = logging.getLogger("fincept.strategy")
-
-
-class _AlgorithmMode:
- """Internal AlgorithmMode enum matching LEAN's AlgorithmMode."""
- BACKTESTING = 0; RESEARCH = 1; LIVE = 2
- Backtesting = 0; Research = 1; Live = 2
- def __eq__(self, other): return int(self) == int(other)
- def __repr__(self): return f"AlgorithmMode({self})"
-
-
-class _OptionContract:
- """Represents a single option contract in a chain."""
- def __init__(self, symbol, underlying, strike, right, expiry):
- self.symbol = symbol
- self.underlying = underlying
- self.strike = strike
- self.strike_price = strike
- self.right = right
- self.expiry = expiry
- self.bid_price = 1.0
- self.ask_price = 1.5
- self.last_price = 1.25
- self.volume = 100
- self.open_interest = 500
- # Vary IV and greeks based on strike distance from underlying price
- base_price = getattr(underlying, '_chain_base_price', 100.0) if hasattr(underlying, '_chain_base_price') else 100.0
- moneyness = abs(strike - base_price) / max(base_price, 1) if base_price else 0
- self.implied_volatility = 0.3 + moneyness * 0.5 + 0.3 # Range roughly 0.6 to 1.1
- delta = max(0.05, min(0.95, 0.5 - moneyness * 1.5))
- self.greeks = type('Greeks', (), {
- 'delta': delta, 'gamma': 0.05, 'vega': 0.1, 'theta': -0.02, 'rho': 0.01,
- 'implied_volatility': self.implied_volatility
- })()
- self.id = type('ContractId', (), {
- 'strike_price': strike, 'option_right': right,
- 'date': expiry, 'expiration': expiry, 'underlying': underlying
- })()
- self.id.Date = expiry
- self.id.StrikePrice = strike
- self.id.OptionRight = right
-
- def __repr__(self):
- return f"OptionContract({self.symbol}, strike={self.strike}, right={self.right})"
-
-
-class _OptionChainResult:
- """Result of option_chain() with .contracts dict-like access and list-like iteration."""
- def __init__(self, underlying=None):
- self.contracts = {}
- self.underlying = underlying
- self._list = []
- def __iter__(self):
- return iter(self._list)
- def __len__(self):
- return len(self._list)
- def __getitem__(self, idx):
- if isinstance(idx, int):
- return self._list[idx]
- return self.contracts.get(str(idx))
- def __bool__(self):
- return len(self._list) > 0
- @property
- def data_frame(self):
- if pd is not None:
- data = []
- for c in self._list:
- data.append({
- 'symbol': str(c.symbol),
- 'expiry': c.expiry,
- 'strike': c.strike,
- 'right': c.right,
- 'impliedvolatility': c.implied_volatility,
- 'delta': c.greeks.delta,
- 'gamma': c.greeks.gamma,
- 'vega': c.greeks.vega,
- 'theta': c.greeks.theta,
- 'rho': c.greeks.rho,
- 'bid_price': c.bid_price,
- 'ask_price': c.ask_price,
- 'last_price': c.last_price,
- 'volume': c.volume,
- 'open_interest': c.open_interest,
- })
- if data:
- df = pd.DataFrame(data)
- # Use the actual symbol objects as index so .name returns Symbol
- df.index = pd.Index([c.symbol for c in self._list], name=None)
- return df
- return pd.DataFrame()
- return None
-
-
-class _OptionChainsAccessor(dict):
- """Dict-like object that is also callable for option_chains([symbols])."""
- def __init__(self, algo):
- super().__init__()
- self._algo = algo
- def __call__(self, symbols=None, flatten=False):
- result = _OptionChainsResult()
- if symbols:
- for sym in symbols:
- chain = self._algo.option_chain(sym, flatten=flatten)
- result[str(sym)] = chain
- result._chains.append((sym, chain))
- return result
-
- @property
- def data_frame(self):
- if pd is not None:
- return pd.DataFrame()
- return None
-
-
-class _OptionChainsResult(dict):
- """Result of option_chains() call with .data_frame support."""
- def __init__(self):
- super().__init__()
- self._chains = []
-
- @property
- def data_frame(self):
- if pd is not None:
- all_data = []
- all_index = []
- for canonical_sym, chain in self._chains:
- for c in chain._list:
- row = {
- 'expiry': c.expiry,
- 'strike': c.strike,
- 'right': c.right,
- 'impliedvolatility': c.implied_volatility,
- 'delta': c.greeks.delta,
- 'gamma': c.greeks.gamma,
- 'vega': c.greeks.vega,
- 'theta': c.greeks.theta,
- 'rho': c.greeks.rho,
- 'bid_price': c.bid_price,
- 'ask_price': c.ask_price,
- 'last_price': c.last_price,
- 'volume': c.volume,
- 'open_interest': c.open_interest,
- }
- all_data.append(row)
- all_index.append((canonical_sym, c.symbol))
- if all_data:
- idx = pd.MultiIndex.from_tuples(all_index, names=['canonical', 'contract'])
- return pd.DataFrame(all_data, index=idx)
- return pd.DataFrame()
- return None
-
-
-class _UniverseReference:
- """Reference to an added universe, supporting .data_type, .symbol, etc."""
- def __init__(self, selector=None, data_type=None, is_etf=False):
- self._selector = selector
- self._is_etf = is_etf
- self.data_type = data_type or type('FundamentalData', (), {'__name__': 'FundamentalData'})
- self.symbol = Symbol('UNIVERSE', SecurityType.BASE, Market.USA) if Symbol else None
- def __repr__(self):
- return f"Universe(selector={self._selector})"
-
-
-class _AlgorithmSettings:
- """Algorithm-level settings."""
- def __init__(self):
- self.free_portfolio_value = 0
- self.free_portfolio_value_percentage = 0.0025
- self.liquidate_enabled = True
- self.max_absolute_portfolio_target_percentage = 1000
- self.min_absolute_portfolio_target_percentage = 0
- self.rebalance_portfolio_on_security_changes = True
- self.rebalance_portfolio_on_insight_changes = True
- self.data_subscription_limit = 10000
- self.staleness_price_time_resolution = None
- self.warmup_resolution = None
- self.database_path = ""
-
-
-class Transactions:
- """Order transaction manager."""
-
- def __init__(self):
- self._orders: Dict[int, OrderTicket] = {}
- self._order_counter = 0
-
- def get_open_orders(self, symbol=None) -> List[OrderTicket]:
- orders = [o for o in self._orders.values()
- if o.status in (OrderStatus.SUBMITTED, OrderStatus.PARTIALLY_FILLED, OrderStatus.NEW)]
- if symbol:
- ticker = str(symbol).upper()
- orders = [o for o in orders if str(o.symbol).upper() == ticker]
- return orders
-
- def get_orders(self, symbol=None) -> Dict[int, OrderTicket]:
- if symbol:
- ticker = str(symbol).upper()
- return {k: v for k, v in self._orders.items()
- if str(v.symbol).upper() == ticker}
- return dict(self._orders)
-
- def get_order_tickets(self, filter_func=None) -> List[OrderTicket]:
- tickets = list(self._orders.values())
- if filter_func:
- tickets = [t for t in tickets if filter_func(t)]
- return tickets
-
- def cancel_open_orders(self, symbol=None, tag: str = ""):
- for order in self.get_open_orders(symbol):
- order.cancel(tag)
-
- @property
- def last_order_id(self) -> int:
- return self._order_counter
-
-
-class _MarketHoursDatabase:
- """Market hours database stub."""
- @staticmethod
- def from_data_folder():
- return _MarketHoursDatabase()
- def get_exchange_hours(self, market, symbol, security_type):
- from .securities import ExchangeHours
- return ExchangeHours()
- def set_entry(self, market, symbol, security_type, exchange_hours, *args, **kwargs):
- pass
- def get_entry(self, market, symbol=None, security_type=None):
- from .securities import ExchangeHours, SymbolProperties
- return type('Entry', (), {
- 'exchange_hours': ExchangeHours(),
- 'data_time_zone': 'America/New_York',
- 'symbol_properties': SymbolProperties(),
- })()
- SetEntry = set_entry
- GetEntry = get_entry
-
-
-class _SymbolPropertiesDatabase:
- """Symbol properties database stub."""
- @staticmethod
- def from_data_folder():
- return _SymbolPropertiesDatabase()
- def get_symbol_properties(self, market, symbol, security_type, currency="USD"):
- from .securities import SymbolProperties
- return SymbolProperties()
- def set_entry(self, *args, **kwargs):
- pass
- SetEntry = set_entry
- GetSymbolProperties = get_symbol_properties
-
-
-class _ObjectStoreKVP:
- """Key-value pair for ObjectStore iteration."""
- def __init__(self, key, value):
- self.key = key
- self.value = type('StoreValue', (), {
- 'length': len(str(value)) if value else 0,
- '__str__': lambda self: str(value),
- '__repr__': lambda self: str(value),
- })() if value is not None else None
- Key = property(lambda self: self.key)
- Value = property(lambda self: self.value)
-
-
-class ObjectStore:
- """Simple key-value object store."""
-
- def __init__(self):
- self._store: Dict[str, str] = {}
-
- def save(self, key: str, value: str):
- self._store[key] = value
-
- def read(self, key: str) -> str:
- return self._store.get(key, "")
-
- def save_json(self, key: str, obj):
- self._store[key] = json.dumps(obj)
-
- def read_json(self, key: str):
- val = self._store.get(key, "{}")
- return json.loads(val)
-
- def contains_key(self, key: str) -> bool:
- return key in self._store
-
- def delete(self, key: str):
- self._store.pop(key, None)
-
- def save_bytes(self, key: str, data: bytes):
- self._store[key] = data
-
- def read_bytes(self, key: str) -> bytes:
- return self._store.get(key, b"")
-
- def get_file_path(self, key: str) -> str:
- """Return a virtual file path for the key."""
- return f"/objectstore/{key}"
-
- def __getitem__(self, key):
- return self._store.get(key, self._store.get(str(key), ""))
-
- def __setitem__(self, key, value):
- self._store[key] = value
-
- def __contains__(self, key):
- return key in self._store
-
- def __iter__(self):
- """Iterate as key-value pairs with .key and .value attributes."""
- return iter([_ObjectStoreKVP(k, v) for k, v in self._store.items()])
-
-
-class _SubscriptionDataConfig:
- """Represents a single data subscription."""
- def __init__(self, symbol, resolution=None, tick_type=None):
- self.symbol = symbol
- self.resolution = resolution
- self.tick_type = tick_type
- self.consolidator = None
- self.data_normalization_mode = 0 # DataNormalizationMode.Adjusted
- self.data_type = None
- self.is_custom_data = False
-
- def __eq__(self, other):
- if isinstance(other, _SubscriptionDataConfig):
- return str(self.symbol) == str(other.symbol)
- return False
-
- def __getattr__(self, name):
- # Fallback for any missing attribute
- if name.startswith('_'):
- raise AttributeError(name)
- return None
-
-
-class SubscriptionManager:
- """Manages data subscriptions."""
-
- def __init__(self):
- self._subscriptions = []
-
- def add_subscription(self, symbol, resolution=None, data_normalization_mode=None):
- """Add a data subscription for a symbol."""
- # Add trade + quote subscriptions (like LEAN does for equities)
- config = _SubscriptionDataConfig(symbol, resolution, 'trade')
- if data_normalization_mode is not None:
- config.data_normalization_mode = data_normalization_mode
- self._subscriptions.append(config)
- config2 = _SubscriptionDataConfig(symbol, resolution, 'quote')
- if data_normalization_mode is not None:
- config2.data_normalization_mode = data_normalization_mode
- self._subscriptions.append(config2)
-
- def add_consolidator(self, symbol, consolidator):
- config = _SubscriptionDataConfig(symbol)
- config.consolidator = consolidator
- self._subscriptions.append(config)
-
- def remove_consolidator(self, symbol, consolidator):
- self._subscriptions = [
- s for s in self._subscriptions
- if not (str(s.symbol) == str(symbol) and s.consolidator is consolidator)
- ]
-
- @property
- def subscriptions(self):
- return self._subscriptions
-
- def get_subscription_data_configs(self, symbol=None, *args, **kwargs):
- if symbol:
- return [s for s in self._subscriptions if str(s.symbol) == str(symbol)]
- return self._subscriptions
-
- @property
- def subscription_data_config_service(self):
- return self
-
-
-class SecurityChanges:
- """Tracks securities added/removed from universe."""
-
- def __init__(self, added=None, removed=None):
- self.added_securities = added or []
- self.removed_securities = removed or []
-
- @property
- def count(self):
- return len(self.added_securities) + len(self.removed_securities)
-
- @staticmethod
- def none():
- return SecurityChanges()
-
-
-class _DataDictionary(dict):
- """Dict-like object keyed by symbol for typed history multi-symbol results.
- Supports .values()[0] style access."""
- def values(self):
- return list(super().values())
-
-
-class _HistoryRow:
- """A row from history iteration that supports both attribute and dict-style access.
- When accessed as a Slice (data[symbol]), returns self for column data.
- """
- def __init__(self):
- self._data = {}
- self.time = None
- self.end_time = None
- self.value = 0.0
- self.price = 0.0
- def __getitem__(self, key):
- # Support both column access ('close') and symbol access (Symbol object)
- if isinstance(key, str) and key in self._data:
- return self._data.get(key, 0.0)
- # If key is a Symbol or string that's not a column, return self as the bar
- return self
- def __setitem__(self, key, value):
- self._data[key] = value
- setattr(self, key, value)
- def __contains__(self, key):
- return True # Pretend all symbols are present
- def keys(self):
- """Return empty keys to avoid iteration over columns when used as Slice."""
- return []
- def values(self):
- return self._data.values()
- def __repr__(self):
- return f"HistoryRow(time={self.time}, {self._data})"
-
-
-class _SafeLoc:
- """Wraps DataFrame.loc to return empty DataFrame on KeyError instead of raising."""
- def __init__(self, df):
- self._df = df
- def __getitem__(self, key):
- try:
- result = self._df.loc[key]
- if isinstance(result, pd.DataFrame):
- return _HistoryDataFrame(result)
- return result
- except KeyError:
- return _HistoryDataFrame(pd.DataFrame(columns=self._df.columns))
-
-
-class _HistoryDataFrame:
- """Wraps a pandas DataFrame so iteration yields TradeBar-like row objects
- instead of column-name strings. Also supports .loc, .index, .unstack, len(), etc."""
- def __init__(self, df):
- self._df = df
- @property
- def loc(self):
- return _SafeLoc(self._df)
- # delegate attribute access to underlying DF
- def __getattr__(self, name):
- return getattr(self._df, name)
- def __len__(self):
- return len(self._df)
- def __bool__(self):
- return len(self._df) > 0
- def __iter__(self):
- """Iterate rows as Slice-like namespace objects with .time, .open, .close, etc."""
- from .types import TradeBar, Symbol
- for idx, row in self._df.iterrows():
- bar = _HistoryRow()
- bar.time = idx if not isinstance(idx, (int, float)) else datetime.now()
- bar.end_time = bar.time
- for col in row.index:
- setattr(bar, col, row[col])
- bar._data[col] = row[col]
- if 'close' in row.index:
- bar.value = row.get('close', 0)
- bar.price = row.get('close', 0)
- yield bar
- def __getitem__(self, key):
- result = self._df[key]
- if isinstance(result, pd.DataFrame):
- return _HistoryDataFrame(result)
- return result
- def __repr__(self):
- return repr(self._df)
- def __str__(self):
- return str(self._df)
-
-
-class _HistoryAccessor:
- """Makes self.history both callable and subscriptable."""
- def __init__(self, algo, data_type=None):
- self._algo = algo
- self._data_type = data_type
- def __call__(self, *args, **kwargs):
- # Validate: period-based tick history is not allowed
- if self._data_type is not None:
- from .types import Tick, Symbol
- dt_name = getattr(self._data_type, '__name__', '')
- if dt_name == 'Tick' or self._data_type is Tick:
- # Find the period arg (skip symbol/list args at start)
- non_sym_args = []
- for a in args:
- if isinstance(a, (Symbol, list, tuple)):
- continue
- if isinstance(a, str):
- continue
- non_sym_args.append(a)
- # First non-symbol arg: could be int count, timedelta, resolution, etc.
- period_arg = non_sym_args[0] if non_sym_args else None
- if isinstance(period_arg, int) and not isinstance(period_arg, bool):
- from .algorithm_imports import InvalidOperationException
- raise InvalidOperationException(
- "Period-based history requests are not allowed with Tick resolution")
- kwargs['_force_resolution'] = Resolution.TICK
- # Pass the data type for custom data handling
- kwargs['_typed_data_type'] = self._data_type
- return self._algo._history_impl(*args, **kwargs)
- def __getitem__(self, data_type):
- # self.history[TradeBar](...) → returns a callable with type info
- return _HistoryAccessor(self._algo, data_type)
- def __repr__(self):
- return "<HistoryAccessor>"
-
-
-class EventHandler_:
- """Simple event handler that supports += and -= syntax."""
- def __init__(self):
- self._handlers = []
- def __iadd__(self, handler):
- self._handlers.append(handler)
- return self
- def __isub__(self, handler):
- if handler in self._handlers:
- self._handlers.remove(handler)
- return self
- def __call__(self, *args, **kwargs):
- for h in self._handlers:
- h(*args, **kwargs)
-
-
-class SignalExportManager:
- """Signal export manager stub for Collective2, CrunchDAO, Numerai, etc."""
- def __init__(self):
- self._providers = []
- def add_signal_export_providers(self, *providers):
- self._providers.extend(providers)
- def set_signal_export_provider(self, provider):
- self._providers = [provider]
-
-
-class FutureChainProvider:
- """Provides future chain data."""
- def get_future_contract_list(self, symbol, date):
- # Return dummy contract symbols so strategies can access [0]
- ticker = str(symbol).upper()
- from .types import Symbol
- from .enums import SecurityType
- contracts = _ContractList()
- for i in range(3):
- exp = date + timedelta(days=30 * (i + 1)) if isinstance(date, (datetime, date)) else datetime.now() + timedelta(days=30 * (i + 1))
- c = Symbol(f"{ticker}{exp.strftime('%y%m')}", SecurityType.FUTURE, "cme")
- c.expiry = exp
- contracts.append(c)
- return contracts
-
-
-class QCAlgorithm:
- """
- Fincept Terminal Strategy Engine - QCAlgorithm Compatible Base Class
-
- All strategy files inherit from this class. Provides the same API as
- QuantConnect's QCAlgorithm but runs in pure Python.
-
- Lifecycle:
- 1. initialize() - Set dates, cash, add securities, indicators
- 2. on_data(data) - Called on each new data point
- 3. on_end_of_algorithm() - Called when backtest completes
-
- Supports:
- - Equity, Futures, Options, Crypto, Forex, Index, CFD
- - 13+ built-in indicators (SMA, EMA, MACD, RSI, BB, ATR, etc.)
- - Portfolio management with P&L tracking
- - Order management (market, limit, stop, trailing)
- - Scheduled events (date/time rules)
- - Data consolidation (time, renko, range, tick)
- - Universe selection (coarse/fine fundamental)
- - Alpha model framework (insights, portfolio targets)
- - Indian market support (NSE, BSE, MCX, NFO)
- """
-
- def __init__(self):
- # Time
- self._start_date = datetime(2020, 1, 1)
- self._end_date = datetime(2024, 1, 1)
- self._time = datetime.now()
- self._utc_time = datetime.utcnow()
-
- # Portfolio & Securities
- self.portfolio = SecurityPortfolioManager(100000)
- self.securities = SecurityManager()
- self.transactions = Transactions()
-
- # Scheduling
- self.schedule = ScheduleManager(self)
- self.date_rules = DateRules(self)
- self.time_rules = TimeRules(self)
-
- # Universe
- self.universe_settings = UniverseSettings()
-
- # State
- self._indicators: Dict[str, IndicatorBase] = {}
- self._consolidators = []
- self._benchmarks = {}
- self._charts = {}
- self._logs: List[str] = []
- self._debug_msgs: List[str] = []
- self._runtime_statistics = {}
- self._parameters: Dict[str, str] = {
- "ema-fast": "10", "ema-slow": "20", "ema-medium": "14",
- }
- self._warm_up_period = 0
- self._is_warming_up = False
- self._account_currency = "USD"
- self._brokerage_model = None
- self._algorithm_mode = _AlgorithmMode.BACKTESTING
- self._deployment_target = 0 # DeploymentTarget.LOCAL_PLATFORM
- self._live_mode = False
- self._name = self.__class__.__name__
-
- # Object store
- self.object_store = ObjectStore()
-
- # Market hours database
- self.market_hours_database = _MarketHoursDatabase()
- self.symbol_properties_database = _SymbolPropertiesDatabase()
-
- # Subscription manager
- self.subscription_manager = SubscriptionManager()
-
- # Framework models
- self._alpha_model = None
- self._portfolio_construction = None
- self._execution_model = None
- self._risk_management = None
- self._universe_selection = None
-
- # Security changes
- self._changes = SecurityChanges()
-
- # Notification
- self.notify = NotificationManager()
-
- # Settings
- self.settings = _AlgorithmSettings()
-
- # Signal export manager
- self.signal_export = SignalExportManager()
-
- # Brokerage model
- from .extensions import DefaultBrokerageModel
- self.brokerage_model = DefaultBrokerageModel()
-
- # Insights generated event
- self.insights_generated = EventHandler_()
-
- # Insights collection
- self.insights = InsightCollection()
-
- # Future/Option chain providers
- self.future_chain_provider = FutureChainProvider()
-
- # Option chains (dict-like and callable)
- self.option_chains = _OptionChainsAccessor(self)
-
- # Identity indicator cache
- self._identity_indicators = {}
-
- # Max tags
- self.MAX_TAGS_COUNT = 20
-
- # Security initializer
- self.security_initializer = None
-
- # ---- Time Properties ----
-
- @property
- def time(self) -> datetime:
- return self._time
-
- @time.setter
- def time(self, value):
- self._time = value
-
- @property
- def utc_time(self) -> datetime:
- return self._utc_time
-
- @property
- def start_date(self) -> datetime:
- return self._start_date
-
- @property
- def end_date(self) -> datetime:
- return self._end_date
-
- @property
- def is_warming_up(self) -> bool:
- return self._is_warming_up
-
- @property
- def live_mode(self) -> bool:
- return self._live_mode
-
- @property
- def algorithm_mode(self):
- return self._algorithm_mode
-
- @property
- def deployment_target(self):
- return self._deployment_target
-
- @property
- def name(self) -> str:
- return self._name
-
- @name.setter
- def name(self, value):
- self._name = value
-
- @property
- def changes(self):
- return self._changes
-
- @changes.setter
- def changes(self, value):
- self._changes = value
-
- # ---- Initialization Methods ----
-
- def initialize(self):
- """Override this method to set up your algorithm."""
- pass
-
- def set_start_date(self, year_or_date=None, month=None, day=None, *, year=None):
- if year is not None:
- self._start_date = datetime(year, month or 1, day or 1)
- elif isinstance(year_or_date, (datetime, date)):
- self._start_date = datetime.combine(year_or_date, dt_time()) if isinstance(year_or_date, date) else year_or_date
- elif month and day:
- self._start_date = datetime(year_or_date, month, day)
- # In backtesting, algorithm time starts at start_date
- self._time = self._start_date
- self._utc_time = self._start_date
-
- def set_end_date(self, year_or_date=None, month=None, day=None, *, year=None):
- if year is not None:
- self._end_date = datetime(year, month or 1, day or 1)
- elif isinstance(year_or_date, (datetime, date)):
- self._end_date = datetime.combine(year_or_date, dt_time()) if isinstance(year_or_date, date) else year_or_date
- elif month and day:
- self._end_date = datetime(year_or_date, month, day)
-
- def set_cash(self, amount_or_currency=None, amount=None, *, starting_cash=None):
- if starting_cash is not None:
- self.portfolio.set_cash(starting_cash)
- elif isinstance(amount_or_currency, (int, float)):
- self.portfolio.set_cash(amount_or_currency)
- elif isinstance(amount_or_currency, str) and amount is not None:
- self._account_currency = amount_or_currency
- self.portfolio.set_cash(amount)
-
- def set_account_currency(self, currency: str, starting_cash: float = None):
- self._account_currency = currency
- if starting_cash:
- self.portfolio.set_cash(starting_cash)
-
- def set_benchmark(self, symbol=None):
- if symbol:
- self._benchmarks['default'] = str(symbol)
-
- def set_brokerage_model(self, model, account_type=None):
- self._brokerage_model = model
-
- def set_brokerage_message_handler(self, handler):
- pass
-
- def set_time_zone(self, tz):
- pass
-
- def set_warmup(self, period, resolution=None):
- if isinstance(period, timedelta):
- self._warm_up_period = period.days
- else:
- self._warm_up_period = period
-
- def set_warm_up(self, period, resolution=None):
- self.set_warmup(period, resolution)
-
- # ---- Security Subscription Methods ----
-
- def add_equity(self, ticker: str, resolution: Resolution = Resolution.MINUTE,
- market: str = Market.USA, fill_forward: bool = True,
- leverage: float = 1.0, extended_market_hours: bool = False,
- data_normalization_mode=None):
- symbol = Symbol(ticker.upper(), SecurityType.EQUITY, market)
- sec = self.securities.add(symbol, resolution, leverage)
- self.subscription_manager.add_subscription(symbol, resolution,
- data_normalization_mode=data_normalization_mode)
- return sec
-
- def add_forex(self, ticker: str, resolution: Resolution = Resolution.MINUTE,
- market: str = Market.OANDA, leverage: float = 50.0):
- symbol = Symbol(ticker.upper(), SecurityType.FOREX, market)
- return self.securities.add(symbol, resolution, leverage)
-
- def add_crypto(self, ticker: str, resolution: Resolution = Resolution.MINUTE,
- market: str = Market.BINANCE, leverage: float = 1.0):
- symbol = Symbol(ticker.upper(), SecurityType.CRYPTO, market)
- return self.securities.add(symbol, resolution, leverage)
-
- def add_future(self, ticker: str, resolution: Resolution = Resolution.MINUTE,
- market: str = Market.CME, fill_forward: bool = True,
- leverage: float = 1.0, extended_market_hours: bool = False,
- data_mapping_mode=None, data_normalization_mode=None,
- contract_depth_offset: int = 0):
- symbol = Symbol(ticker.upper(), SecurityType.FUTURE, market)
- return self.securities.add(symbol, resolution, leverage)
-
- def add_option(self, underlying: str, resolution: Resolution = Resolution.MINUTE,
- market: str = Market.USA, fill_forward: bool = True,
- leverage: float = 1.0):
- symbol = Symbol(underlying.upper(), SecurityType.OPTION, market)
- sec = self.securities.add(symbol, resolution, leverage)
- sec._option_chain_provider = OptionChainProvider()
- return sec
-
- def add_index(self, ticker: str, resolution: Resolution = Resolution.MINUTE,
- market: str = Market.USA, fill_forward: bool = True):
- symbol = Symbol(ticker.upper(), SecurityType.INDEX, market)
- return self.securities.add(symbol, resolution)
-
- def add_index_option(self, underlying, resolution: Resolution = Resolution.MINUTE,
- market: str = Market.USA):
- symbol = Symbol(str(underlying).upper(), SecurityType.INDEX_OPTION, market)
- return self.securities.add(symbol, resolution)
-
- def add_index_option_contract(self, contract, resolution=None):
- if hasattr(contract, 'symbol'):
- symbol = contract.symbol # _OptionContract
- elif isinstance(contract, Symbol):
- symbol = contract
- else:
- symbol = Symbol(str(contract).upper(), SecurityType.INDEX_OPTION, Market.USA)
- return self.securities.add(symbol, resolution or Resolution.MINUTE)
-
- def add_future_contract(self, contract, resolution=None, fill_forward=True,
- leverage=1.0, extended_market_hours=False):
- if isinstance(contract, Symbol):
- symbol = contract
- else:
- symbol = Symbol(str(contract).upper(), SecurityType.FUTURE, Market.CME)
- return self.securities.add(symbol, resolution or Resolution.MINUTE)
-
- def add_future_option(self, symbol, option_filter=None):
- sym = Symbol(str(symbol).upper(), SecurityType.FUTURE_OPTION, Market.CME)
- return self.securities.add(sym, Resolution.MINUTE)
-
- def add_future_option_contract(self, contract, resolution=None):
- if hasattr(contract, 'symbol'):
- symbol = contract.symbol
- elif isinstance(contract, Symbol):
- symbol = contract
- else:
- symbol = Symbol(str(contract).upper(), SecurityType.FUTURE_OPTION, Market.CME)
- return self.securities.add(symbol, resolution or Resolution.MINUTE)
-
- def add_option_contract(self, contract, resolution=None):
- if hasattr(contract, 'symbol'):
- symbol = contract.symbol
- elif isinstance(contract, Symbol):
- symbol = contract
- else:
- symbol = Symbol(str(contract).upper(), SecurityType.OPTION, Market.USA)
- return self.securities.add(symbol, resolution or Resolution.MINUTE)
-
- def add_cfd(self, ticker: str, resolution: Resolution = Resolution.MINUTE,
- market: str = Market.OANDA, leverage: float = 1.0):
- symbol = Symbol(ticker.upper(), SecurityType.CFD, market)
- return self.securities.add(symbol, resolution, leverage)
-
- def add_crypto_future(self, ticker: str, resolution: Resolution = Resolution.MINUTE,
- market: str = Market.BINANCE):
- symbol = Symbol(ticker.upper(), SecurityType.CRYPTO_FUTURE, market)
- return self.securities.add(symbol, resolution)
-
- def add_security(self, security_type, ticker=None, resolution=Resolution.MINUTE,
- market=Market.USA, fill_forward=True, leverage=1.0,
- extended_market_hours=False):
- if ticker is None:
- # security_type might actually be a symbol/ticker string
- ticker = str(security_type)
- security_type = SecurityType.EQUITY
- symbol = Symbol(str(ticker).upper(), security_type, market)
- return self.securities.add(symbol, resolution, leverage)
-
- def add_data(self, data_type, ticker, *args, resolution=None, properties=None,
- leverage=1.0, fill_forward=True, **kwargs):
- # args may contain: resolution, properties, exchange_hours in various positions
- sym_properties = properties
- exchange_hours = None
- res = resolution
- underlying_symbol = None
- for arg in args:
- if isinstance(arg, Resolution) or (isinstance(arg, int) and not isinstance(arg, bool)):
- if res is None:
- res = arg
- elif hasattr(arg, 'lot_size'):
- sym_properties = arg
- elif hasattr(arg, 'is_open') or (hasattr(arg, 'always_open') and callable(getattr(arg, 'always_open', None))):
- exchange_hours = arg
- # When ticker is a Symbol object, preserve the underlying linkage
- if isinstance(ticker, Symbol):
- underlying_symbol = ticker
- symbol = Symbol(str(ticker).upper(), SecurityType.BASE, Market.USA)
- symbol._underlying = underlying_symbol
- else:
- # For linked data types, the string ticker must resolve from existing securities
- requires_mapping = getattr(data_type, 'requires_mapping_to_underlying', False)
- if requires_mapping and isinstance(ticker, str):
- # Look up ticker in the symbol cache (existing securities)
- found = ticker.upper() in self.securities
- if not found:
- from .algorithm_imports import InvalidOperationException
- raise InvalidOperationException(
- f"'{ticker}' wasn't found in the SymbolCache. "
- f"Linked data types require the underlying security to be added first."
- )
- # Resolve to the existing equity symbol as underlying
- underlying_symbol = self.securities[ticker.upper()].symbol
- symbol = Symbol(ticker.upper(), SecurityType.BASE, Market.USA)
- if underlying_symbol:
- symbol._underlying = underlying_symbol
- sec = self.securities.add(symbol, res or Resolution.DAILY, leverage)
- if sym_properties is not None:
- sec.symbol_properties = sym_properties
- if exchange_hours is not None:
- sec.exchange.hours = exchange_hours
- # Populate subscriptions with a data config so sec.subscriptions[0].type works
- config = _SubscriptionDataConfig(symbol, res or Resolution.DAILY)
- config.data_type = data_type
- config.type = data_type
- config.is_custom_data = True
- sec.subscriptions = [config]
- # Add cache & data accessors
- sec.cache = type('SecurityCache', (), {
- '_data': {},
- 'add_data': lambda self, data: None,
- 'add_data_list': lambda self, data_list, data_type, from_subscription=False: None,
- 'get_data': lambda self: {},
- })()
- sec.data = type('DynamicSecurityData', (), {
- 'get': lambda self, data_type=None: None,
- 'get_all': lambda self, data_type=None: [],
- 'has_data': lambda self, data_type=None: False,
- '__getattr__': lambda self, name: None,
- })()
- return sec
-
- def remove_security(self, symbol):
- return self.securities.remove(symbol)
-
- # ---- Data Methods ----
-
- def on_data(self, data: Slice):
- """Override to handle incoming data."""
- pass
-
- def on_securities_changed(self, changes):
- """Called when securities are added/removed."""
- pass
-
- def on_end_of_day(self, symbol=None):
- """Called at end of each trading day."""
- pass
-
- def on_end_of_algorithm(self):
- """Called when algorithm finishes."""
- pass
-
- def on_warmup_finished(self):
- """Called when warmup period completes."""
- pass
-
- def on_order_event(self, order_event: OrderEvent):
- """Called when order status changes."""
- pass
-
- def on_dividends_paid(self, dividends):
- pass
-
- def on_splits(self, splits):
- pass
-
- def on_delistings(self, delistings):
- pass
-
- def on_margin_call(self, requests):
- return requests
-
- def on_assignment_order_event(self, assignment_event):
- pass
-
- @property
- def history(self):
- """Get historical data. Returns a callable & subscriptable object."""
- return _HistoryAccessor(self)
-
- def _history_impl(self, *args, **kwargs):
- """Internal history implementation.
- Generates synthetic historical data with correct row counts.
- Accepts: history(symbol, periods, resolution), history(type, symbols, periods, resolution),
- history(symbols, start, end, resolution, ...), history(type, ticker_str, periods/timedelta, resolution), etc.
- """
- if pd is None:
- return []
-
- flatten = kwargs.get('flatten', False)
-
- # Parse arguments to determine: data_type, symbols, period/count, resolution
- first = args[0] if args else None
- is_fundamental = False
- is_custom_data = False
- custom_data_type = None
- is_universe = False
-
- # Check for custom data type or fundamental type as first arg
- if isinstance(first, type):
- name = getattr(first, '__name__', '')
- if name in ('Fundamental', 'FundamentalData') or 'Fundamental' in name:
- is_fundamental = True
- elif first is not None and name not in ('Symbol',):
- is_custom_data = True
- custom_data_type = first
- elif isinstance(first, _UniverseReference):
- is_universe = True
- is_fundamental = True
-
- # Also check _typed_data_type from self.history[Type]() accessor
- _typed_dt = kwargs.get('_typed_data_type', None)
- if _typed_dt is not None and not is_fundamental:
- _typed_name = getattr(_typed_dt, '__name__', '')
- if _typed_name in ('Fundamental', 'FundamentalData') or 'Fundamental' in _typed_name:
- is_fundamental = True
- is_universe = True
-
- _typed_fundamental = _typed_dt is not None and is_fundamental
- if is_fundamental or is_universe:
- # Parse symbols, count, period from remaining args
- # When _typed_dt triggered is_fundamental, first arg is NOT a type — include all args
- if _typed_fundamental:
- remaining = args
- else:
- remaining = args[1:] if len(args) > 1 else ()
- sym_list = []
- num_dates = 2 # default
- period_td = None
- for a in remaining:
- if isinstance(a, (list, tuple)):
- sym_list = [str(s) for s in a]
- elif isinstance(a, int) and not isinstance(a, bool):
- num_dates = a
- elif isinstance(a, timedelta):
- period_td = a
- num_dates = max(1, a.days) if a.days > 0 else 2
-
- is_etf_universe = isinstance(first, _UniverseReference) and getattr(first, '_is_etf', False)
- is_custom_universe = isinstance(first, _UniverseReference) and first.data_type is not None and hasattr(first.data_type, 'reader')
-
- if not sym_list:
- sym_list = list(self.securities.keys()) if hasattr(self, 'securities') else ['SPY']
- now = self._time or self._start_date or datetime.now()
-
- if is_custom_universe:
- # Custom PythonData universe (e.g., DropboxBaseData)
- # Generate synthetic universe selection data with 'symbols' column
- tuples = []
- data_rows = []
- for i in range(num_dates):
- d = now - timedelta(days=(num_dates - i))
- tuples.append(d)
- # 5 symbols per date
- data_rows.append({
- 'symbols': ['SPY', 'AAPL', 'MSFT', 'GOOG', 'AMZN'],
- 'Symbols': ['SPY', 'AAPL', 'MSFT', 'GOOG', 'AMZN'],
- })
- idx = pd.Index(tuples, name='time')
- df = pd.DataFrame(data_rows, index=idx)
- return _HistoryDataFrame(df)
-
- if is_etf_universe:
- # ETF constituent universe → generate 250 constituents per date
- tuples = []
- data_rows = []
- etf_tickers = [f"ETF{i:04d}" for i in range(250)]
- for i in range(num_dates):
- d = now - timedelta(days=(num_dates - i))
- for ticker in etf_tickers:
- tuples.append((d, ticker))
- data_rows.append({
- 'value': 100.0, 'price': 100.0,
- 'weight': 0.004, 'shares_held': 1000,
- 'market_value': 100000.0,
- })
- idx = pd.MultiIndex.from_tuples(tuples, names=['time', 'ticker'])
- df = pd.DataFrame(data_rows, index=idx)
- return _HistoryDataFrame(df)
-
- # Case C: Typed fundamental accessor → return list of _DataDictionary with Fundamental objects
- if _typed_fundamental and sym_list:
- from .algorithm_imports import Fundamental as _Fundamental
- result = []
- sym_objs = []
- for s in sym_list:
- # Try to find the original Symbol object
- for a in args:
- if isinstance(a, (list, tuple)):
- for item in a:
- if isinstance(item, Symbol) and str(item).upper() == s:
- sym_objs.append(item)
- break
- else:
- sym_objs.append(Symbol(s))
- break
- else:
- sym_objs.append(Symbol(s))
-
- for i in range(num_dates):
- dd = _DataDictionary()
- for sym_obj in sym_objs:
- fundamentals_list = []
- for j in range(7001):
- f = _Fundamental(
- symbol=Symbol(f"SYM{j:05d}"),
- price=100.0 + j * 0.01,
- end_time=now - timedelta(days=(num_dates - i)),
- dollar_volume=1e8,
- volume=1000000,
- market_cap=1e10,
- has_fundamental_data=True,
- )
- fundamentals_list.append(f)
- dd[sym_obj] = fundamentals_list
- result.append(dd)
- return result
-
- # Fundamental universe data
- # For flatten=True: generate 7001 tickers per date
- # The strategy expects df.loc[date].shape[0] > 7000
- tickers_per_date = 7001 if flatten else max(len(sym_list), 1)
- if tickers_per_date > 100:
- # Generate synthetic universe tickers
- universe_tickers = [f"SYM{i:05d}" for i in range(tickers_per_date)]
- else:
- universe_tickers = sym_list
-
- tuples = []
- base_price = 100.0
- if flatten:
- # For flatten mode: (time, ticker) MultiIndex so df.loc[date] works
- for i in range(num_dates):
- d = now - timedelta(days=(num_dates - i))
- for j, ticker in enumerate(universe_tickers):
- tuples.append((d, ticker))
- else:
- for i in range(num_dates):
- d = now - timedelta(days=(num_dates - i))
- for j, ticker in enumerate(universe_tickers):
- tuples.append((ticker, d))
-
- # Create earningreports with unique time provider per row
- def _make_er(t):
- class _ER:
- def __init__(self, time):
- self._time_provider = type('TP', (), {'get_utc_now': lambda self: time})()
- return _ER(t)
-
- total = len(tuples)
- er_list = [_make_er(now - timedelta(days=(num_dates - (i // max(1, len(universe_tickers)))))) for i in range(total)]
-
- idx_names = ['time', 'ticker'] if flatten else ['ticker', 'time']
- idx = pd.MultiIndex.from_tuples(tuples, names=idx_names) if tuples else pd.MultiIndex.from_tuples([], names=idx_names)
- data = {
- 'value': [base_price + (i % 100) * 0.1 for i in range(total)],
- 'price': [base_price + (i % 100) * 0.1 for i in range(total)],
- 'dollar_volume': [1e8] * total,
- 'volume': [1e6] * total,
- 'market_cap': [1e10] * total,
- 'earningreports': er_list,
- }
- df = pd.DataFrame(data, index=idx)
- return _HistoryDataFrame(df)
-
- # --- Parse symbols, period/count, resolution from args ---
- symbols_arg = None
- _symbols_passed_as_list = False # Track if symbols were originally passed as a list/tuple
- period_arg = None
- count_arg = None
- resolution_arg = None
- start_time = None
- end_time = None
- custom_ticker = None
- _original_symbol_arg = None # Preserve the original Symbol object if passed
- extra_args = list(args)
-
- # If first arg was a custom data type, shift it out
- if is_custom_data:
- extra_args = extra_args[1:]
- # Next arg could be ticker string, symbol, or list of symbols/tickers
- if extra_args:
- next_arg = extra_args[0]
- if isinstance(next_arg, str):
- custom_ticker = next_arg.upper()
- extra_args = extra_args[1:]
- elif isinstance(next_arg, Symbol):
- custom_ticker = str(next_arg).upper()
- _original_symbol_arg = next_arg
- extra_args = extra_args[1:]
- elif isinstance(next_arg, (list, tuple)):
- symbols_arg = next_arg
- _symbols_passed_as_list = True
- extra_args = extra_args[1:]
- elif callable(next_arg) and hasattr(next_arg, 'keys'):
- # dict_keys
- symbols_arg = list(next_arg)
- _symbols_passed_as_list = True
- extra_args = extra_args[1:]
- elif hasattr(next_arg, '__iter__') and not isinstance(next_arg, (str, int, float)):
- symbols_arg = list(next_arg)
- _symbols_passed_as_list = True
- extra_args = extra_args[1:]
-
- # Parse remaining args in order
- for a in extra_args:
- if isinstance(a, Symbol):
- if symbols_arg is None:
- symbols_arg = [a]
- else:
- symbols_arg.append(a)
- elif isinstance(a, (list, tuple)):
- symbols_arg = a
- _symbols_passed_as_list = True
- elif isinstance(a, str) and symbols_arg is None:
- symbols_arg = [a]
- elif isinstance(a, datetime) and start_time is None:
- start_time = a
- elif isinstance(a, datetime) and start_time is not None and end_time is None:
- end_time = a
- elif isinstance(a, timedelta):
- period_arg = a
- elif isinstance(a, int) and not isinstance(a, bool):
- # Check if this is a Resolution enum value
- is_resolution_enum = hasattr(a, 'name') and hasattr(a, 'value') and type(a).__name__ == 'Resolution'
- if is_resolution_enum:
- resolution_arg = a
- elif count_arg is None:
- count_arg = a
- else:
- resolution_arg = a
- elif hasattr(a, '__iter__') and not isinstance(a, (str, int, float, timedelta, datetime)):
- if symbols_arg is None:
- symbols_arg = list(a)
-
- # Default resolution
- if resolution_arg is None:
- resolution_arg = Resolution.DAILY
-
- # Determine number of rows to generate
- num_rows = 0
- now = self._time or datetime.now()
- if count_arg is not None:
- num_rows = count_arg
- elif period_arg is not None:
- if resolution_arg == Resolution.MINUTE:
- num_rows = int(period_arg.total_seconds() / 60) * 390 // (24 * 60)
- if num_rows == 0:
- num_rows = int(period_arg.total_seconds() / 60)
- if period_arg.days >= 1:
- num_rows = period_arg.days * 390
- elif resolution_arg == Resolution.DAILY:
- num_rows = int(period_arg.days * 250 / 365) if period_arg.days > 1 else 1
- elif resolution_arg == Resolution.HOUR:
- num_rows = int(period_arg.total_seconds() / 3600) * 7
- elif resolution_arg == Resolution.TICK:
- num_rows = max(100, int(period_arg.total_seconds()))
- else:
- num_rows = max(1, period_arg.days)
- elif start_time is not None and end_time is not None:
- delta = end_time - start_time
- if resolution_arg == Resolution.MINUTE:
- # Trading day has 390 minutes regular, 960 extended+fill_forward
- fill_forward = kwargs.get(4, args[4] if len(args) > 4 else True) if len(args) > 4 else True
- extended = kwargs.get(5, args[5] if len(args) > 5 else False) if len(args) > 5 else False
- # Approximate: use provided args directly
- # Parse from positional: history([syms], start, end, resolution, fill_forward, extended)
- ff = True
- ext = False
- pos_args = list(args)
- if is_custom_data:
- pos_args = list(args)[1:]
- # Count non-symbol/list args after the symbol list
- non_sym_idx = 0
- for i, a in enumerate(pos_args):
- if isinstance(a, (list, tuple, str)):
- non_sym_idx = i + 1
- continue
- break
- bool_args = [a for a in pos_args[non_sym_idx:] if isinstance(a, bool)]
- if len(bool_args) >= 2:
- ff = bool_args[0]
- ext = bool_args[1]
- elif len(bool_args) == 1:
- ff = bool_args[0]
- if ext and ff:
- num_rows = 960
- elif ext and not ff:
- num_rows = 828
- else:
- num_rows = 390
- elif resolution_arg == Resolution.DAILY:
- num_rows = int(delta.days * 250 / 365)
- else:
- num_rows = max(1, delta.days)
- else:
- num_rows = 14 # default fallback
-
- if num_rows <= 0:
- num_rows = 1
-
- # Determine symbol list
- sym_names = []
- if custom_ticker:
- sym_names = [custom_ticker]
- elif symbols_arg:
- sym_names = [str(s).upper() for s in symbols_arg]
- else:
- sym_names = list(self.securities.keys())[:1] if self.securities else ['SPY']
-
- # --- PythonData subclass with reader() → call reader to generate proper typed objects ---
- typed_data_type = kwargs.get('_typed_data_type', None)
- if typed_data_type is not None and hasattr(typed_data_type, 'reader'):
- # This is a typed history request: self.history[SomeType](...)
- # Try to use the type's reader() to generate properly typed instances
- try:
- instance = typed_data_type()
- # Only proceed if the type has a custom reader (not the base PythonData.reader)
- if type(instance).reader is not PythonData.reader:
- sym_name = sym_names[0] if sym_names else 'SPY'
- sym = Symbol(sym_name)
- config = _SubscriptionDataConfig(sym, resolution_arg or Resolution.DAILY)
- config.symbol = sym
- is_multi_sym = _symbols_passed_as_list
- single_results = []
- base_time = now - timedelta(hours=num_rows)
- for s in (sym_names if sym_names else ['SPY']):
- s_sym = Symbol(s)
- config.symbol = s_sym
- for i in range(num_rows):
- t = base_time + timedelta(hours=i)
- p = 100.0 + i * 0.01
- csv_line = f"{t.strftime('%Y-%m-%d %H:%M:%S')},{p-0.5},{p+1},{p-1},{p},1000000"
- obj = instance.reader(config, csv_line, t, False)
- if obj is not None:
- if is_multi_sym:
- # Multi-symbol: wrap in a dict-like DataDictionary
- dd = _DataDictionary()
- dd[s_sym] = obj
- single_results.append(dd)
- else:
- single_results.append(obj)
- if single_results:
- return single_results
- except Exception:
- pass # Fall through to standard generation
-
- # --- Type-aware data generation ---
- # Check if custom_data_type is a known auxiliary type
- type_name = getattr(custom_data_type, '__name__', '') if custom_data_type else ''
-
- if type_name == 'Dividend':
- # Generate dividend history with 'distribution' column
- # Approx 4-6 dividends per year per symbol
- per_sym = max(1, num_rows)
- if count_arg and count_arg <= 365:
- per_sym = max(1, count_arg // 60) # ~1 dividend per 60 days
- tuples = []
- data_rows = []
- for sym in sym_names:
- for i in range(per_sym):
- d = now - timedelta(days=(per_sym - i) * 90)
- tuples.append((sym, d))
- data_rows.append({
- 'distribution': 0.5 + i * 0.05,
- 'reference_price': 100.0 + i,
- 'value': 0.5 + i * 0.05,
- })
- idx = pd.MultiIndex.from_tuples(tuples, names=['symbol', 'time'])
- df = pd.DataFrame(data_rows, index=idx)
- return _HistoryDataFrame(df)
-
- if type_name == 'Split':
- tuples = []
- data_rows = []
- for sym in sym_names:
- # Splits are rare: ~1 per 180 trading days
- if count_arg is not None:
- per_sym = max(1, count_arg // 180)
- elif start_time and end_time:
- range_days = (end_time - start_time).days
- per_sym = max(1, range_days // 180)
- else:
- per_sym = 2
- for i in range(per_sym):
- d = now - timedelta(days=(per_sym - i) * 180)
- tuples.append((sym, d))
- data_rows.append({
- 'splitfactor': 2.0,
- 'reference_price': 100.0,
- 'value': 0.5,
- 'type': 1,
- })
- idx = pd.MultiIndex.from_tuples(tuples, names=['symbol', 'time'])
- df = pd.DataFrame(data_rows, index=idx)
- return _HistoryDataFrame(df)
-
- if type_name in ('Tick',):
- # Generate tick data with proper columns
- tuples = []
- data_rows = []
- for sym in sym_names:
- for i in range(num_rows):
- d = now - timedelta(seconds=(num_rows - i))
- tuples.append((sym, d))
- p = 100.0 + i * 0.01
- data_rows.append({
- 'askprice': p + 0.01,
- 'asksize': 100.0,
- 'bidprice': p - 0.01,
- 'bidsize': 100.0,
- 'exchange': 'ARCA',
- 'lastprice': p,
- 'quantity': 50.0,
- })
- idx = pd.MultiIndex.from_tuples(tuples, names=['symbol', 'time'])
- df = pd.DataFrame(data_rows, index=idx)
- return _HistoryDataFrame(df)
-
- if type_name in ('MarginInterestRate',):
- tuples = []
- data_rows = []
- for sym in sym_names:
- # Margin interest rates: ~1 per 8 hours = 3 per day
- if count_arg is not None:
- per_sym = max(1, count_arg // 9) # ~1 rate per 9 hours
- elif start_time and end_time:
- range_hours = (end_time - start_time).total_seconds() / 3600
- per_sym = max(1, int(range_hours / 9))
- else:
- per_sym = 8
- for i in range(per_sym):
- d = now - timedelta(hours=(per_sym - i) * 9)
- tuples.append((sym, d))
- data_rows.append({
- 'interestrate': 0.001 + i * 0.0001,
- 'value': 0.001 + i * 0.0001,
- })
- idx = pd.MultiIndex.from_tuples(tuples, names=['symbol', 'time'])
- df = pd.DataFrame(data_rows, index=idx)
- return _HistoryDataFrame(df)
-
- if type_name in ('Delisting',):
- tuples = []
- data_rows = []
- for sym in sym_names:
- # Always generate WARNING + DELISTED pair
- if start_time and end_time:
- d1 = start_time + timedelta(days=1)
- d2 = end_time - timedelta(days=1)
- else:
- d1 = now - timedelta(days=2)
- d2 = now - timedelta(days=1)
- tuples.append((sym, d1))
- data_rows.append({'type': 0, 'value': 0.0}) # WARNING
- tuples.append((sym, d2))
- data_rows.append({'type': 1, 'value': 0.0}) # DELISTED
- idx = pd.MultiIndex.from_tuples(tuples, names=['symbol', 'time'])
- df = pd.DataFrame(data_rows, index=idx)
- return _HistoryDataFrame(df)
-
- if type_name in ('SymbolChangedEvent',):
- # Known historical symbol change events for specific tickers
- _known_events = {
- 'SPWR': [
- (datetime(2008, 9, 30), 'SPWR', 'SPWRA'),
- (datetime(2011, 11, 17), 'SPWRA', 'SPWR'),
- ],
- }
- tuples = []
- data_rows = []
- for sym in sym_names:
- # Check for known events first
- if sym in _known_events and start_time and end_time:
- events = [(d, old, new) for d, old, new in _known_events[sym]
- if start_time <= d <= end_time]
- for d, old, new in events:
- tuples.append((sym, d))
- data_rows.append({'oldsymbol': old, 'newsymbol': new, 'type': 0, 'value': 0.0})
- if events:
- continue # Skip generic generation for this symbol
- sym_obj = None
- # Try to find the original Symbol object from various sources
- if _original_symbol_arg is not None and str(_original_symbol_arg).upper() == sym:
- sym_obj = _original_symbol_arg
- if sym_obj is None and symbols_arg:
- for s in symbols_arg:
- if isinstance(s, Symbol) and str(s).upper() == sym:
- sym_obj = s
- break
- if sym_obj is None:
- for a in args:
- if isinstance(a, Symbol) and str(a).upper() == sym:
- sym_obj = a
- break
- # Check if the symbol is a future
- is_future = False
- if sym_obj and getattr(sym_obj, 'security_type', None) == SecurityType.FUTURE:
- is_future = True
- elif sym in self.securities and getattr(self.securities[sym].symbol, 'security_type', None) == SecurityType.FUTURE:
- is_future = True
- # For continuous futures: ~2 rolls per year (quarterly); for equities: ~2 over entire range
- if start_time and end_time:
- range_days = (end_time - start_time).days
- range_years = max(1, range_days / 365.0)
- if is_future:
- per_sym = max(1, int(range_years * 1.8)) # ~1.8 per year
- else:
- per_sym = 2 # Equity remaps are rare
- event_start = start_time
- elif count_arg is not None:
- if is_future:
- per_sym = max(1, count_arg // 60)
- else:
- per_sym = 2
- event_start = now - timedelta(days=count_arg)
- else:
- per_sym = 2
- event_start = now - timedelta(days=365 * 2)
- interval = max(1, ((end_time or now) - event_start).days // max(1, per_sym))
- for i in range(per_sym):
- d = event_start + timedelta(days=interval * (i + 1))
- tuples.append((sym, d))
- data_rows.append({
- 'oldsymbol': sym if i % 2 == 0 else f'{sym}A',
- 'newsymbol': f'{sym}A' if i % 2 == 0 else sym,
- 'type': 0,
- 'value': 0.0,
- })
- idx = pd.MultiIndex.from_tuples(tuples, names=['symbol', 'time'])
- df = pd.DataFrame(data_rows, index=idx)
- return _HistoryDataFrame(df)
-
- # Check if this is an option universe history request
- # When the symbol is an option type and flatten=True, return option chain data
- _is_option_sym = False
- if sym_names and len(sym_names) == 1:
- s_name = sym_names[0]
- sec = self.securities.get(s_name)
- if sec:
- st = getattr(sec.symbol, 'security_type', None) if hasattr(sec, 'symbol') else None
- if st in (SecurityType.OPTION, SecurityType.INDEX_OPTION, SecurityType.FUTURE_OPTION):
- _is_option_sym = True
-
- if _is_option_sym and flatten:
- from .enums import OptionRight
- sym_name = sym_names[0]
- sec = self.securities[sym_name]
- sym_obj = sec.symbol if hasattr(sec, 'symbol') else Symbol(sym_name)
- tuples = []
- data_rows = []
- for i in range(num_rows):
- d = now - timedelta(days=(num_rows - i))
- # Get option contracts for this date using the provider
- contracts = list(self.option_chain_provider.get_option_contract_list(sym_obj, d))
- for contract_sym in contracts:
- tuples.append((d, contract_sym))
- strike = getattr(contract_sym, 'strike_price', 100.0)
- data_rows.append({
- 'close': strike, 'open': strike - 0.5,
- 'high': strike + 1.0, 'low': strike - 1.0,
- 'volume': 100000.0, 'value': strike,
- })
- idx = pd.MultiIndex.from_tuples(tuples, names=['time', 'symbol'])
- df = pd.DataFrame(data_rows, index=idx)
- return _HistoryDataFrame(df)
-
- # Generate standard synthetic OHLCV data
- base_price = 100.0
- is_multi = len(sym_names) > 1
-
- if is_multi:
- tuples = []
- data_rows = []
- for sym in sym_names:
- for i in range(num_rows):
- d = now - timedelta(days=(num_rows - i))
- tuples.append((sym, d))
- p = base_price + i * 0.01
- data_rows.append({
- 'open': p - 0.5, 'high': p + 1.0, 'low': p - 1.0,
- 'close': p, 'volume': 1000000.0, 'value': p
- })
- idx = pd.MultiIndex.from_tuples(tuples, names=['symbol', 'time'])
- df = pd.DataFrame(data_rows, index=idx)
- return _HistoryDataFrame(df)
-
- # Single symbol — use MultiIndex (symbol, time) so .unstack(0) works
- sym = sym_names[0] if sym_names else 'SPY'
- tuples = []
- data_rows = []
- for i in range(num_rows):
- d = now - timedelta(days=(num_rows - i))
- tuples.append((sym, d))
- p = base_price + i * 0.01
- data_rows.append({
- 'open': p - 0.5, 'high': p + 1.0, 'low': p - 1.0,
- 'close': p, 'volume': 1000000.0, 'value': p
- })
- idx = pd.MultiIndex.from_tuples(tuples, names=['symbol', 'time'])
- df = pd.DataFrame(data_rows, index=idx)
- return _HistoryDataFrame(df)
-
- # ---- Order Methods ----
-
- def _next_order_id(self) -> int:
- self.transactions._order_counter += 1
- return self.transactions._order_counter
-
- def market_order(self, symbol, quantity, asynchronous=False, tag="",
- order_properties=None):
- oid = self._next_order_id()
- sym = Symbol(str(symbol).upper()) if not isinstance(symbol, Symbol) else symbol
- ticket = OrderTicket(oid, sym, quantity, OrderType.MARKET, tag=tag)
- self.transactions._orders[oid] = ticket
-
- # Simulate immediate fill for backtesting
- price = self.securities[str(symbol)].price if str(symbol) in self.securities else 0
- if price > 0:
- ticket.average_fill_price = price
- ticket.quantity_filled = quantity
- ticket.status = OrderStatus.FILLED
- self.portfolio.process_fill(str(symbol), quantity, price)
-
- event = OrderEvent(oid, sym, OrderStatus.FILLED, price, quantity)
- self.on_order_event(event)
-
- return ticket
-
- def limit_order(self, symbol, quantity, limit_price, tag="", order_properties=None):
- oid = self._next_order_id()
- sym = Symbol(str(symbol).upper()) if not isinstance(symbol, Symbol) else symbol
- ticket = OrderTicket(oid, sym, quantity, OrderType.LIMIT,
- limit_price=limit_price, tag=tag)
- self.transactions._orders[oid] = ticket
- return ticket
-
- def stop_market_order(self, symbol, quantity, stop_price, tag="", order_properties=None):
- oid = self._next_order_id()
- sym = Symbol(str(symbol).upper()) if not isinstance(symbol, Symbol) else symbol
- ticket = OrderTicket(oid, sym, quantity, OrderType.STOP_MARKET,
- stop_price=stop_price, tag=tag)
- self.transactions._orders[oid] = ticket
- return ticket
-
- def stop_limit_order(self, symbol, quantity, stop_price, limit_price, tag="", order_properties=None):
- oid = self._next_order_id()
- sym = Symbol(str(symbol).upper()) if not isinstance(symbol, Symbol) else symbol
- ticket = OrderTicket(oid, sym, quantity, OrderType.STOP_LIMIT,
- limit_price=limit_price, stop_price=stop_price, tag=tag)
- self.transactions._orders[oid] = ticket
- return ticket
-
- def trailing_stop_order(self, symbol, quantity, trailing_amount=None,
- trailing_as_percentage=False, tag="", order_properties=None):
- oid = self._next_order_id()
- sym = Symbol(str(symbol).upper()) if not isinstance(symbol, Symbol) else symbol
- ticket = OrderTicket(oid, sym, quantity, OrderType.TRAILING_STOP, tag=tag)
- self.transactions._orders[oid] = ticket
- return ticket
-
- def market_on_open_order(self, symbol, quantity, tag=""):
- oid = self._next_order_id()
- sym = Symbol(str(symbol).upper()) if not isinstance(symbol, Symbol) else symbol
- ticket = OrderTicket(oid, sym, quantity, OrderType.MARKET_ON_OPEN, tag=tag)
- self.transactions._orders[oid] = ticket
- return ticket
-
- def market_on_close_order(self, symbol, quantity, tag=""):
- oid = self._next_order_id()
- sym = Symbol(str(symbol).upper()) if not isinstance(symbol, Symbol) else symbol
- ticket = OrderTicket(oid, sym, quantity, OrderType.MARKET_ON_CLOSE, tag=tag)
- self.transactions._orders[oid] = ticket
- return ticket
-
- def limit_if_touched_order(self, symbol, quantity, trigger_price, limit_price, tag=""):
- oid = self._next_order_id()
- sym = Symbol(str(symbol).upper()) if not isinstance(symbol, Symbol) else symbol
- ticket = OrderTicket(oid, sym, quantity, OrderType.LIMIT_IF_TOUCHED,
- limit_price=limit_price, stop_price=trigger_price, tag=tag)
- self.transactions._orders[oid] = ticket
- return ticket
-
- def buy(self, symbol, quantity):
- return self.market_order(symbol, abs(quantity))
-
- def sell(self, symbol, quantity):
- return self.market_order(symbol, -abs(quantity))
-
- def order(self, symbol, quantity, **kwargs):
- return self.market_order(symbol, quantity, **kwargs)
-
- def set_holdings(self, symbol_or_targets, percentage=None, liquidate_existing=False,
- tag="", order_properties=None):
- """Set portfolio to target percentage allocation."""
- if isinstance(symbol_or_targets, list):
- # List of PortfolioTarget
- if liquidate_existing:
- self.liquidate(tag=tag)
- for target in symbol_or_targets:
- sym = target.symbol if hasattr(target, 'symbol') else target
- pct = target.quantity if hasattr(target, 'quantity') else percentage
- self._set_holdings_single(str(sym), pct, tag)
- return
-
- if percentage is not None:
- if liquidate_existing:
- self.liquidate(tag=tag)
- self._set_holdings_single(str(symbol_or_targets), percentage, tag)
-
- def _set_holdings_single(self, ticker: str, percentage: float, tag: str = ""):
- ticker = ticker.upper()
- price = self.securities[ticker].price if ticker in self.securities else 0
- if price == 0:
- return
-
- portfolio_value = self.portfolio.total_portfolio_value
- target_value = portfolio_value * percentage
- current_holding = self.portfolio[ticker].quantity
- current_value = current_holding * price
- diff_value = target_value - current_value
-
- if abs(diff_value) < price:
- return
-
- quantity = int(diff_value / price)
- if quantity != 0:
- self.market_order(ticker, quantity, tag=tag)
-
- def liquidate(self, symbol=None, tag="", order_properties=None):
- """Liquidate all or specific holdings."""
- if symbol:
- ticker = str(symbol).upper()
- qty = self.portfolio[ticker].quantity
- if qty != 0:
- self.market_order(ticker, -qty, tag=tag)
- else:
- for ticker, holding in list(self.portfolio.items()):
- if holding.quantity != 0:
- self.market_order(ticker, -holding.quantity, tag=tag)
-
- def can_liquidate(self, symbol):
- ticker = str(symbol).upper()
- return self.portfolio[ticker].quantity != 0
-
- # ---- Indicator Factory Methods ----
-
- def ema(self, symbol, period, resolution=None, selector=None):
- name = f"EMA_{symbol}_{period}"
- indicator = ExponentialMovingAverage(name, period)
- self._indicators[name] = indicator
- return indicator
-
- def sma(self, symbol, period, resolution=None, selector=None):
- name = f"SMA_{symbol}_{period}"
- indicator = SimpleMovingAverage(name, period)
- self._indicators[name] = indicator
- return indicator
-
- def macd(self, symbol, fast_period=12, slow_period=26, signal_period=9,
- moving_average_type=None, resolution=None, selector=None):
- name = f"MACD_{symbol}"
- indicator = MovingAverageConvergenceDivergence(name, fast_period, slow_period, signal_period)
- self._indicators[name] = indicator
- return indicator
-
- def rsi(self, symbol, period=14, moving_average_type=None, resolution=None, selector=None):
- name = f"RSI_{symbol}_{period}"
- indicator = RelativeStrengthIndex(name, period, moving_average_type)
- if isinstance(self._indicators, dict):
- self._indicators[name] = indicator
- return indicator
-
- def b(self, symbol, reference_symbol=None, period=14, resolution=None, selector=None):
- """Beta indicator."""
- name = f"BETA_{symbol}_{period}"
- from .algorithm_imports import Beta
- indicator = Beta(name, period)
- if isinstance(self._indicators, dict):
- self._indicators[name] = indicator
- return indicator
-
- def bb(self, symbol, period=20, k=2.0, moving_average_type=None, resolution=None, selector=None):
- name = f"BB_{symbol}_{period}"
- indicator = BollingerBands(name, period, k)
- if isinstance(self._indicators, dict):
- self._indicators[name] = indicator
- return indicator
-
- def atr(self, symbol, period=14, moving_average_type=None, resolution=None, selector=None):
- name = f"ATR_{symbol}_{period}"
- indicator = AverageTrueRange(name, period)
- if isinstance(self._indicators, dict):
- self._indicators[name] = indicator
- return indicator
-
- def sto(self, symbol, period=14, k_period=3, d_period=3, resolution=None):
- name = f"STO_{symbol}_{period}"
- indicator = Stochastic(name, period, k_period, d_period)
- self._indicators[name] = indicator
- return indicator
-
- def roc(self, symbol, period=14, resolution=None):
- name = f"ROC_{symbol}_{period}"
- indicator = RateOfChange(name, period)
- self._indicators[name] = indicator
- return indicator
-
- def mom(self, symbol, period=14, resolution=None, selector=None):
- name = f"MOM_{symbol}_{period}"
- indicator = Momentum(name, period)
- if isinstance(self._indicators, dict):
- self._indicators[name] = indicator
- return indicator
-
- def wilr(self, symbol, period=14, resolution=None):
- name = f"WILR_{symbol}_{period}"
- indicator = WilliamsPercentR(name, period)
- self._indicators[name] = indicator
- return indicator
-
- def cci(self, symbol, period=20, resolution=None):
- name = f"CCI_{symbol}_{period}"
- indicator = CommodityChannelIndex(name, period)
- self._indicators[name] = indicator
- return indicator
-
- def adx(self, symbol, period=14, resolution=None):
- name = f"ADX_{symbol}_{period}"
- indicator = AverageDirectionalIndex(name, period)
- self._indicators[name] = indicator
- return indicator
-
- def identity(self, symbol, resolution=None, selector=None, name=None):
- """Identity indicator (returns input value unchanged)."""
- ind_name = name or f"ID_{symbol}"
- indicator = SimpleMovingAverage(ind_name, 1)
- self._indicators[ind_name] = indicator
- return indicator
-
- def filtered_identity(self, symbol, filter_func=None, resolution=None):
- """Filtered identity indicator."""
- name = f"FID_{symbol}"
- indicator = SimpleMovingAverage(name, 1)
- self._indicators[name] = indicator
- return indicator
-
- def rc(self, symbol, period=20, resolution=None, selector=None):
- """Regression Channel indicator."""
- name = f"RC_{symbol}_{period}"
- indicator = SimpleMovingAverage(name, period)
- # Add regression channel-specific attributes
- indicator.linear_regression = SimpleMovingAverage(f"RC_LR_{symbol}", period)
- indicator.upper_channel = SimpleMovingAverage(f"RC_UC_{symbol}", period)
- indicator.lower_channel = SimpleMovingAverage(f"RC_LC_{symbol}", period)
- indicator.intercept = SimpleMovingAverage(f"RC_INT_{symbol}", period)
- indicator.slope = SimpleMovingAverage(f"RC_SLP_{symbol}", period)
- self._indicators[name] = indicator
- return indicator
-
- def std(self, symbol, period=20, resolution=None, selector=None):
- """Standard Deviation indicator."""
- name = f"STD_{symbol}_{period}"
- indicator = SimpleMovingAverage(name, period)
- # Add std-specific attributes
- indicator._std_window = deque(maxlen=period)
- indicator._orig_compute = indicator._compute
- def _std_compute(value):
- indicator._std_window.append(value)
- if len(indicator._std_window) < 2:
- return 0.0
- mean = sum(indicator._std_window) / len(indicator._std_window)
- variance = sum((x - mean) ** 2 for x in indicator._std_window) / len(indicator._std_window)
- return variance ** 0.5
- indicator._compute = _std_compute
- if isinstance(self._indicators, dict):
- self._indicators[name] = indicator
- return indicator
-
- def min(self, symbol, period=14, resolution=None, selector=None):
- """Minimum indicator - tracks lowest value over period."""
- name = f"MIN_{symbol}_{period}"
- indicator = SimpleMovingAverage(name, period)
- indicator._min_window = deque(maxlen=period)
- def _min_compute(value):
- indicator._min_window.append(value)
- return __builtins__['min'](indicator._min_window) if isinstance(__builtins__, dict) else min(indicator._min_window)
- indicator._compute = _min_compute
- if isinstance(self._indicators, dict):
- self._indicators[name] = indicator
- return indicator
-
- def max(self, symbol, period=14, resolution=None, selector=None):
- """Maximum indicator - tracks highest value over period."""
- name = f"MAX_{symbol}_{period}"
- indicator = SimpleMovingAverage(name, period)
- indicator._max_window = deque(maxlen=period)
- def _max_compute(value):
- indicator._max_window.append(value)
- return __builtins__['max'](indicator._max_window) if isinstance(__builtins__, dict) else max(indicator._max_window)
- indicator._compute = _max_compute
- if isinstance(self._indicators, dict):
- self._indicators[name] = indicator
- return indicator
-
- def aroon(self, symbol, period=20, resolution=None, selector=None):
- """Aroon indicator."""
- name = f"AROON_{symbol}_{period}"
- indicator = SimpleMovingAverage(name, period)
- indicator.aroon_up = SimpleMovingAverage(f"AROON_UP_{symbol}", period)
- indicator.aroon_down = SimpleMovingAverage(f"AROON_DOWN_{symbol}", period)
- if isinstance(self._indicators, dict):
- self._indicators[name] = indicator
- return indicator
-
- def register_indicator(self, symbol, indicator, resolution_or_consolidator=None, selector=None):
- if isinstance(self._indicators, dict):
- name = getattr(indicator, 'name', str(id(indicator)))
- self._indicators[name] = indicator
- # If _indicators was overridden to a list by user code, don't break it
-
- def unregister_indicator(self, indicator):
- name = getattr(indicator, 'name', str(id(indicator)))
- self._indicators.pop(name, None)
-
- def indicator_history(self, indicator, symbol_or_symbols, period_or_start,
- resolution=None, selector=None):
- if pd:
- return pd.DataFrame()
- return []
-
- def resolve_consolidator(self, symbol, resolution, data_type=None):
- """Resolve a consolidator for the given symbol and resolution."""
- from .consolidators import TradeBarConsolidator
- if isinstance(resolution, timedelta):
- return TradeBarConsolidator(resolution)
- return TradeBarConsolidator(timedelta(minutes=1))
-
- def create_indicator_name(self, symbol, indicator_type, resolution):
- """Create a standard indicator name."""
- return f"{indicator_type}({symbol},{resolution})"
-
- # ---- Data Consolidation ----
-
- def consolidate(self, symbol, period_or_type, handler=None, tick_type=None):
- if isinstance(period_or_type, timedelta):
- consolidator = TradeBarConsolidator(period_or_type)
- elif isinstance(period_or_type, int):
- consolidator = TradeBarConsolidator(max_count=period_or_type)
- else:
- consolidator = TradeBarConsolidator(timedelta(days=1))
-
- if handler:
- consolidator.data_consolidated = handler
-
- self._consolidators.append({'symbol': str(symbol), 'consolidator': consolidator})
- return consolidator
-
- # ---- Universe Methods ----
-
- def add_universe(self, *args, **kwargs):
- """Add a universe selection model or function."""
- # If asynchronous universe settings + coarse/fine function combo, raise
- if getattr(self.universe_settings, 'asynchronous', False) and len(args) >= 2:
- if callable(args[0]) and callable(args[1]):
- raise ValueError("Asynchronous universe selection does not support coarse/fine function combo. Use FineFundamentalUniverseSelectionModel instead.")
- # Detect universe type
- data_type = None
- is_etf = False
- selector = args[0] if args else None
- if args and isinstance(args[0], type) and hasattr(args[0], 'reader'):
- # Custom PythonData universe type (e.g., StockDataSource)
- data_type = args[0]
- selector = args[1] if len(args) > 1 else None
- elif args and isinstance(args[0], _UniverseReference):
- return args[0]
- elif args and hasattr(args[0], '_is_etf'):
- # ETF universe (e.g., self.universe.etf(spy, settings, filter))
- etf_settings = args[0]
- ref = _UniverseReference(getattr(etf_settings, '_filter_func', None), is_etf=True)
- ref._etf_settings = etf_settings
- return ref
- return _UniverseReference(selector, data_type=data_type, is_etf=is_etf)
-
- def add_universe_options(self, *args, **kwargs):
- pass
-
- def set_universe_selection(self, model):
- self._universe_selection = model
-
- def add_universe_selection(self, model):
- self._universe_selection = model
-
- # ---- Framework Model Methods ----
-
- def set_alpha(self, model):
- self._alpha_model = model
-
- def add_alpha(self, model):
- self._alpha_model = model
-
- def set_portfolio_construction(self, model):
- self._portfolio_construction = model
-
- def set_execution(self, model):
- self._execution_model = model
-
- def set_risk_management(self, model):
- self._risk_management = model
-
- def add_risk_management(self, model):
- self._risk_management = model
-
- def emit_insights(self, *insights):
- pass
-
- # ---- Charting & Logging ----
-
- def plot(self, chart_name: str, series_name: str = None,
- value: float = None, *args):
- if chart_name not in self._charts:
- self._charts[chart_name] = {}
- if series_name and value is not None:
- if series_name not in self._charts[chart_name]:
- self._charts[chart_name][series_name] = []
- self._charts[chart_name][series_name].append({
- 'time': self._time.isoformat(),
- 'value': value
- })
-
- def add_chart(self, chart):
- name = chart.name if hasattr(chart, 'name') else str(chart)
- self._charts[name] = {}
-
- def log(self, message: str):
- entry = f"[{self._time}] {message}"
- self._logs.append(entry)
- logger.info(entry)
-
- def debug(self, message: str):
- self._debug_msgs.append(f"[{self._time}] {message}")
- logger.debug(message)
-
- def error(self, message: str):
- logger.error(f"[{self._time}] {message}")
-
- def quit(self, message: str = ""):
- logger.info(f"Algorithm quit: {message}")
-
- def set_runtime_statistic(self, name: str, value):
- self._runtime_statistics[name] = str(value)
-
- def set_summary_statistic(self, name: str, value):
- self._runtime_statistics[name] = str(value)
-
- # ---- Parameter Methods ----
-
- def get_parameter(self, name: str, default_value=None):
- val = self._parameters.get(name, None)
- if val is None:
- return default_value
- # Coerce to the type of default_value if provided
- if default_value is not None:
- try:
- if isinstance(default_value, int) and not isinstance(default_value, bool):
- return int(val)
- elif isinstance(default_value, float):
- return float(val)
- except (ValueError, TypeError):
- pass
- return val
-
- def set_parameters(self, params: dict):
- self._parameters.update(params)
-
- # ---- Security Initializer ----
-
- def set_security_initializer(self, initializer):
- self.security_initializer = initializer
-
- # ---- Utility Methods ----
-
- def symbol(self, ticker: str) -> Symbol:
- return Symbol(ticker.upper())
-
- def download(self, url: str, headers=None) -> str:
- try:
- import urllib.request
- req = urllib.request.Request(url)
- if headers:
- for k, v in headers.items():
- req.add_header(k, v)
- with urllib.request.urlopen(req) as resp:
- return resp.read().decode('utf-8')
- except Exception as e:
- self.error(f"Download failed: {e}")
- return ""
-
- def train(self, *args):
- """Execute a training function. Can be train(func) or train(date_rule, time_rule, func)."""
- func = args[-1] if args else None
- if callable(func):
- func()
-
- def add_command(self, command_type, handler=None):
- """Register a command handler. Validates the command type has a 'run' method."""
- if isinstance(command_type, type) and not hasattr(command_type, 'run'):
- raise ValueError(f"Command type '{command_type.__name__}' does not have a 'run' method")
-
- def link(self, command):
- """Generate a command link URL string for a command object."""
- import urllib.parse
-
- def _encode_value(key, val, parts):
- if isinstance(val, dict):
- for k, v in val.items():
- parts.append(f"command[{key}][{k}]={urllib.parse.quote_plus(str(v))}")
- elif isinstance(val, (list, tuple)):
- for i, v in enumerate(val):
- parts.append(f"command[{key}][{i}]={urllib.parse.quote_plus(str(v))}")
- elif val is None:
- pass # skip None values
- else:
- parts.append(f"command[{key}]={urllib.parse.quote_plus(str(val))}")
-
- parts = []
-
- if isinstance(command, dict):
- for attr, val in command.items():
- _encode_value(attr, val, parts)
- return "&" + "&".join(parts)
-
- # Object command — collect all public non-callable attrs
- # Sort alphabetically to match LEAN's serialization order
- type_name = command.__class__.__name__
- skip_attrs = {'name'}
- attrs_map = {}
-
- # Collect from class body
- for attr in command.__class__.__dict__:
- if attr.startswith('_') or attr in skip_attrs:
- continue
- val = getattr(command, attr)
- if callable(val):
- continue
- attrs_map[attr] = val
-
- # Collect from instance
- for attr in vars(command):
- if attr.startswith('_') or attr in skip_attrs:
- continue
- val = getattr(command, attr)
- if callable(val):
- continue
- attrs_map[attr] = val
-
- # Sort alphabetically
- for attr in sorted(attrs_map.keys()):
- _encode_value(attr, attrs_map[attr], parts)
- parts.append(f"command[$type]={type_name}")
- return "&" + "&".join(parts)
-
- def fundamentals(self, symbol=None):
- """Get fundamental data for a symbol or list of symbols."""
- if isinstance(symbol, (list, tuple)):
- return [self.fundamentals(s) for s in symbol]
- # Try to get price from securities
- price = 100.0
- sym_str = str(symbol).upper() if symbol else ''
- if sym_str in self.securities:
- sec_price = self.securities[sym_str].price
- if sec_price > 0:
- price = sec_price
- from .algorithm_imports import Fundamental as _Fundamental
- result = _Fundamental(
- price=price,
- end_time=self._time or self._start_date,
- symbol=symbol,
- dollar_volume=1e8,
- volume=1000000,
- market_cap=1e10,
- has_fundamental_data=True,
- )
- return result
-
- def cusip(self, symbol):
- """Get CUSIP for a symbol."""
- sym = symbol if isinstance(symbol, Symbol) else Symbol(str(symbol))
- return sym.cusip
-
- def composite_figi(self, symbol):
- """Get Composite FIGI for a symbol."""
- sym = symbol if isinstance(symbol, Symbol) else Symbol(str(symbol))
- return sym.composite_figi
-
- def sedol(self, symbol):
- """Get SEDOL for a symbol."""
- sym = symbol if isinstance(symbol, Symbol) else Symbol(str(symbol))
- return sym.sedol
-
- def isin(self, symbol):
- """Get ISIN for a symbol."""
- sym = symbol if isinstance(symbol, Symbol) else Symbol(str(symbol))
- return sym.isin
-
- def cik(self, symbol):
- """Get CIK for a symbol."""
- sym = symbol if isinstance(symbol, Symbol) else Symbol(str(symbol))
- return sym.cik
-
- def option_chain(self, symbol, flatten=False):
- """Get option chain for symbol. Returns OptionChainResult with contracts."""
- from .enums import OptionRight, OptionStyle
- underlying = symbol if isinstance(symbol, Symbol) else Symbol(str(symbol).upper())
- chain = _OptionChainResult(underlying)
-
- # Determine underlying properties
- ticker_str = str(underlying).upper()
- und_sec_type = getattr(underlying, 'security_type', SecurityType.EQUITY)
-
- # Determine option SecurityType, Market, and Style based on underlying
- if und_sec_type == SecurityType.FUTURE:
- opt_sec_type = SecurityType.FUTURE_OPTION
- opt_market = getattr(underlying, 'market', Market.CME)
- opt_style = OptionStyle.AMERICAN
- elif und_sec_type == SecurityType.INDEX:
- opt_sec_type = SecurityType.INDEX_OPTION
- opt_market = Market.USA
- opt_style = OptionStyle.EUROPEAN
- else:
- opt_sec_type = SecurityType.OPTION
- opt_market = Market.USA
- opt_style = OptionStyle.AMERICAN
-
- # Determine base price
- base_price = 100.0
- sec = self.securities.get(ticker_str)
- if sec and sec.price > 0:
- base_price = sec.price
- else:
- _default_prices = {
- 'SPX': 3800.0, 'SPXW': 3800.0, 'NDX': 13000.0, 'SPY': 380.0, 'QQQ': 310.0,
- 'ES': 3200.0, 'NQ': 13000.0, 'YM': 30000.0, 'RTY': 1800.0, 'MES': 3200.0,
- 'GOOG': 750.0, 'GOOGL': 750.0, 'AAPL': 150.0, 'MSFT': 300.0, 'AMZN': 3200.0,
- 'TSLA': 700.0, 'NVDA': 250.0, 'META': 250.0, 'NFLX': 500.0,
- 'GC': 1800.0, 'SI': 25.0, 'CL': 70.0, 'NG': 4.0,
- 'DC': 17.0, 'ZC': 400.0, 'ZW': 600.0, 'ZS': 1200.0,
- # Full-name future tickers (used by Futures.Dairy.CLASS_III_MILK etc.)
- 'CLASS_III_MILK': 17.0, 'BUTTER': 2.0, 'CASH_SETTLED_CHEESE': 2.0,
- 'SP_500_E_MINI': 3200.0, 'E_MINI': 3200.0,
- }
- if ticker_str in _default_prices:
- base_price = _default_prices[ticker_str]
-
- # Store base_price on underlying for _OptionContract IV calculation
- underlying._chain_base_price = base_price
-
- now = self._time or self._start_date or datetime.now()
-
- # Generate strike offsets proportional to base price
- if base_price > 1000:
- strike_offsets = [-800, -600, -450, -400, -200, -100, -50, 0, 50, 100, 200, 400, 450, 600, 800]
- elif base_price > 200:
- strike_offsets = [-100, -50, -20, -10, -5, 0, 5, 10, 20, 50, 100]
- else:
- strike_offsets = [-30, -20, -10, -5, -3, 0, 3, 5, 10, 20, 30]
-
- # Generate expiry dates - use standard monthly options (3rd Friday of month)
- # for the next few months from the algorithm's current time
- def _third_friday(year, month):
- """Get the third Friday of a given month/year."""
- import calendar
- c = calendar.Calendar(firstweekday=calendar.MONDAY)
- fridays = [d for d in c.itermonthdays2(year, month)
- if d[0] != 0 and d[1] == calendar.FRIDAY]
- return datetime(year, month, fridays[2][0])
-
- # For futures, use the underlying's expiry date if available
- und_expiry = getattr(underlying, 'expiry', None)
- expiry_dates = []
- if und_expiry:
- # For future options, the option expires on the same date as the future
- expiry_dates = [und_expiry]
- else:
- # Generate monthly expiry dates for the next 4 months
- for m_offset in range(0, 4):
- y = now.year
- m = now.month + m_offset
- while m > 12:
- m -= 12
- y += 1
- try:
- exp = _third_friday(y, m)
- # Only include expiries in the future
- if exp >= now - timedelta(days=1):
- expiry_dates.append(exp)
- except Exception:
- pass
- # Also add a near-term expiry (7 days out) ONLY if it doesn't overlap with monthly
- near_exp = now + timedelta(days=7)
- if not any(abs((near_exp - e).days) < 5 for e in expiry_dates):
- expiry_dates.append(near_exp)
-
- for expiry in expiry_dates:
- for strike_offset in strike_offsets:
- strike = base_price + strike_offset
- if strike <= 0:
- continue
- for right in [OptionRight.CALL, OptionRight.PUT]:
- right_char = 'C' if right == OptionRight.CALL else 'P'
- ticker = f"{ticker_str}{expiry.strftime('%y%m%d')}{right_char}{int(strike)}"
- opt_sym = Symbol(ticker, opt_sec_type, opt_market)
- opt_sym.expiry = expiry
- opt_sym.strike_price = float(strike)
- opt_sym.right = right
- opt_sym.option_style = opt_style
- opt_sym._underlying = underlying
- opt_sym.id = type('SymbolId', (), {
- 'strike_price': float(strike), 'option_right': right,
- 'date': expiry, 'expiration': expiry,
- 'underlying': underlying
- })()
- contract = _OptionContract(opt_sym, underlying, strike, right, expiry)
- chain.contracts[str(opt_sym)] = contract
- chain._list.append(contract)
- return chain
-
- @property
- def option_chain_provider(self):
- return OptionChainProvider(self)
-
- def is_market_open(self, symbol=None):
- """Check if market is currently open."""
- if symbol and str(symbol) in self.securities:
- return self.securities[str(symbol)].exchange.exchange_open
- return True
-
- def plot_indicator(self, chart_name, wait_for_ready=True, *indicators):
- """Plot indicator values on a chart."""
- for indicator in indicators:
- name = getattr(indicator, 'name', str(indicator))
- value = float(indicator) if hasattr(indicator, '__float__') else 0
- self.plot(chart_name, name, value)
-
- # ---- Combo Order Methods ----
-
- def combo_market_order(self, legs, quantity, asynchronous=False, tag="", order_properties=None):
- """Submit a combo market order (multi-leg)."""
- tickets = []
- for leg in legs:
- sym = leg.symbol if hasattr(leg, 'symbol') else leg
- qty = leg.quantity if hasattr(leg, 'quantity') else quantity
- ticket = self.market_order(sym, qty, tag=tag)
- tickets.append(ticket)
- return tickets
-
- def combo_limit_order(self, legs, quantity, limit_price, tag="", order_properties=None):
- """Submit a combo limit order."""
- tickets = []
- for leg in legs:
- sym = leg.symbol if hasattr(leg, 'symbol') else leg
- qty = leg.quantity if hasattr(leg, 'quantity') else quantity
- ticket = self.limit_order(sym, qty, limit_price, tag=tag)
- tickets.append(ticket)
- return tickets
-
- def combo_leg_limit_order(self, legs, quantity, tag="", order_properties=None):
- """Submit combo leg limit orders."""
- tickets = []
- for leg in legs:
- sym = leg.symbol if hasattr(leg, 'symbol') else leg
- qty = leg.quantity if hasattr(leg, 'quantity') else quantity
- price = leg.limit_price if hasattr(leg, 'limit_price') else 0
- ticket = self.limit_order(sym, qty, price, tag=tag)
- tickets.append(ticket)
- return tickets
-
- # ---- Additional Indicator Shortcuts ----
-
- def aroon(self, symbol, period=25, resolution=None, selector=None):
- """Aroon indicator (stub using SMA as placeholder)."""
- name = f"AROON_{symbol}_{period}"
- indicator = SimpleMovingAverage(name, period)
- self._indicators[name] = indicator
- return indicator
-
- def vwap(self, symbol, resolution=None, selector=None):
- """VWAP indicator (stub)."""
- name = f"VWAP_{symbol}"
- indicator = SimpleMovingAverage(name, 1)
- self._indicators[name] = indicator
- return indicator
-
- def momp(self, symbol, period=14, resolution=None, selector=None):
- """Momentum Percent indicator."""
- name = f"MOMP_{symbol}_{period}"
- indicator = RateOfChange(name, period)
- self._indicators[name] = indicator
- return indicator
-
- def trin(self, symbol, resolution=None, selector=None):
- """TRIN (Arms Index) indicator (stub)."""
- name = f"TRIN_{symbol}"
- indicator = SimpleMovingAverage(name, 1)
- self._indicators[name] = indicator
- return indicator
-
- # ---- Additional Utility Methods ----
-
- def get_last_known_prices(self, symbol=None):
- """Get the last known prices for a security."""
- if symbol and str(symbol) in self.securities:
- sec = self.securities[str(symbol)]
- return [sec]
- return []
-
- def warm_up_indicator(self, symbol, indicator, resolution=None, selector=None):
- """Warm up an indicator with historical data."""
- period = getattr(indicator, 'warm_up_period', 0)
- if period <= 0:
- # Indicator doesn't define a warm-up period, skip
- return indicator
- base_price = 100.0
- now = self._time or datetime.now()
- for i in range(period):
- t = now - timedelta(days=(period - i))
- p = base_price + i * 0.1
- # Create a bar-like object for indicators that accept bars
- bar = type('WarmUpBar', (), {
- 'time': t, 'end_time': t,
- 'open': p - 0.5, 'high': p + 1.0, 'low': p - 1.0,
- 'close': p, 'volume': 1000000, 'value': p, 'price': p,
- })()
- # Track samples manually for PythonIndicator subclasses
- old_samples = getattr(indicator, 'samples', 0)
- try:
- indicator.update(bar)
- except TypeError:
- try:
- indicator.update(t, p)
- except Exception:
- pass
- # Ensure samples was incremented
- new_samples = getattr(indicator, 'samples', 0)
- if new_samples == old_samples:
- try:
- indicator.samples = old_samples + 1
- except AttributeError:
- pass
- indicator.is_ready = True
- return indicator
-
- def arima(self, symbol, ar_order=1, diff_order=0, ma_order=1, period=50, resolution=None, selector=None):
- """ARIMA indicator (stub)."""
- name = f"ARIMA_{symbol}_{ar_order}_{diff_order}_{ma_order}"
- indicator = SimpleMovingAverage(name, period)
- self._indicators[name] = indicator
- return indicator
-
- def iv(self, symbol, mirror_option=None, risk_free_rate=None, dividend_yield=None,
- option_model=None, period=None, resolution=None, **kwargs):
- """Implied Volatility indicator (stub)."""
- name = f"IV_{symbol}"
- indicator = _OptionGreekIndicator(name, period or 14)
- if isinstance(self._indicators, dict):
- self._indicators[name] = indicator
- return indicator
-
- def d(self, symbol, mirror_option=None, risk_free_rate=None, dividend_yield=None,
- option_model=None, period=None, resolution=None, **kwargs):
- """Delta indicator (stub)."""
- name = f"D_{symbol}"
- indicator = _OptionGreekIndicator(name, period or 14)
- if isinstance(self._indicators, dict):
- self._indicators[name] = indicator
- return indicator
-
- def g(self, symbol, mirror_option=None, risk_free_rate=None, dividend_yield=None,
- option_model=None, period=None, resolution=None, **kwargs):
- """Gamma indicator (stub)."""
- name = f"G_{symbol}"
- indicator = _OptionGreekIndicator(name, period or 14)
- if isinstance(self._indicators, dict):
- self._indicators[name] = indicator
- return indicator
-
- def r(self, symbol, mirror_option=None, risk_free_rate=None, dividend_yield=None,
- option_model=None, period=None, resolution=None, **kwargs):
- """Rho indicator (stub)."""
- name = f"R_{symbol}"
- indicator = _OptionGreekIndicator(name, period or 14)
- if isinstance(self._indicators, dict):
- self._indicators[name] = indicator
- return indicator
-
- def v(self, symbol, mirror_option=None, risk_free_rate=None, dividend_yield=None,
- option_model=None, period=None, resolution=None, **kwargs):
- """Vega indicator (stub)."""
- name = f"V_{symbol}"
- indicator = _OptionGreekIndicator(name, period or 14)
- if isinstance(self._indicators, dict):
- self._indicators[name] = indicator
- return indicator
-
- def t(self, symbol, mirror_option=None, risk_free_rate=None, dividend_yield=None,
- option_model=None, period=None, resolution=None, **kwargs):
- """Theta indicator (stub)."""
- name = f"T_{symbol}"
- indicator = _OptionGreekIndicator(name, period or 14)
- if isinstance(self._indicators, dict):
- self._indicators[name] = indicator
- return indicator
-
- @property
- def universe(self):
- """Universe manager."""
- return self.universe_settings
-
- # ---- PascalCase Aliases for LEAN/C# Compatibility ----
-
- def SetStartDate(self, *args, **kwargs):
- return self.set_start_date(*args, **kwargs)
-
- def SetEndDate(self, *args, **kwargs):
- return self.set_end_date(*args, **kwargs)
-
- def SetCash(self, *args, **kwargs):
- return self.set_cash(*args, **kwargs)
-
- def SetBenchmark(self, *args, **kwargs):
- return self.set_benchmark(*args, **kwargs)
-
- def SetBrokerageModel(self, *args, **kwargs):
- return self.set_brokerage_model(*args, **kwargs)
-
- def SetWarmUp(self, *args, **kwargs):
- return self.set_warmup(*args, **kwargs)
-
- def SetWarmup(self, *args, **kwargs):
- return self.set_warmup(*args, **kwargs)
-
- def AddEquity(self, *args, **kwargs):
- return self.add_equity(*args, **kwargs)
-
- def AddForex(self, *args, **kwargs):
- return self.add_forex(*args, **kwargs)
-
- def AddCrypto(self, *args, **kwargs):
- return self.add_crypto(*args, **kwargs)
-
- def AddFuture(self, *args, **kwargs):
- return self.add_future(*args, **kwargs)
-
- def AddOption(self, *args, **kwargs):
- return self.add_option(*args, **kwargs)
-
- def AddIndex(self, *args, **kwargs):
- return self.add_index(*args, **kwargs)
-
- def AddData(self, *args, **kwargs):
- return self.add_data(*args, **kwargs)
-
- def AddSecurity(self, *args, **kwargs):
- return self.add_security(*args, **kwargs)
-
- def MarketOrder(self, *args, **kwargs):
- return self.market_order(*args, **kwargs)
-
- def LimitOrder(self, *args, **kwargs):
- return self.limit_order(*args, **kwargs)
-
- def StopMarketOrder(self, *args, **kwargs):
- return self.stop_market_order(*args, **kwargs)
-
- def StopLimitOrder(self, *args, **kwargs):
- return self.stop_limit_order(*args, **kwargs)
-
- def SetHoldings(self, *args, **kwargs):
- return self.set_holdings(*args, **kwargs)
-
- def Liquidate(self, *args, **kwargs):
- return self.liquidate(*args, **kwargs)
-
- def Log(self, *args, **kwargs):
- return self.log(*args, **kwargs)
-
- def Debug(self, *args, **kwargs):
- return self.debug(*args, **kwargs)
-
- def Error(self, *args, **kwargs):
- return self.error(*args, **kwargs)
-
- def Plot(self, *args, **kwargs):
- return self.plot(*args, **kwargs)
-
- def History(self, *args, **kwargs):
- return self.history(*args, **kwargs)
-
- def Buy(self, *args, **kwargs):
- return self.buy(*args, **kwargs)
-
- def Sell(self, *args, **kwargs):
- return self.sell(*args, **kwargs)
-
- def Order(self, *args, **kwargs):
- return self.order(*args, **kwargs)
-
- def EMA(self, *args, **kwargs):
- return self.ema(*args, **kwargs)
-
- def SMA(self, *args, **kwargs):
- return self.sma(*args, **kwargs)
-
- def MACD(self, *args, **kwargs):
- return self.macd(*args, **kwargs)
-
- def RSI(self, *args, **kwargs):
- return self.rsi(*args, **kwargs)
-
- def BB(self, *args, **kwargs):
- return self.bb(*args, **kwargs)
-
- def ATR(self, *args, **kwargs):
- return self.atr(*args, **kwargs)
-
- def ROC(self, *args, **kwargs):
- return self.roc(*args, **kwargs)
-
- def MOM(self, *args, **kwargs):
- return self.mom(*args, **kwargs)
-
- def WILR(self, *args, **kwargs):
- return self.wilr(*args, **kwargs)
-
- def CCI(self, *args, **kwargs):
- return self.cci(*args, **kwargs)
-
- def ADX(self, *args, **kwargs):
- return self.adx(*args, **kwargs)
-
- def AROON(self, *args, **kwargs):
- return self.aroon(*args, **kwargs)
-
- def VWAP(self, *args, **kwargs):
- return self.vwap(*args, **kwargs)
-
- def MOMP(self, *args, **kwargs):
- return self.momp(*args, **kwargs)
-
- def GetParameter(self, *args, **kwargs):
- return self.get_parameter(*args, **kwargs)
-
- def SetParameters(self, *args, **kwargs):
- return self.set_parameters(*args, **kwargs)
-
- def Train(self, *args, **kwargs):
- return self.train(*args, **kwargs)
-
- def Download(self, *args, **kwargs):
- return self.download(*args, **kwargs)
-
- def Quit(self, *args, **kwargs):
- return self.quit(*args, **kwargs)
-
- def SetAlpha(self, *args, **kwargs):
- return self.set_alpha(*args, **kwargs)
-
- def AddAlpha(self, *args, **kwargs):
- return self.add_alpha(*args, **kwargs)
-
- def SetPortfolioConstruction(self, *args, **kwargs):
- return self.set_portfolio_construction(*args, **kwargs)
-
- def SetExecution(self, *args, **kwargs):
- return self.set_execution(*args, **kwargs)
-
- def SetRiskManagement(self, *args, **kwargs):
- return self.set_risk_management(*args, **kwargs)
-
- def AddRiskManagement(self, *args, **kwargs):
- return self.add_risk_management(*args, **kwargs)
-
- def SetUniverseSelection(self, *args, **kwargs):
- return self.set_universe_selection(*args, **kwargs)
-
- def AddUniverse(self, *args, **kwargs):
- return self.add_universe(*args, **kwargs)
-
- def AddChart(self, *args, **kwargs):
- return self.add_chart(*args, **kwargs)
-
- def SetSecurityInitializer(self, *args, **kwargs):
- return self.set_security_initializer(*args, **kwargs)
-
- def SetAccountCurrency(self, *args, **kwargs):
- return self.set_account_currency(*args, **kwargs)
-
- def SetTimeZone(self, *args, **kwargs):
- return self.set_time_zone(*args, **kwargs)
-
- def RegisterIndicator(self, *args, **kwargs):
- return self.register_indicator(*args, **kwargs)
-
- def Consolidate(self, *args, **kwargs):
- return self.consolidate(*args, **kwargs)
-
- def Initialize(self):
- return self.initialize()
-
- def GetLastKnownPrices(self, *args, **kwargs):
- return self.get_last_known_prices(*args, **kwargs)
-
- def WarmUpIndicator(self, *args, **kwargs):
- return self.warm_up_indicator(*args, **kwargs)
-
- def PlotIndicator(self, *args, **kwargs):
- return self.plot_indicator(*args, **kwargs)
-
- def FilteredIdentity(self, *args, **kwargs):
- return self.filtered_identity(*args, **kwargs)
-
- def CreateIndicatorName(self, *args, **kwargs):
- return self.create_indicator_name(*args, **kwargs)
-
- def IV(self, *args, **kwargs):
- return self.iv(*args, **kwargs)
-
- def D(self, *args, **kwargs):
- return self.d(*args, **kwargs)
-
- def G(self, *args, **kwargs):
- return self.g(*args, **kwargs)
-
- def T(self, *args, **kwargs):
- return self.t(*args, **kwargs)
-
- def R(self, *args, **kwargs):
- return self.r(*args, **kwargs)
-
- def V(self, *args, **kwargs):
- return self.v(*args, **kwargs)
-
- # ---- Properties with PascalCase aliases ----
-
- @property
- def Time(self):
- return self._time
-
- @property
- def UtcTime(self):
- return self._utc_time
-
- @property
- def StartDate(self):
- return self._start_date
-
- @property
- def EndDate(self):
- return self._end_date
-
- @property
- def IsWarmingUp(self):
- return self._is_warming_up
-
- @property
- def LiveMode(self):
- return self._live_mode
-
- @property
- def Portfolio(self):
- return self.portfolio
-
- @property
- def Securities(self):
- return self.securities
-
- @property
- def Name(self):
- return self._name
-
- @Name.setter
- def Name(self, value):
- self._name = value
-
- def __repr__(self):
- return f"FinceptStrategy({self._name})"
-
-
-class _ImpliedVolatilitySub:
- """Sub-object for implied_volatility on Greek indicators."""
- def __init__(self):
- self.current = type('Val', (), {'value': 0.25})()
- self.is_ready = True
- self._smoothing_func = None
- def set_smoothing_function(self, func):
- self._smoothing_func = func
- def SetSmoothingFunction(self, func):
- self._smoothing_func = func
- def update(self, *args, **kwargs):
- return True
-
-
-class _OptionGreekIndicator(IndicatorBase):
- """Indicator for option Greeks (IV, Delta, Gamma, Vega, Theta, Rho).
- Has an .implied_volatility sub-indicator with set_smoothing_function."""
- def __init__(self, name, period=14):
- super().__init__(name, period)
- self.implied_volatility = _ImpliedVolatilitySub()
- def _compute(self, value: float) -> float:
- return value if value else 0.25
-
-
-class _ContractList(list):
- """List subclass with .count property (like LEAN's C# List<T>)."""
- @property
- def count(self):
- return len(self)
- Count = count
-
-
-class OptionChainProvider:
- """Provides option chain data."""
- def __init__(self, algo=None):
- self._algo = algo
-
- def get_option_contract_list(self, symbol, date):
- """Get option contracts for a symbol. Must match option_chain() output exactly."""
- from .enums import OptionRight, OptionStyle
- underlying = symbol if isinstance(symbol, Symbol) else Symbol(str(symbol).upper())
- contracts = _ContractList()
- ticker_str = str(underlying).upper()
- und_sec_type = getattr(underlying, 'security_type', SecurityType.EQUITY)
-
- # Determine option properties based on underlying
- if und_sec_type == SecurityType.FUTURE:
- opt_sec_type = SecurityType.FUTURE_OPTION
- opt_market = getattr(underlying, 'market', Market.CME)
- elif und_sec_type == SecurityType.INDEX:
- opt_sec_type = SecurityType.INDEX_OPTION
- opt_market = Market.USA
- else:
- opt_sec_type = SecurityType.OPTION
- opt_market = Market.USA
-
- # Determine base price
- _default_prices = {
- 'SPX': 3800.0, 'SPXW': 3800.0, 'NDX': 13000.0, 'SPY': 380.0, 'QQQ': 310.0,
- 'ES': 3200.0, 'NQ': 13000.0, 'YM': 30000.0, 'RTY': 1800.0, 'MES': 3200.0,
- 'GOOG': 750.0, 'GOOGL': 750.0, 'AAPL': 150.0, 'MSFT': 300.0, 'AMZN': 3200.0,
- 'TSLA': 700.0, 'NVDA': 250.0, 'META': 250.0, 'NFLX': 500.0,
- 'GC': 1800.0, 'SI': 25.0, 'CL': 70.0, 'NG': 4.0,
- 'DC': 17.0, 'ZC': 400.0, 'ZW': 600.0, 'ZS': 1200.0,
- 'CLASS_III_MILK': 17.0, 'BUTTER': 2.0, 'CASH_SETTLED_CHEESE': 2.0,
- 'SP_500_E_MINI': 3200.0, 'E_MINI': 3200.0,
- }
- base_price = _default_prices.get(ticker_str, 100.0)
- # Try to get price from algo's securities
- if self._algo:
- sec = self._algo.securities.get(ticker_str)
- if sec and sec.price > 0:
- base_price = sec.price
-
- # Strike offsets - must match option_chain()
- if base_price > 1000:
- strike_offsets = [-800, -600, -450, -400, -200, -100, -50, 0, 50, 100, 200, 400, 450, 600, 800]
- elif base_price > 200:
- strike_offsets = [-100, -50, -20, -10, -5, 0, 5, 10, 20, 50, 100]
- else:
- strike_offsets = [-30, -20, -10, -5, -3, 0, 3, 5, 10, 20, 30]
-
- # Generate expiry dates - must match option_chain()
- def _third_friday(year, month):
- import calendar
- c = calendar.Calendar(firstweekday=calendar.MONDAY)
- fridays = [d for d in c.itermonthdays2(year, month)
- if d[0] != 0 and d[1] == calendar.FRIDAY]
- return datetime(year, month, fridays[2][0])
-
- # Use algo's time/start_date to ensure consistency with option_chain()
- if self._algo and (self._algo._time or self._algo._start_date):
- now = self._algo._time or self._algo._start_date
- elif isinstance(date, datetime):
- now = date.replace(tzinfo=None) if date.tzinfo else date
- else:
- now = datetime.now()
- und_expiry = getattr(underlying, 'expiry', None)
- expiry_dates = []
- if und_expiry:
- expiry_dates = [und_expiry]
- else:
- for m_offset in range(0, 4):
- y = now.year
- m = now.month + m_offset
- while m > 12:
- m -= 12
- y += 1
- try:
- exp = _third_friday(y, m)
- if exp >= now - timedelta(days=1):
- expiry_dates.append(exp)
- except Exception:
- pass
- near_exp = now + timedelta(days=7)
- if not any(abs((near_exp - e).days) < 5 for e in expiry_dates):
- expiry_dates.append(near_exp)
-
- for expiry in expiry_dates:
- for strike_offset in strike_offsets:
- strike = base_price + strike_offset
- if strike <= 0:
- continue
- for right in [OptionRight.CALL, OptionRight.PUT]:
- right_char = 'C' if right == OptionRight.CALL else 'P'
- ticker = f"{ticker_str}{expiry.strftime('%y%m%d')}{right_char}{int(strike)}"
- opt_sym = Symbol(ticker, opt_sec_type, opt_market)
- opt_sym.expiry = expiry
- opt_sym.strike_price = float(strike)
- opt_sym.right = right
- opt_sym._underlying = underlying
- opt_sym.id = type('SymbolId', (), {
- 'strike_price': float(strike), 'option_right': right,
- 'date': expiry, 'expiration': expiry, 'underlying': underlying
- })()
- contracts.append(opt_sym)
- return contracts
-
- GetOptionContractList = get_option_contract_list
-
-
-class Chart:
- """Chart container for plotting."""
- def __init__(self, name: str):
- self.name = name
- self.series = {}
-
- def add_series(self, series):
- self.series[series.name if hasattr(series, 'name') else str(series)] = series
-
-
-class Series:
- """Chart data series."""
- def __init__(self, name: str, series_type=0, unit="$"):
- self.name = name
- self.series_type = series_type
- self.unit = unit
- self.values = []
-
-
-class SeriesType:
- LINE = 0
- SCATTER = 1
- CANDLE = 2
- BAR = 3
- FLAG = 4
- STACKED_AREA = 5
- PIE = 6
- TREEMAP = 7
-
-
-class NotificationManager:
- """Notification stub."""
- def email(self, to, subject, body):
- pass
-
- def sms(self, phone, message):
- pass
-
- def web(self, url, data=None):
- pass
-
-
-# Framework model base classes
-
-class AlphaModel:
- """Base class for alpha models."""
- def update(self, algorithm, data):
- return []
-
- def on_securities_changed(self, algorithm, changes):
- pass
-
-
-class PortfolioConstructionModel:
- """Base class for portfolio construction."""
- def create_targets(self, algorithm, insights):
- return []
-
- def on_securities_changed(self, algorithm, changes):
- pass
-
-
-class ExecutionModel:
- """Base class for execution models."""
- def execute(self, algorithm, targets):
- pass
-
- def on_securities_changed(self, algorithm, changes):
- pass
-
-
-class RiskManagementModel:
- """Base class for risk management."""
- def manage_risk(self, algorithm, targets):
- return targets
-
- def on_securities_changed(self, algorithm, changes):
- pass
-
-
-class UniverseSelectionModel:
- """Base class for universe selection."""
- def create_universes(self, algorithm):
- return []
-
- def get_next_refresh_time_utc(self):
- return datetime.utcnow() + timedelta(days=1)
-
-
-class NullRiskManagementModel(RiskManagementModel):
- """No-op risk management."""
- pass
-
-
-class NullAlphaModel(AlphaModel):
- """No-op alpha model."""
- pass
-
-
-class ConstantAlphaModel(AlphaModel):
- """Alpha model that emits constant insights for all securities."""
-
- def __init__(self, insight_type=None, direction=None, period=None, magnitude=None,
- weight=None, confidence=None):
- self._type = insight_type or InsightType.PRICE
- self._direction = direction or InsightDirection.UP
- self._period = period or timedelta(days=1)
- self._magnitude = magnitude
- self._weight = weight
- self._confidence = confidence
- self._securities = []
-
- def update(self, algorithm, data):
- insights = []
- for security in self._securities:
- if data.contains_key(security.symbol):
- insights.append(Insight(
- security.symbol, self._period, self._type,
- self._direction, self._magnitude, weight=self._weight
- ))
- return insights
-
- def on_securities_changed(self, algorithm, changes):
- for sec in changes.added_securities:
- if sec not in self._securities:
- self._securities.append(sec)
- for sec in changes.removed_securities:
- if sec in self._securities:
- self._securities.remove(sec)
-
-
-class EqualWeightingPortfolioConstructionModel(PortfolioConstructionModel):
- """Portfolio construction model that assigns equal weight to all insights."""
-
- def __init__(self, rebalance=None, portfolio_bias=None, resolution=None, **kwargs):
- self._rebalance = rebalance
- self._portfolio_bias = portfolio_bias
- self._resolution = resolution
-
- def create_targets(self, algorithm, insights):
- if not insights:
- return []
- targets = []
- weight = 1.0 / len(insights) if insights else 0
- for insight in insights:
- direction = 1 if insight.direction == InsightDirection.UP else (
- -1 if insight.direction == InsightDirection.DOWN else 0)
- targets.append(PortfolioTarget(insight.symbol, weight * direction))
- return targets
-
-
-class InsightWeightingPortfolioConstructionModel(PortfolioConstructionModel):
- """Portfolio construction weighted by insight magnitude/confidence."""
-
- def __init__(self, rebalance=None, portfolio_bias=None):
- self._rebalance = rebalance
- self._portfolio_bias = portfolio_bias
-
- def create_targets(self, algorithm, insights):
- if not insights:
- return []
- total_weight = sum(abs(i.weight or i.confidence or 1.0) for i in insights)
- if total_weight == 0:
- total_weight = 1
- targets = []
- for insight in insights:
- w = abs(insight.weight or insight.confidence or 1.0) / total_weight
- direction = 1 if insight.direction == InsightDirection.UP else (
- -1 if insight.direction == InsightDirection.DOWN else 0)
- targets.append(PortfolioTarget(insight.symbol, w * direction))
- return targets
-
-
-class MeanVarianceOptimizationPortfolioConstructionModel(PortfolioConstructionModel):
- """Portfolio construction using mean-variance optimization (simplified stub)."""
-
- def __init__(self, rebalance=None, portfolio_bias=None, lookback=1,
- period=63, resolution=None, risk_free_rate=0.0, optimizer=None):
- self._rebalance = rebalance
- self._lookback = lookback
-
- def create_targets(self, algorithm, insights):
- if not insights:
- return []
- weight = 1.0 / len(insights)
- return [PortfolioTarget(i.symbol, weight * (1 if i.direction == InsightDirection.UP else -1))
- for i in insights]
-
-
-class BlackLittermanOptimizationPortfolioConstructionModel(PortfolioConstructionModel):
- """Black-Litterman portfolio construction (simplified stub)."""
-
- def __init__(self, rebalance=None, portfolio_bias=None, lookback=63,
- resolution=None, risk_free_rate=0.0, optimizer=None):
- self._rebalance = rebalance
- self._lookback = lookback
-
- def create_targets(self, algorithm, insights):
- if not insights:
- return []
- weight = 1.0 / len(insights)
- return [PortfolioTarget(i.symbol, weight * (1 if i.direction == InsightDirection.UP else -1))
- for i in insights]
-
-
-class ImmediateExecutionModel(ExecutionModel):
- """Execution model that immediately submits market orders."""
-
- def execute(self, algorithm, targets):
- for target in targets:
- existing = algorithm.portfolio[str(target.symbol)].quantity
- diff = target.quantity - existing
- if abs(diff) > 0:
- algorithm.market_order(target.symbol, diff)
-
-
-class VolumeWeightedAveragePriceExecutionModel(ExecutionModel):
- """VWAP execution model (simplified stub - acts like immediate)."""
-
- def execute(self, algorithm, targets):
- for target in targets:
- existing = algorithm.portfolio[str(target.symbol)].quantity
- diff = target.quantity - existing
- if abs(diff) > 0:
- algorithm.market_order(target.symbol, diff)
-
-
-class StandardDeviationExecutionModel(ExecutionModel):
- """Std dev execution model (simplified stub)."""
-
- def __init__(self, period=60, deviations=2, resolution=None):
- self._period = period
- self._deviations = deviations
-
- def execute(self, algorithm, targets):
- for target in targets:
- existing = algorithm.portfolio[str(target.symbol)].quantity
- diff = target.quantity - existing
- if abs(diff) > 0:
- algorithm.market_order(target.symbol, diff)
-
-
-class MaximumDrawdownPercentPortfolio(RiskManagementModel):
- """Risk model: maximum portfolio drawdown percentage."""
-
- def __init__(self, maximum_drawdown_percent=0.05, is_not_a_ccount_currency_for=False):
- self._max_dd = maximum_drawdown_percent
- self._trailing_high = 0
-
- def manage_risk(self, algorithm, targets):
- portfolio_value = algorithm.portfolio.total_portfolio_value
- self._trailing_high = max(self._trailing_high, portfolio_value)
- if self._trailing_high > 0:
- dd = (self._trailing_high - portfolio_value) / self._trailing_high
- if dd > self._max_dd:
- return [PortfolioTarget(str(s.symbol), 0) for s in algorithm.securities]
- return targets
-
-
-class MaximumDrawdownPercentPerSecurity(RiskManagementModel):
- """Risk model: maximum drawdown per security."""
-
- def __init__(self, maximum_drawdown_percent=0.05):
- self._max_dd = maximum_drawdown_percent
-
- def manage_risk(self, algorithm, targets):
- risk_targets = list(targets) if targets else []
- for ticker, holding in algorithm.portfolio.items():
- if holding.invested and holding.unrealized_profit_percent < -self._max_dd:
- risk_targets.append(PortfolioTarget(ticker, 0))
- return risk_targets
-
-
-class MaximumUnrealizedProfitPercentPerSecurity(RiskManagementModel):
- """Risk model: take profit at maximum unrealized profit."""
-
- def __init__(self, maximum_unrealized_profit_percent=0.05):
- self._max_profit = maximum_unrealized_profit_percent
-
- def manage_risk(self, algorithm, targets):
- risk_targets = list(targets) if targets else []
- for ticker, holding in algorithm.portfolio.items():
- if holding.invested and holding.unrealized_profit_percent > self._max_profit:
- risk_targets.append(PortfolioTarget(ticker, 0))
- return risk_targets
-
-
-class TrailingStopRiskManagementModel(RiskManagementModel):
- """Risk model: trailing stop for each security."""
-
- def __init__(self, maximum_drawdown_percent=0.05):
- self._max_dd = maximum_drawdown_percent
- self._trailing_highs = {}
-
- def manage_risk(self, algorithm, targets):
- risk_targets = list(targets) if targets else []
- for ticker, holding in algorithm.portfolio.items():
- if holding.invested:
- price = holding.market_price
- if ticker not in self._trailing_highs:
- self._trailing_highs[ticker] = price
- self._trailing_highs[ticker] = max(self._trailing_highs[ticker], price)
- trail = self._trailing_highs[ticker]
- if trail > 0 and (trail - price) / trail > self._max_dd:
- risk_targets.append(PortfolioTarget(ticker, 0))
- else:
- self._trailing_highs.pop(ticker, None)
- return risk_targets
-
-
-class MaximumSectorExposureRiskManagementModel(RiskManagementModel):
- """Risk model: maximum sector exposure (stub)."""
-
- def __init__(self, maximum_sector_exposure=0.3):
- self._max_exposure = maximum_sector_exposure
-
- def manage_risk(self, algorithm, targets):
- return targets
-
-
-class CompositeRiskManagementModel(RiskManagementModel):
- """Combines multiple risk management models."""
-
- def __init__(self, *models):
- self._models = list(models)
-
- def add_risk_management(self, model):
- self._models.append(model)
-
- def manage_risk(self, algorithm, targets):
- for model in self._models:
- targets = model.manage_risk(algorithm, targets)
- return targets
-
-
-class ManualUniverseSelectionModel(UniverseSelectionModel):
- """Universe selection from a manually specified list of symbols."""
-
- def __init__(self, symbols=None, *args):
- self._symbols = symbols or []
- if args:
- self._symbols = list(args) if not symbols else self._symbols
-
- def create_universes(self, algorithm):
- return self._symbols
-
-
-class FundamentalUniverseSelectionModel(UniverseSelectionModel):
- """Universe selection based on fundamental data."""
-
- def __init__(self, filter_fine_universe=True, universe_settings=None, *args, **kwargs):
- self._filter_fine = filter_fine_universe
-
- def create_universes(self, algorithm):
- return []
-
- def select_coarse(self, algorithm, coarse):
- return [c.symbol for c in coarse]
-
- def select_fine(self, algorithm, fine):
- return [f.symbol for f in fine]
-
-
-class ScheduledUniverseSelectionModel(UniverseSelectionModel):
- """Universe selection on a schedule."""
-
- def __init__(self, date_rule, time_rule, selector, settings=None):
- self._date_rule = date_rule
- self._time_rule = time_rule
- self._selector = selector
-
- def create_universes(self, algorithm):
- if callable(self._selector):
- return self._selector(algorithm.time)
- return []
-
-
-class CustomUniverseSelectionModel(UniverseSelectionModel):
- """Custom universe selection from a function."""
-
- def __init__(self, name, selector, settings=None):
- self._name = name
- self._selector = selector
-
- def create_universes(self, algorithm):
- if callable(self._selector):
- return self._selector(algorithm.time)
- return []
-
-
-class CompositeAlphaModel(AlphaModel):
- """Combines multiple alpha models."""
-
- def __init__(self, *models):
- self._models = list(models)
-
- def update(self, algorithm, data):
- all_insights = []
- for model in self._models:
- insights = model.update(algorithm, data)
- if insights:
- all_insights.extend(insights)
- return all_insights
-
- def on_securities_changed(self, algorithm, changes):
- for model in self._models:
- model.on_securities_changed(algorithm, changes)
-
-
-class PythonData:
- """Base class for custom Python data types."""
-
- def __init__(self):
- self.symbol = None
- self.time = None
- self.end_time = None
- self.value = 0.0
- self._data = {}
-
- def get_source(self, config, date, is_live_mode):
- return None
-
- def reader(self, config, line, date, is_live_mode):
- return None
-
- def __getattr__(self, name):
- if name.startswith('_'):
- raise AttributeError(name)
- return self._data.get(name, 0)
-
- def __setattr__(self, name, value):
- if name in ('symbol', 'time', 'end_time', 'value', '_data'):
- super().__setattr__(name, value)
- else:
- if not hasattr(self, '_data'):
- super().__setattr__('_data', {})
- self._data[name] = value
-
- def __getitem__(self, key):
- return self._data.get(key, 0)
-
- def __setitem__(self, key, value):
- self._data[key] = value
-
- def __repr__(self):
- return f"PythonData({self.symbol}, {self.value})"
-
-
-class PythonQuandl(PythonData):
- """Quandl data loader (stub)."""
-
- def __init__(self):
- super().__init__()
-
- def get_source(self, config, date, is_live_mode):
- return None
-
-
-class InsightCollection:
- """Collection of insights with filtering capabilities."""
-
- def __init__(self):
- self._insights = []
-
- def add(self, insight):
- self._insights.append(insight)
-
- def add_range(self, insights):
- self._insights.extend(insights)
-
- def clear(self):
- self._insights.clear()
-
- def get_active_insights(self, utc_time):
- return [i for i in self._insights if i.close_time_utc > utc_time]
-
- def has_active_insights(self, symbol, utc_time):
- return any(i for i in self._insights
- if str(i.symbol) == str(symbol) and i.close_time_utc > utc_time)
-
- def remove_expired_insights(self, utc_time):
- self._insights = [i for i in self._insights if i.close_time_utc > utc_time]
-
- def set_insight_score_function(self, func):
- """Set a custom scoring function for insights."""
- self._score_function = func
-
- def __iter__(self):
- return iter(self._insights)
-
- def __len__(self):
- return len(self._insights)
-
-
-class Field:
- """Universe selection field for sorting/filtering."""
-
- @staticmethod
- def dollar_volume(x):
- return getattr(x, 'dollar_volume', 0)
-
- @staticmethod
- def price(x):
- return getattr(x, 'price', 0)
-
- @staticmethod
- def volume(x):
- return getattr(x, 'volume', 0)
-
- CLOSE = staticmethod(lambda x: getattr(x, 'close', getattr(x, 'price', 0)))
- OPEN = staticmethod(lambda x: getattr(x, 'open', 0))
- HIGH = staticmethod(lambda x: getattr(x, 'high', 0))
- LOW = staticmethod(lambda x: getattr(x, 'low', 0))
- VOLUME = staticmethod(lambda x: getattr(x, 'volume', 0))
- AVERAGE = staticmethod(lambda x: getattr(x, 'close', getattr(x, 'price', 0)))
-
- # Lowercase aliases (used by many strategies)
- close = CLOSE
- open = OPEN
- high = HIGH
- low = LOW
- average = AVERAGE
-
- SEVEN_BAR = staticmethod(lambda x: getattr(x, 'close', getattr(x, 'price', 0)))
- BID_CLOSE = staticmethod(lambda x: getattr(x, 'bid_close', getattr(x, 'close', 0)))
- ASK_CLOSE = staticmethod(lambda x: getattr(x, 'ask_close', getattr(x, 'close', 0)))
- BID_OPEN = staticmethod(lambda x: getattr(x, 'bid_open', getattr(x, 'open', 0)))
- ASK_OPEN = staticmethod(lambda x: getattr(x, 'ask_open', getattr(x, 'open', 0)))
- BID_HIGH = staticmethod(lambda x: getattr(x, 'bid_high', getattr(x, 'high', 0)))
- ASK_HIGH = staticmethod(lambda x: getattr(x, 'ask_high', getattr(x, 'high', 0)))
- BID_LOW = staticmethod(lambda x: getattr(x, 'bid_low', getattr(x, 'low', 0)))
- ASK_LOW = staticmethod(lambda x: getattr(x, 'ask_low', getattr(x, 'low', 0)))
- SevenBar = SEVEN_BAR
- BidClose = BID_CLOSE
- AskClose = ASK_CLOSE
- BidOpen = BID_OPEN
- AskOpen = ASK_OPEN
- BidHigh = BID_HIGH
- AskHigh = ASK_HIGH
- BidLow = BID_LOW
- AskLow = ASK_LOW
-
- DollarVolume = staticmethod(lambda x: getattr(x, 'dollar_volume', 0))
- Price = staticmethod(lambda x: getattr(x, 'price', 0))
- Volume = staticmethod(lambda x: getattr(x, 'volume', 0))
- Close = CLOSE
- Open = OPEN
- High = HIGH
- Low = LOW
- Average = AVERAGE
-
-
-class Futures:
- """Futures contract specifications."""
-
- class Indices:
- SP_500_E_MINI = "ES"
- NASDAQ_100_E_MINI = "NQ"
- DOW_30_E_MINI = "YM"
- RUSSELL_2000_E_MINI = "RTY"
- VIX = "VX"
- SP500 = "ES"
- MICRO_SP_500_E_MINI = "MES"
- EURO_STOXX_50 = "FESX"
- NIKKEI_225 = "NK"
- FTSE_100 = "Z"
- DAX = "FDAX"
- HANG_SENG = "HSI"
- MSCI_EMERGING_MARKETS = "MXEF"
-
- class Metals:
- GOLD = "GC"
- SILVER = "SI"
- PLATINUM = "PL"
- PALLADIUM = "PA"
- COPPER = "HG"
- MICRO_GOLD = "MGC"
- MICRO_SILVER = "SIL"
-
- class Energies:
- CRUDE_OIL_WTI = "CL"
- NATURAL_GAS = "NG"
- HEATING_OIL = "HO"
- GASOLINE = "RB"
- BRENT_CRUDE = "BZ"
- MICRO_CRUDE_OIL_WTI = "MCL"
-
- class Grains:
- CORN = "ZC"
- WHEAT = "ZW"
- SOYBEANS = "ZS"
- SOYBEAN_MEAL = "ZM"
- SOYBEAN_OIL = "ZL"
- OATS = "ZO"
-
- class Currencies:
- EUR = "6E"
- GBP = "6B"
- JPY = "6J"
- AUD = "6A"
- CAD = "6C"
- CHF = "6S"
-
- class Financials:
- Y_2_TREASURY_NOTE = "ZT"
- Y_5_TREASURY_NOTE = "ZF"
- Y_10_TREASURY_NOTE = "ZN"
- Y_30_TREASURY_BOND = "ZB"
- EURODOLLAR = "GE"
-
- class Meats:
- LIVE_CATTLE = "LE"
- FEEDER_CATTLE = "GF"
- LEAN_HOGS = "HE"
-
- class Softs:
- SUGAR = "SB"
- COTTON = "CT"
- COFFEE = "KC"
- COCOA = "CC"
-
-
-class Globals:
- """Global settings."""
- DataFolder = ""
- Cache = ""
-
-
-class SecurityIdentifier:
- """Security identifier generator."""
-
- @staticmethod
- def generate_equity(ticker, market="usa", map_first_date=True):
- return Symbol(ticker, SecurityType.EQUITY, market)
-
- @staticmethod
- def generate_option(underlying, market="usa", option_style=0, option_right=0,
- strike_price=0, expiry_date=None):
- return Symbol(underlying, SecurityType.OPTION, market)
-
- @staticmethod
- def generate_future(ticker, market="cme", expiry_date=None):
- return Symbol(ticker, SecurityType.FUTURE, market)
-
-
-class PortfolioBias:
- """Portfolio bias setting."""
- LONG = 0
- SHORT = 1
- LONG_SHORT = 2
-
- Long = 0
- Short = 1
- LongShort = 2
-
-
-class Resolution_:
- """Namespace aliases for Resolution to support both Resolution.Daily and Resolution.DAILY"""
- pass
diff --git a/fincept-qt/scripts/strategies/fincept_engine/algorithm_imports.py b/fincept-qt/scripts/strategies/fincept_engine/algorithm_imports.py
deleted file mode 100644
index 9c601a071..000000000
--- a/fincept-qt/scripts/strategies/fincept_engine/algorithm_imports.py
+++ /dev/null
@@ -1,1714 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Algorithm Imports Compatibility Layer
-# Drop-in replacement for QuantConnect's AlgorithmImports.py
-# Routes all imports to fincept_engine modules (pure Python, no .NET)
-# ============================================================================
-
-# --- Pre-register module intercepts to prevent pythonnet/QuantConnect crashes ---
-import sys as _sys_boot
-import types as _types_boot
-
-# Block QuantConnect .NET imports - redirect to our stubs
-def _register_stub_module(name, attrs=None):
- """Register a stub module in sys.modules to prevent .NET import crashes."""
- if name not in _sys_boot.modules or _should_override(name):
- mod = _types_boot.ModuleType(name)
- if attrs:
- for k, v in attrs.items():
- setattr(mod, k, v)
- # Make sub-attribute access return stubs
- mod.__path__ = [] # Mark as package so submodule imports work
- _sys_boot.modules[name] = mod
- return _sys_boot.modules[name]
-
-def _should_override(name):
- """Check if existing module is broken (pythonnet) and should be overridden."""
- try:
- mod = _sys_boot.modules.get(name)
- if mod and hasattr(mod, '__file__') and mod.__file__ and 'pythonnet' in str(mod.__file__):
- return True
- if mod and hasattr(mod, '__loader__') and 'clr' in str(type(mod.__loader__)):
- return True
- except Exception:
- return True
- return False
-
-# Pre-register QuantConnect stubs (prevents pythonnet .NET assembly load crashes)
-for _qc_sub in ['QuantConnect', 'QuantConnect.Algorithm', 'QuantConnect.Algorithm.Framework',
- 'QuantConnect.Algorithm.Framework.Alphas', 'QuantConnect.Algorithm.Framework.Portfolio',
- 'QuantConnect.Algorithm.Framework.Execution', 'QuantConnect.Algorithm.Framework.Risk',
- 'QuantConnect.Algorithm.Framework.Selection',
- 'QuantConnect.Data', 'QuantConnect.Data.Custom', 'QuantConnect.Data.Custom.Tiingo',
- 'QuantConnect.Data.Custom.Intrinio',
- 'QuantConnect.Data.Market', 'QuantConnect.Data.UniverseSelection',
- 'QuantConnect.Data.Fundamental',
- 'QuantConnect.Orders', 'QuantConnect.Orders.Fees', 'QuantConnect.Orders.Fills',
- 'QuantConnect.Orders.Slippage', 'QuantConnect.Orders.OptionExercise',
- 'QuantConnect.Securities', 'QuantConnect.Securities.Option',
- 'QuantConnect.Securities.Option.StrategyMatcher',
- 'QuantConnect.Securities.Future',
- 'QuantConnect.Securities.Equity',
- 'QuantConnect.Securities.Positions',
- 'QuantConnect.Indicators',
- 'QuantConnect.Brokerages',
- 'QuantConnect.Python',
- 'QuantConnect.Util',
- 'QuantConnect.Data.Custom.IconicTypes',
- 'QuantConnect.Data.Custom.Tiingo',
- 'QuantConnect.Data.Auxiliary',
- 'QuantConnect.Algorithm.CSharp',
- 'QuantConnect.Lean.Engine.DataFeeds',
- 'QuantConnect.Logging']:
- _register_stub_module(_qc_sub)
-
-# Populate specific QC modules with needed attributes
-_qc_orders = _sys_boot.modules.get('QuantConnect.Orders')
-if _qc_orders:
- _qc_orders.OrderEvent = type('OrderEvent', (), {
- '__init__': lambda self, *a, **kw: None
- })
-
-# OptionExercise stubs
-_qc_opt_exercise = _sys_boot.modules.get('QuantConnect.Orders.OptionExercise')
-if _qc_opt_exercise:
- _qc_opt_exercise.OptionExerciseOrder = type('OptionExerciseOrder', (), {
- '__init__': lambda self, *a, **kw: [
- setattr(self, 'symbol', kw.get('symbol')),
- setattr(self, 'quantity', kw.get('quantity', 0)),
- setattr(self, 'tag', kw.get('tag', '')),
- setattr(self, 'type', 0),
- setattr(self, 'status', 0),
- setattr(self, 'direction', 0),
- ],
- })
-
-_qc_sec_pos = _sys_boot.modules.get('QuantConnect.Securities.Positions')
-if _qc_sec_pos:
- _qc_sec_pos.IPositionGroup = type('IPositionGroup', (), {})
-
-# Tiingo data type
-_qc_tiingo = _sys_boot.modules.get('QuantConnect.Data.Custom.Tiingo')
-if _qc_tiingo:
- class _TiingoPrice:
- def __init__(self):
- self.symbol = None; self.time = None; self.close = 0; self.value = 0
- self.high = 0; self.low = 0; self.open = 0; self.volume = 0
- _TiingoPrice.set_auth_code = staticmethod(lambda code: None)
- _TiingoPrice.SetAuthCode = staticmethod(lambda code: None)
- _qc_tiingo.TiingoPrice = _TiingoPrice
- _qc_tiingo.TiingoDailyData = _TiingoPrice
- _qc_tiingo.Tiingo = _TiingoPrice
- _qc_tiingo.TiingoNews = type('TiingoNews', (), {
- '__init__': lambda self: None
- })
-
-# IconicTypes data stubs
-_qc_iconic = _sys_boot.modules.get('QuantConnect.Data.Custom.IconicTypes')
-if _qc_iconic:
- class _LinkedData:
- requires_mapping_to_underlying = True # Linked types need symbol cache lookup
- def __init__(self):
- self.symbol = None; self.time = None; self.value = 0
- self.count = 0; self.linked_symbol = None
- _qc_iconic.LinkedData = _LinkedData
- class _UnlinkedData:
- requires_mapping_to_underlying = False # Unlinked types don't need cache lookup
- def __init__(self):
- self.symbol = None; self.time = None; self.value = 0
- _qc_iconic.UnlinkedData = _UnlinkedData
- _qc_iconic.UnlinkedDataTradeBar = type('UnlinkedDataTradeBar', (), {
- '__init__': lambda self: None
- })
-
-# Auxiliary data stubs
-_qc_aux = _sys_boot.modules.get('QuantConnect.Data.Auxiliary')
-if _qc_aux:
- _qc_aux.MapFileResolver = type('MapFileResolver', (), {'Empty': None})
-
-# Algorithm.CSharp stubs
-_qc_csharp = _sys_boot.modules.get('QuantConnect.Algorithm.CSharp')
-if _qc_csharp:
- _qc_csharp.CustomPartialFillModel = type('CustomPartialFillModel', (), {
- '__init__': lambda self, *a, **kw: None
- })
- _qc_csharp.TestOptionAssignmentModel = type('TestOptionAssignmentModel', (), {
- '__init__': lambda self, *a, **kw: None
- })
- _qc_csharp.TestOptionExerciseModel = type('TestOptionExerciseModel', (), {
- '__init__': lambda self, *a, **kw: None
- })
- # OptionAssignmentRegressionAlgorithm stub base class
- _qc_csharp.OptionAssignmentRegressionAlgorithm = type('OptionAssignmentRegressionAlgorithm', (), {
- '__init__': lambda self, *a, **kw: None
- })
-
-# DataFeeds stubs
-_qc_df = _sys_boot.modules.get('QuantConnect.Lean.Engine.DataFeeds')
-if _qc_df:
- _qc_df.DefaultDataProvider = type('DefaultDataProvider', (), {
- '__init__': lambda self, *a, **kw: None
- })
-
-# Logging stubs
-_qc_log = _sys_boot.modules.get('QuantConnect.Logging')
-if _qc_log:
- _qc_log.Log = type('Log', (), {
- 'trace': staticmethod(lambda msg: None),
- 'debug': staticmethod(lambda msg: None),
- 'error': staticmethod(lambda msg: None),
- 'Trace': staticmethod(lambda msg: None),
- 'Debug': staticmethod(lambda msg: None),
- 'Error': staticmethod(lambda msg: None),
- })
-
-# Pre-register System stubs with common types
-_sys_mod = _register_stub_module('System', {
- 'Action': type('Action', (), {'__init__': lambda self, *a: None, '__getitem__': classmethod(lambda cls, *a: cls)}),
- 'Func': type('Func', (), {'__init__': lambda self, *a: None, '__getitem__': classmethod(lambda cls, *a: cls)}),
- 'Nullable': type('Nullable', (), {'__getitem__': classmethod(lambda cls, *a: cls)}),
- 'TimeSpan': type('TimeSpan', (), {}),
- 'DateTime': type('DateTime', (), {}),
- 'String': str,
- 'Int32': int,
- 'Double': float,
- 'Boolean': bool,
- 'Decimal': float,
- 'Object': object,
-})
-# Make Action subscriptable: System.Action[Type1, Type2]
-class _SubscriptableType:
- def __init__(self, name='Type'):
- self.__name__ = name
- def __getitem__(self, item):
- return self
- def __call__(self, *args, **kwargs):
- return None
- def __instancecheck__(cls, instance):
- return True
-_sys_mod.Action = _SubscriptableType('Action')
-_sys_mod.Func = _SubscriptableType('Func')
-_sys_mod.Nullable = _SubscriptableType('Nullable')
-
-_register_stub_module('System.Collections', {})
-class _CSharpList(list):
- """C# List<T> compatible list with .add() method."""
- def add(self, item): self.append(item)
- def Add(self, item): self.append(item)
- def remove(self, item): super().remove(item)
- def Remove(self, item): super().remove(item)
- @property
- def count(self): return len(self)
- Count = count
-_register_stub_module('System.Collections.Generic', {
- 'List': _CSharpList,
- 'Dictionary': dict,
- 'IEnumerable': list,
- 'HashSet': set,
-})
-_register_stub_module('System.Drawing', {'Color': type('Color', (), {
- 'Red': 'red', 'Green': 'green', 'Blue': 'blue', 'White': 'white',
- 'Black': 'black', 'Yellow': 'yellow', 'Orange': 'orange',
-})})
-_register_stub_module('System.IO', {})
-_register_stub_module('System.Globalization', {'CultureInfo': type('CultureInfo', (), {
- 'InvariantCulture': None
-})})
-
-# Pre-register clr stub (prevents pythonnet crash)
-_register_stub_module('clr', {'AddReference': lambda *a: None})
-
-# Pre-register Newtonsoft stub
-_register_stub_module('Newtonsoft', {})
-_jc = type('JsonConvert', (), {
- 'SerializeObject': staticmethod(lambda obj, *a, **kw: '{}'),
- 'DeserializeObject': staticmethod(lambda s, *a, **kw: {}),
- 'serialize_object': staticmethod(lambda obj, *a, **kw: '{}'),
- 'deserialize_object': staticmethod(lambda s, *a, **kw: {}),
-})
-_register_stub_module('Newtonsoft.Json', {'JsonConvert': _jc})
-
-# Pre-register keras/tensorflow stubs if not available
-if 'keras' not in _sys_boot.modules:
- try:
- import keras as _keras_test
- except ImportError:
- _keras_mod = _register_stub_module('keras')
- _keras_models = _register_stub_module('keras.models', {
- 'Sequential': type('Sequential', (), {
- '__init__': lambda self, *a, **kw: setattr(self, '_layers', []),
- 'add': lambda self, *a, **kw: self._layers.append(a[0]) if hasattr(self, '_layers') else None,
- 'compile': lambda self, *a, **kw: None,
- 'fit': lambda self, *a, **kw: type('History', (), {'history': {'loss': [0.1]}})(),
- 'predict': lambda self, *a, **kw: [[0.0]],
- 'save': lambda self, *a, **kw: None,
- 'load_model': staticmethod(lambda *a, **kw: None),
- 'train_on_batch': lambda self, *a, **kw: 0.1,
- 'get_weights': lambda self: [[0.0]],
- 'set_weights': lambda self, *a, **kw: None,
- '__getitem__': lambda self, idx: type('Layer', (), {
- 'output': None, 'input': None, 'name': f'layer_{idx}',
- 'get_weights': lambda self: [[0.0]],
- })(),
- '__len__': lambda self: len(getattr(self, '_layers', [])),
- })
- })
- _keras_layers = _register_stub_module('keras.layers', {
- 'Dense': type('Dense', (), {'__init__': lambda self, *a, **kw: None}),
- 'Activation': type('Activation', (), {'__init__': lambda self, *a, **kw: None}),
- 'LSTM': type('LSTM', (), {'__init__': lambda self, *a, **kw: None}),
- 'Dropout': type('Dropout', (), {'__init__': lambda self, *a, **kw: None}),
- })
- _keras_optimizers = _register_stub_module('keras.optimizers', {
- 'SGD': type('SGD', (), {'__init__': lambda self, *a, **kw: None}),
- 'Adam': type('Adam', (), {'__init__': lambda self, *a, **kw: None}),
- })
- _keras_mod.models = _keras_models
- _keras_mod.layers = _keras_layers
- _keras_mod.optimizers = _keras_optimizers
-
-if 'tensorflow' not in _sys_boot.modules:
- try:
- import tensorflow as _tf_test
- except ImportError:
- _tf_mod = _register_stub_module('tensorflow')
- _tf_mod.keras = _sys_boot.modules.get('keras', _types_boot.ModuleType('keras'))
- _register_stub_module('tensorflow.keras', _tf_mod.keras.__dict__ if hasattr(_tf_mod.keras, '__dict__') else {})
- # tensorflow.compat.v1 stub
- _tf_compat = _register_stub_module('tensorflow.compat')
- _tf_v1 = _register_stub_module('tensorflow.compat.v1', {
- 'Session': type('Session', (), {
- '__init__': lambda self, *a, **kw: None,
- 'run': lambda self, *a, **kw: [],
- '__enter__': lambda self: self,
- '__exit__': lambda self, *a: None,
- }),
- 'placeholder': lambda *a, **kw: None,
- 'Variable': lambda *a, **kw: None,
- 'global_variables_initializer': lambda: None,
- 'train': type('train', (), {
- 'GradientDescentOptimizer': type('GradientDescentOptimizer', (), {
- '__init__': lambda self, *a, **kw: None,
- 'minimize': lambda self, *a, **kw: None,
- }),
- })(),
- 'reduce_mean': lambda *a, **kw: None,
- 'square': lambda *a, **kw: None,
- 'matmul': lambda *a, **kw: None,
- 'add': lambda *a, **kw: None,
- 'nn': type('nn', (), {
- 'relu': lambda *a, **kw: None,
- 'sigmoid': lambda *a, **kw: None,
- })(),
- 'float32': 'float32',
- 'disable_v2_behavior': lambda: None,
- })
- _tf_compat.v1 = _tf_v1
- _tf_mod.compat = _tf_compat
-
-del _sys_boot, _types_boot, _register_stub_module, _should_override
-
-# --- Core Algorithm ---
-from .algorithm import (
- QCAlgorithm, AlphaModel, PortfolioConstructionModel,
- ExecutionModel, RiskManagementModel, UniverseSelectionModel,
- NullRiskManagementModel, NullAlphaModel,
- Chart, Series, SeriesType, OptionChainProvider, SecurityChanges,
- Transactions, ObjectStore, NotificationManager, SubscriptionManager
-)
-
-# --- Framework Models: Alpha ---
-from .algorithm import ConstantAlphaModel, CompositeAlphaModel
-
-# --- Framework Models: Portfolio Construction ---
-from .algorithm import (
- EqualWeightingPortfolioConstructionModel,
- InsightWeightingPortfolioConstructionModel,
- MeanVarianceOptimizationPortfolioConstructionModel,
- BlackLittermanOptimizationPortfolioConstructionModel
-)
-
-# --- Framework Models: Execution ---
-from .algorithm import (
- ImmediateExecutionModel,
- VolumeWeightedAveragePriceExecutionModel,
- StandardDeviationExecutionModel
-)
-
-# --- Framework Models: Risk Management ---
-from .algorithm import (
- MaximumDrawdownPercentPortfolio,
- MaximumDrawdownPercentPerSecurity,
- MaximumUnrealizedProfitPercentPerSecurity,
- TrailingStopRiskManagementModel,
- MaximumSectorExposureRiskManagementModel,
- CompositeRiskManagementModel
-)
-
-# --- Framework Models: Universe Selection ---
-from .algorithm import (
- ManualUniverseSelectionModel,
- FundamentalUniverseSelectionModel,
- ScheduledUniverseSelectionModel,
- CustomUniverseSelectionModel
-)
-
-# --- Data Types ---
-from .algorithm import (
- PythonData, PythonQuandl, InsightCollection,
- Field, Futures, Globals, SecurityIdentifier, PortfolioBias
-)
-
-# --- Enums ---
-from .enums import (
- Resolution, SecurityType, OrderType, OrderStatus,
- Market, InsightDirection, InsightType, OrderDirection,
- TimeInForce, DataNormalizationMode, MovingAverageType,
- OptionRight, OptionStyle, BrokerageName, AccountType,
- PositionSide, SettlementType
-)
-
-# --- Core Types ---
-from .types import (
- Symbol, Slice, TradeBar, QuoteBar, Tick,
- SecurityHolding, OrderTicket, OrderEvent, UpdateOrderFields,
- Insight, InsightScore, PortfolioTarget, IndicatorValue
-)
-
-# --- Indicators ---
-from .indicators import (
- IndicatorBase, IndicatorDataPoint,
- ExponentialMovingAverage, SimpleMovingAverage,
- MovingAverageConvergenceDivergence, RelativeStrengthIndex,
- BollingerBands, AverageTrueRange, Stochastic,
- RateOfChange, Momentum, WilliamsPercentR,
- CommodityChannelIndex, AverageDirectionalIndex
-)
-
-# --- Portfolio ---
-from .portfolio import SecurityPortfolioManager
-
-# --- Securities ---
-from .securities import SecurityManager, Security, Exchange, ExchangeHours
-
-# --- Scheduling ---
-from .scheduling import (
- ScheduleManager, DateRules, TimeRules,
- ScheduledEvent, DateRule, TimeRule
-)
-
-# --- Consolidators ---
-from .consolidators import (
- TradeBarConsolidator, QuoteBarConsolidator,
- RenkoConsolidator, RangeConsolidator, TickConsolidator,
- EventHandler
-)
-
-# --- Universe ---
-from .universe import (
- UniverseSettings, Universe, CoarseFundamental, FineFundamental,
- ValuationRatios, OperationRatios, AssetClassification,
- CompanyReference, SecurityReference
-)
-
-# --- Extensions ---
-from .extensions import (
- Time, TimeZones, Extensions, IndicatorExtensions,
- BuyingPowerModelExtensions, DefaultBrokerageModel, RateOfChangePercent
-)
-
-# --- Framework Models: Alpha (from framework/alphas.py) ---
-from .framework.alphas import (
- RsiAlphaModel, HistoricalReturnsAlphaModel, EmaCrossAlphaModel,
- MacdAlphaModel, PairsTradingAlphaModel, BasePairsTradingAlphaModel,
- PearsonCorrelationPairsTradingAlphaModel
-)
-
-# --- Framework Models: Portfolio (from framework/portfolio_construction.py) ---
-from .framework.portfolio_construction import UnconstrainedMeanVariancePortfolioOptimizer
-
-# --- Framework Models: Execution (from framework/execution.py) ---
-from .framework.execution import SpreadExecutionModel
-
-# --- Framework Models: Selection (from framework/selection.py) ---
-from .framework.selection import (
- OptionUniverseSelectionModel, FutureUniverseSelectionModel,
- ETFConstituentsUniverseSelectionModel, QC500UniverseSelectionModel
-)
-
-# --- Standard Library (matching LEAN's AlgorithmImports) ---
-from datetime import date, time, datetime, timedelta
-from typing import *
-import math
-import json
-import random as _random_mod
-
-try:
- import numpy as np
-except ImportError:
- np = None
-
-try:
- import pandas as pd
-except ImportError:
- pd = None
-
-try:
- import matplotlib
- matplotlib.use('Agg')
- import matplotlib.pyplot as plt
-except ImportError:
- plt = None
-
-
-# ============================================================================
-# LEAN Compatibility Aliases & Stub Types
-# These provide drop-in compatibility for QuantConnect/LEAN strategy code
-# ============================================================================
-
-# --- Algorithm aliases ---
-QCAlgorithmFramework = QCAlgorithm
-QCAlgorithmFrameworkBridge = QCAlgorithm
-IAlgorithm = QCAlgorithm
-
-# Fix up QC stub modules that need to reference QCAlgorithm (which wasn't available during early stub setup)
-import sys as _sys_fixup
-_qc_csharp_fix = _sys_fixup.modules.get('QuantConnect.Algorithm.CSharp')
-if _qc_csharp_fix:
- _qc_csharp_fix.OptionAssignmentRegressionAlgorithm = type('OptionAssignmentRegressionAlgorithm', (QCAlgorithm,), {
- '__init__': lambda self, *a, **kw: QCAlgorithm.__init__(self),
- })
-del _sys_fixup
-
-# --- TimeSpan (C# System.TimeSpan) ---
-class TimeSpan(timedelta):
- """timedelta subclass with LEAN-compatible static factory methods."""
-
- @staticmethod
- def from_days(days):
- return timedelta(days=days)
-
- @staticmethod
- def from_hours(hours):
- return timedelta(hours=hours)
-
- @staticmethod
- def from_minutes(minutes):
- return timedelta(minutes=minutes)
-
- @staticmethod
- def from_seconds(seconds):
- return timedelta(seconds=seconds)
-
- @staticmethod
- def from_milliseconds(ms):
- return timedelta(milliseconds=ms)
-
- FromDays = from_days
- FromHours = from_hours
- FromMinutes = from_minutes
- FromSeconds = from_seconds
- FromMilliseconds = from_milliseconds
-
-# --- DateTime alias ---
-DateTime = datetime
-
-# --- DayOfWeek ---
-class DayOfWeek:
- MONDAY = 0; TUESDAY = 1; WEDNESDAY = 2; THURSDAY = 3
- FRIDAY = 4; SATURDAY = 5; SUNDAY = 6
- Monday = 0; Tuesday = 1; Wednesday = 2; Thursday = 3
- Friday = 4; Saturday = 5; Sunday = 6
-
-# --- TickType ---
-class TickType:
- TRADE = 0; QUOTE = 1; OPEN_INTEREST = 2
- Trade = 0; Quote = 1; OpenInterest = 2
-
-# --- OptionPricingModelType ---
-class OptionPricingModelType:
- BLACK_SCHOLES = 0; BINOMIAL = 1; FORWARD_TREE = 2
- BINOMIAL_COX_ROSS_RUBINSTEIN = 1; CRANK_NICOLSON_FD = 3
- BlackScholes = 0; Binomial = 1; ForwardTree = 2
- BinomialCoxRossRubinstein = 1; CrankNicolsonFD = 3
-
-# --- OptionPriceModels ---
-class OptionPriceModels:
- @staticmethod
- def crank_nicolson_fd(): return None
- @staticmethod
- def black_scholes(): return None
- @staticmethod
- def additive_equiprobabilities(): return None
- @staticmethod
- def binomial_cox_ross_rubinstein(): return None
- @staticmethod
- def binomial_jarrow_rudd(): return None
- @staticmethod
- def barone_adesi_whaley(): return None
- CrankNicolsonFD = crank_nicolson_fd
- BlackScholes = black_scholes
- BaroneAdesiWhaley = barone_adesi_whaley
-
-# --- OptionFilterUniverse ---
-class OptionFilterUniverse:
- def __init__(self):
- self._strikes_down = 0
- self._strikes_up = 0
- def strikes(self, down, up): self._strikes_down = down; self._strikes_up = up; return self
- def expiration(self, min_days, max_days): return self
- def include_weeklys(self): return self
- def calls_only(self): return self
- def puts_only(self): return self
-
-# --- Fill & Execution Models ---
-class FillModel:
- def market_fill(self, security, order): return None
- def limit_fill(self, security, order): return None
- def stop_market_fill(self, security, order): return None
-
-class ImmediateFillModel(FillModel):
- pass
-
-# --- PythonIndicator ---
-class PythonIndicator:
- """Base class for custom Python indicators."""
- def __init__(self):
- self.name = self.__class__.__name__
- self.value = 0.0
- self.is_ready = False
- self.warm_up_period = 0
- self.current = type('obj', (object,), {'value': 0.0})()
- self.updated = EventHandler()
- self.samples = 0
- self.window = type('obj', (object,), {'count': 0, 'is_ready': False})()
- def __getattr__(self, name):
- # Ensure updated always exists even if subclass skips super().__init__
- if name == 'updated':
- self.updated = EventHandler()
- return self.updated
- if name == 'samples':
- self.samples = 0
- return 0
- if name == 'window':
- self.window = type('obj', (object,), {'count': 0, 'is_ready': False})()
- return self.window
- if name == 'current':
- self.current = type('obj', (object,), {'value': 0.0})()
- return self.current
- raise AttributeError(f"'{type(self).__name__}' object has no attribute '{name}'")
- def update(self, input_data): self.samples += 1; return False
- def __float__(self): return self.value
-
-# --- Order ---
-class Order:
- def __init__(self):
- self.id = 0; self.symbol = None; self.type = OrderType.MARKET
- self.status = OrderStatus.NEW; self.quantity = 0; self.price = 0
- self.tag = ""; self.direction = OrderDirection.BUY
-
-# --- MarketOnCloseOrder / MarketOnOpenOrder ---
-class MarketOnCloseOrder:
- def __init__(self, symbol=None, quantity=0, tag=""):
- self.symbol = symbol; self.quantity = quantity; self.tag = tag
-
-class MarketOnOpenOrder:
- def __init__(self, symbol=None, quantity=0, tag=""):
- self.symbol = symbol; self.quantity = quantity; self.tag = tag
-
-# --- Brokerage ---
-class BrokerageModelSecurityInitializer:
- def __init__(self, brokerage_model=None, security_seeder=None):
- self._model = brokerage_model; self._seeder = security_seeder
- def initialize(self, security): pass
-
-class SecuritySeeder:
- @staticmethod
- def null(): return SecuritySeeder()
- def seed_security(self, security): pass
-
-SecuritySeeder.NULL = SecuritySeeder()
-SecuritySeeder.Null = SecuritySeeder.NULL
-
-class FuncSecuritySeeder:
- def __init__(self, func=None): self._func = func
-
-class DefaultBrokerageMessageHandler:
- def __init__(self, *args, **kwargs): pass
-
-class BrokerageMessageEvent:
- def __init__(self, type_=0, code=0, message=""):
- self.type = type_; self.code = code; self.message = message
-
-class BrokerageMessageType:
- INFORMATION = 0; WARNING = 1; ERROR = 2; DISCONNECT = 3; RECONNECT = 4
- Information = 0; Warning = 1; Error = 2; Disconnect = 3; Reconnect = 4
-
-# --- Fee Models ---
-class FeeModel:
- def get_order_fee(self, parameters): return OrderFee(0)
-
-class ConstantFeeModel(FeeModel):
- def __init__(self, fee=0): self._fee = fee
- def get_order_fee(self, parameters): return OrderFee(self._fee)
-
-class OrderFee:
- def __init__(self, value=0, currency="USD"):
- self.value = CashAmount(value, currency)
- @staticmethod
- def zero(currency="USD"): return OrderFee(0, currency)
-
-class CashAmount:
- def __init__(self, amount=0, currency="USD"):
- self.amount = amount; self.currency = currency
- Zero = None
-CashAmount.Zero = CashAmount(0, "USD")
-OrderFee.ZERO = OrderFee(0)
-OrderFee.Zero = OrderFee.ZERO
-
-# --- Slippage Models ---
-class SlippageModel:
- def get_slippage_approximation(self, asset, order): return 0.0
-
-class ConstantSlippageModel(SlippageModel):
- def __init__(self, slippage=0): self._slippage = slippage
- def get_slippage_approximation(self, asset, order): return self._slippage
-
-# --- Volatility Model ---
-class VolatilityModel:
- def __init__(self): self.volatility = 0.0
- @staticmethod
- def null(): return VolatilityModel()
-
-# --- Buying Power / Margin ---
-class BuyingPowerModel:
- def get_maximum_order_quantity_for_target_buying_power(self, *args):
- return type('obj', (object,), {'quantity': 0, 'is_successful': True})()
- def get_buying_power(self, *args):
- return type('obj', (object,), {'value': 0})()
-
-class SecurityMarginModel(BuyingPowerModel):
- def __init__(self, leverage=1.0): self.leverage = leverage
-
-# --- Settlement Models ---
-class ImmediateSettlementModel:
- pass
-
-class DelayedSettlementModel:
- def __init__(self, days=0, hours=0):
- self._days = days; self._hours = hours
-
-# --- Update / Request Types ---
-class UpdateOrderRequest:
- def __init__(self, *args, **kwargs):
- self.order_id = 0; self.limit_price = None; self.stop_price = None
- self.quantity = None; self.tag = None
-
-# --- Currencies ---
-class Currencies:
- USD = "USD"; EUR = "EUR"; GBP = "GBP"; JPY = "JPY"
- AUD = "AUD"; CAD = "CAD"; CHF = "CHF"; NullCurrency = ""
-
-# --- Portfolio Construction Extras ---
-class AccumulativeInsightPortfolioConstructionModel(PortfolioConstructionModel):
- def __init__(self, *args, **kwargs): pass
- def create_targets(self, algorithm, insights): return []
-
-class ConfidenceWeightedPortfolioConstructionModel(PortfolioConstructionModel):
- def __init__(self, *args, **kwargs): pass
- def create_targets(self, algorithm, insights):
- if not insights: return []
- total = sum(abs(i.confidence or 1) for i in insights)
- if total == 0: total = 1
- return [PortfolioTarget(i.symbol, (i.confidence or 1)/total * (1 if i.direction == InsightDirection.UP else -1))
- for i in insights]
-
-class SectorWeightingPortfolioConstructionModel(PortfolioConstructionModel):
- def __init__(self, *args, **kwargs): pass
-
-# --- Security Data Filter ---
-class SecurityDataFilter:
- def filter(self, vehicle, data): return True
-
-# --- IPortfolioTarget alias ---
-IPortfolioTarget = PortfolioTarget
-
-# --- PortfolioTargetCollection ---
-class PortfolioTargetCollection(dict):
- """Collection of portfolio targets, keyed by symbol."""
- def __init__(self, *args, **kwargs):
- super().__init__()
- self._targets = {}
- def add(self, target):
- self._targets[str(target.symbol)] = target
- self[str(target.symbol)] = target
- def add_range(self, targets):
- for t in targets:
- self.add(t)
- def clear_fulfilled(self, algorithm):
- fulfilled = [sym for sym, t in self._targets.items()
- if not hasattr(algorithm, 'portfolio') or
- algorithm.portfolio.get(sym, type('H', (), {'quantity': t.quantity})()).quantity == t.quantity]
- for sym in fulfilled:
- self._targets.pop(sym, None)
- self.pop(sym, None)
- def order_by_margin_impact(self, algorithm):
- return sorted(self._targets.values(), key=lambda t: abs(t.quantity), reverse=True)
- def contains(self, symbol):
- return str(symbol) in self._targets
- def is_empty(self):
- return len(self._targets) == 0
- @property
- def count(self):
- return len(self._targets)
- def __iter__(self):
- return iter(self._targets.values())
- def __len__(self):
- return len(self._targets)
- ClearFulfilled = clear_fulfilled
- OrderByMarginImpact = order_by_margin_impact
- Contains = contains
- IsEmpty = is_empty
-
-# --- Provider stubs ---
-class LocalDiskShortableProvider:
- def __init__(self, *args, **kwargs): pass
-
-class ContractMultiplierProvider:
- pass
-
-# --- Consolidator Extras ---
-class ClassicRangeConsolidator:
- def __init__(self, range_size, data_type=None):
- self._range_size = range_size
- self.data_consolidated = EventHandler()
-
-ClassicRenkoConsolidator = RenkoConsolidator
-
-# --- Delistings / Dividends / Splits ---
-class Delistings:
- def __init__(self): self._data = {}
- def __contains__(self, key): return str(key) in self._data
- def __getitem__(self, key): return self._data.get(str(key))
- def contains_key(self, key): return str(key) in self._data
-
-class DelistingType:
- WARNING = 0; DELISTED = 1; Warning = 0; Delisted = 1
-
-class Dividends(dict):
- pass
-
-class Splits(dict):
- pass
-
-class SymbolChangedEvents(dict):
- pass
-
-# --- Singular data event types (for history() requests) ---
-class Split:
- def __init__(self):
- self.symbol = None; self.time = None; self.split_factor = 1.0
- self.reference_price = 0.0; self.type = 0; self.value = 0.0
-
-class MarginInterestRate:
- def __init__(self):
- self.symbol = None; self.time = None; self.interest_rate = 0.0; self.value = 0.0
-
-class Delisting:
- def __init__(self):
- self.symbol = None; self.time = None; self.type = 0; self.value = 0.0
-
-class SymbolChangedEvent:
- def __init__(self):
- self.symbol = None; self.time = None; self.old_symbol = ""; self.new_symbol = ""
- self.type = 0; self.value = 0.0
-
-# --- Algorithm Mode / Deployment Target ---
-class AlgorithmMode:
- BACKTESTING = 0; RESEARCH = 1; LIVE = 2
- Backtesting = 0; Research = 1; Live = 2
-
-class DeploymentTarget:
- LOCAL = 0; CLOUD = 1; LOCAL_PLATFORM = 0; CLOUD_PLATFORM = 1
- Local = 0; Cloud = 1; LocalPlatform = 0; CloudPlatform = 1
-
-# --- Market Hours / Symbol Cache ---
-class MarketHoursDatabase:
- @staticmethod
- def from_data_folder(): return MarketHoursDatabase()
- def get_exchange_hours(self, market, symbol, security_type): return ExchangeHours()
-
-class SymbolCache:
- @staticmethod
- def get_symbol(ticker): return Symbol(ticker)
-
-class DataMappingMode:
- LAST_TRADING_DAY = 0; FIRST_DAY_MONTH = 1; OPEN_INTEREST = 2; OPEN_INTEREST_ANNUAL = 3
- LastTradingDay = 0; FirstDayMonth = 1; OpenInterest = 2; OpenInterestAnnual = 3
-
-# --- BaseData ---
-class BaseData:
- def __init__(self):
- self.symbol = None; self.time = None; self.end_time = None; self.value = 0.0
-
-# --- Option type ---
-class Option:
- def __init__(self, symbol=None):
- self.symbol = symbol; self.underlying = None; self.contract_filter = None
- self.price_model = None; self.strike_price = 0.0; self.expiry = None; self.right = None
- def set_filter(self, *args, **kwargs): return self
- def SetFilter(self, *args, **kwargs): return self.set_filter(*args, **kwargs)
-
-# --- EquityExchange ---
-class EquityExchange:
- def __init__(self):
- self.hours = ExchangeHours(); self.time_zone = "America/New_York"
-
-# --- IndiaOrderProperties ---
-class IndiaOrderProperties:
- def __init__(self, exchange=None): self.exchange = exchange or ""
-
-# --- ETFConstituentData ---
-class ETFConstituentData:
- def __init__(self):
- self.symbol = None; self.weight = 0.0; self.shares_held = 0; self.market_value = 0.0
-
-# --- Fundamental data class (used by self.history(Fundamental, ...) and type checks) ---
-class Fundamental:
- """Fundamental data point for a security."""
- def __init__(self, **kwargs):
- self.symbol = kwargs.get('symbol', None)
- self.price = kwargs.get('price', 0.0)
- self.end_time = kwargs.get('end_time', None)
- self.dollar_volume = kwargs.get('dollar_volume', 0.0)
- self.volume = kwargs.get('volume', 0)
- self.market_cap = kwargs.get('market_cap', 0.0)
- self.has_fundamental_data = kwargs.get('has_fundamental_data', True)
- self.valuation_ratios = kwargs.get('valuation_ratios', type('VR', (), {'pe_ratio': 0})())
-
-# --- .NET Object replacement with reference_equals ---
-class Object:
- """Python replacement for .NET System.Object."""
- @staticmethod
- def reference_equals(a, b):
- """Check if two objects are the same reference (like .NET ReferenceEquals)."""
- return a is b
- ReferenceEquals = reference_equals
-
-# --- Fundamental Universe Selection Aliases ---
-CoarseFundamentalUniverseSelectionModel = FundamentalUniverseSelectionModel
-FineFundamentalUniverseSelectionModel = FundamentalUniverseSelectionModel
-
-# --- Random ---
-Random = _random_mod.Random
-
-# --- Delay indicator stub ---
-class Delay:
- def __init__(self, period=1):
- self._period = period; self.is_ready = False
- self.current = type('obj', (object,), {'value': 0.0})()
- def update(self, *args): self.is_ready = True; return True
-
-# --- Margin Call Model ---
-class MarginCallModel:
- NULL = None # set after class definition
- @staticmethod
- def null(): return MarginCallModel()
- def get_margin_call_orders(self, *args): return []
-
-class DefaultMarginCallModel(MarginCallModel):
- def __init__(self, *args, **kwargs): pass
-
-MarginCallModel.NULL = MarginCallModel()
-MarginCallModel.Null = MarginCallModel.NULL
-
-# --- SecurityPositionGroupModel ---
-class SecurityPositionGroupModel:
- NULL = None # set after class definition
- def __init__(self, *args, **kwargs): pass
- def get_buying_power_for_strategy(self, *args):
- return type('obj', (object,), {'value': 0})()
-
-SecurityPositionGroupModel.NULL = SecurityPositionGroupModel()
-SecurityPositionGroupModel.Null = SecurityPositionGroupModel.NULL
-
-# --- SubscriptionDataSource ---
-class SubscriptionDataSource:
- def __init__(self, source="", transport_medium=0, format_type=0):
- self.source = source; self.transport_medium = transport_medium; self.format = format_type
-
-class SubscriptionTransportMedium:
- LOCAL_FILE = 0; REMOTE_FILE = 1; REST = 2; OBJECT_STORE = 3
- LocalFile = 0; RemoteFile = 1; Rest = 2; ObjectStore = 3
-
-class FileFormat:
- CSV = 0; BINARY = 1; COLLECTION = 2; Csv = 0; UnfoldingBrowser = 3
-
-# --- System.Collections.Generic stub ---
-class List(list):
- def __init__(self, *args):
- if args and isinstance(args[0], type):
- super().__init__()
- else:
- super().__init__(args)
- def add(self, item):
- self.append(item)
- def Add(self, item):
- self.append(item)
-
-# --- RollingWindow ---
-class _RollingWindowBase:
- """Rolling window (circular buffer) for storing last N values."""
- def __init__(self, size_or_type=None, size=None):
- if size is not None:
- self._size = size
- elif isinstance(size_or_type, int):
- self._size = size_or_type
- else:
- self._size = 10
- self._data = []
- self._count = 0
-
- def add(self, item):
- self._data.insert(0, item)
- if len(self._data) > self._size:
- self._data.pop()
- self._count += 1
-
- def __getitem__(self, index): return self._data[index]
- def __len__(self): return len(self._data)
-
- @property
- def count(self): return len(self._data)
- @property
- def is_ready(self): return len(self._data) >= self._size
- @property
- def most_recently_removed(self): return None
-
- def __iter__(self): return iter(self._data)
- def reset(self): self._data.clear()
-
- Count = property(lambda self: self.count)
- IsReady = property(lambda self: self.is_ready)
- MostRecentlyRemoved = property(lambda self: self.most_recently_removed)
- def Add(self, item): return self.add(item)
- def Reset(self): return self.reset()
-
-class _RollingWindowMeta(type):
- """Metaclass to support RollingWindow[float](5) syntax."""
- def __getitem__(cls, item): return cls
-
-RollingWindow = _RollingWindowMeta('RollingWindow', (_RollingWindowBase,), dict(_RollingWindowBase.__dict__))
-
-# --- ConstituentsUniverse ---
-class ConstituentsUniverse:
- def __init__(self, symbol, universe_filter_func=None):
- self.symbol = symbol
- self._filter = universe_filter_func
-
-ETFConstituentUniverse = ConstituentsUniverse
-
-# --- SequentialConsolidator ---
-class SequentialConsolidator:
- def __init__(self, first, second):
- self.first = first
- self.second = second
- self.data_consolidated = EventHandler()
- def update(self, data):
- pass
-
-# --- VolumeRenkoConsolidator ---
-class VolumeRenkoConsolidator:
- def __init__(self, bar_size, *args):
- self._bar_size = bar_size
- self.data_consolidated = EventHandler()
- def update(self, data):
- pass
-
-# --- CandlestickSeries ---
-class CandlestickSeries:
- def __init__(self, name="", index=0, unit=""):
- self.name = name
-
-# --- PythonConsolidator ---
-class PythonConsolidator:
- def __init__(self):
- self.input_type = None
- self.output_type = None
- self.data_consolidated = EventHandler()
- self.consolidated = None
- self.working_data = None
- def __getattr__(self, name):
- if name == 'data_consolidated':
- self.data_consolidated = EventHandler()
- return self.data_consolidated
- if name == 'consolidated':
- self.consolidated = None
- return None
- if name == 'working_data':
- self.working_data = None
- return None
- raise AttributeError(f"'{type(self).__name__}' object has no attribute '{name}'")
- def update(self, data): pass
- def scan(self, time): pass
-
-# --- IDataConsolidator alias ---
-IDataConsolidator = PythonConsolidator
-
-# --- IBaseDataBar / IBaseData ---
-class IBaseDataBar:
- pass
-
-class IBaseData:
- pass
-
-# --- ScheduledUniverse ---
-class ScheduledUniverse:
- def __init__(self, date_rule, time_rule, selector, settings=None):
- self._date_rule = date_rule
- self._time_rule = time_rule
- self._selector = selector
-
-# --- OptionChainedUniverseSelectionModel ---
-class OptionChainedUniverseSelectionModel(UniverseSelectionModel):
- def __init__(self, universe_selection_model, option_filter=None):
- self._inner = universe_selection_model
- self._filter = option_filter
-
-# --- OptionChains ---
-class OptionChains(dict):
- @property
- def data_frame(self):
- try:
- import pandas as pd
- return pd.DataFrame()
- except ImportError:
- return None
-
-# --- OpenInterestFutureUniverseSelectionModel ---
-class OpenInterestFutureUniverseSelectionModel(UniverseSelectionModel):
- def __init__(self, *args, **kwargs): pass
-
-# --- GeneratedInsightsCollection ---
-class GeneratedInsightsCollection:
- def __init__(self, *args):
- self._insights = list(args) if args else []
- def __iter__(self):
- return iter(self._insights)
- def __len__(self):
- return len(self._insights)
-
-# --- AlphaStreamsBrokerageModel ---
-class AlphaStreamsBrokerageModel:
- def __init__(self, *args, **kwargs): pass
-
-# --- InteractiveBrokersOrderProperties ---
-class InteractiveBrokersOrderProperties:
- def __init__(self):
- self.time_in_force = None
- self.outside_regular_trading_hours = False
-
-# --- CircularQueue ---
-class _CircularQueueMeta(type):
- def __getitem__(cls, item): return cls
-
-class CircularQueue(metaclass=_CircularQueueMeta):
- def __init__(self, items_or_size=None):
- from .consolidators import EventHandler
- if isinstance(items_or_size, (list, tuple)):
- self._data = list(items_or_size)
- self._size = len(self._data)
- self._index = 0
- else:
- self._size = items_or_size or 0
- self._data = []
- self._index = 0
- self.circle_completed = EventHandler()
- def enqueue(self, item):
- self._data.append(item)
- if len(self._data) > self._size:
- self._data.pop(0)
- def dequeue(self):
- if not self._data:
- return None
- item = self._data[self._index]
- self._index = (self._index + 1) % len(self._data)
- if self._index == 0:
- self.circle_completed(self, None)
- return item
- @property
- def current(self):
- if self._data:
- return self._data[self._index % len(self._data)]
- return None
- def __iter__(self):
- return iter(self._data)
- def __len__(self):
- return len(self._data)
-
-# --- EquityFillModel ---
-class EquityFillModel(FillModel):
- pass
-
-# --- FuncRiskFreeRateInterestRateModel ---
-class FuncRiskFreeRateInterestRateModel:
- def __init__(self, func=None):
- self._func = func
-
-# --- MassIndex indicator ---
-class MassIndex:
- def __init__(self, *args, **kwargs):
- self.name = "MASS"
- self.is_ready = False
- self.current = type('obj', (object,), {'value': 0.0})()
- self.warm_up_period = 25
- def update(self, *args): return True
- def __float__(self): return self.current.value
-
-# --- StandardDeviationOfReturnsVolatilityModel ---
-class StandardDeviationOfReturnsVolatilityModel:
- def __init__(self, *args, **kwargs):
- self._periods = args[0] if args else kwargs.get('periods', 252)
- self.volatility = 0.0
-
-# --- MarketImpactSlippageModel ---
-class MarketImpactSlippageModel:
- def __init__(self, *args, **kwargs):
- pass
- def get_slippage_approximation(self, asset, order):
- return 0.0
-
-# --- Collective2/CrunchDAO/Numerai Signal Export ---
-class Collective2SignalExport:
- def __init__(self, api_key="", system_id=0):
- self.api_key = api_key
- self.system_id = system_id
-
-class Collective2PortfolioSignalExport:
- def __init__(self, api_key="", system_id=0):
- self.api_key = api_key
-
-class CrunchDaoSignalExport:
- def __init__(self, api_key="", model="", submission_name="", comment=""):
- pass
-
-class CrunchDaoSkeleton(PythonData):
- pass
-
-class NumeraiSignalExport:
- def __init__(self, *args, **kwargs):
- pass
-
-# --- NullShortableProvider ---
-class NullShortableProvider:
- def __init__(self, *args, **kwargs): pass
- def shortable_quantity(self, symbol, local_time):
- return float('inf')
-
-# --- SymbolProperties / MarginInterestRateParameters ---
-class SymbolProperties:
- def __init__(self, description="", quote_currency="USD", contract_multiplier=1,
- minimum_price_variation=0.01, lot_size=1, market_ticker=""):
- self.description = description
- self.quote_currency = quote_currency
- self.contract_multiplier = contract_multiplier
- self.minimum_price_variation = minimum_price_variation
- self.lot_size = lot_size
- self.market_ticker = market_ticker
- self.minimum_order_size = 1
- self.priceMagnifier = 1
-
-class MarginInterestRateParameters:
- def __init__(self, *args):
- self.security = None
- self.position_group = None
-
-# --- InvalidOperationException ---
-class InvalidOperationException(Exception):
- pass
-
-# --- RegressionTestException ---
-class RegressionTestException(Exception):
- pass
-
-# --- SubscriptionDataConfig ---
-class SubscriptionDataConfig:
- def __init__(self, *args, **kwargs):
- self.symbol = None
- self.resolution = None
- self.type = None
-
-# --- Func stub (for C# Func<> delegates) ---
-class _FuncMeta(type):
- def __getitem__(cls, item): return cls
-
-class Func(metaclass=_FuncMeta):
- def __init__(self, func=None):
- self._func = func
- def __call__(self, *args, **kwargs):
- return self._func(*args, **kwargs) if self._func else None
-
-# --- Command ---
-class Command:
- def __init__(self, *args, **kwargs):
- self.name = ""
- self.parameters = {}
-
- def run(self, algo) -> bool:
- """Override this method to implement command logic."""
- return True
-
- def my_custom_method(self):
- return False
-
- def __str__(self):
- return self.__class__.__name__
-
-# --- AddReference (stub for C# assembly references) ---
-def AddReference(*args):
- pass
-
-# --- Dividend ---
-class Dividend:
- def __init__(self):
- self.symbol = None
- self.distribution = 0.0
- self.reference_price = 0.0
- self.time = None
-
-# --- Orders module stub ---
-class _OrdersModule:
- """Stub for 'from Orders import ...' pattern."""
- OrderDirection = OrderDirection
- OrderType = OrderType
- OrderStatus = OrderStatus
-import sys as _sys
-_orders_mod = type(_sys)('Orders')
-_orders_mod.OrderDirection = OrderDirection
-_orders_mod.OrderType = OrderType
-_orders_mod.OrderStatus = OrderStatus
-_orders_mod.Fees = type('Fees', (), {'OrderFee': OrderFee, 'CashAmount': CashAmount})()
-_sys.modules['Orders'] = _orders_mod
-_sys.modules['Orders.Fees'] = _orders_mod.Fees
-
-# --- FuncSecurityInitializer ---
-class FuncSecurityInitializer:
- def __init__(self, func=None):
- self._func = func
- def initialize(self, security):
- if self._func:
- self._func(security)
-
-# --- CompositeSecurityInitializer ---
-class CompositeSecurityInitializer:
- def __init__(self, *initializers):
- self._initializers = list(initializers)
- def initialize(self, security):
- for init in self._initializers:
- if hasattr(init, 'initialize'):
- init.initialize(security)
-
-# --- CrunchDAO case alias ---
-CrunchDAOSignalExport = CrunchDaoSignalExport
-
-# --- LiquidETFUniverse ---
-class LiquidETFUniverse:
- SP500 = "SPY"
- SP500_SECTORS = ["XLB", "XLE", "XLF", "XLI", "XLK", "XLP", "XLRE", "XLU", "XLV", "XLY"]
-
-# --- InceptionDateUniverseSelectionModel ---
-class InceptionDateUniverseSelectionModel(UniverseSelectionModel):
- def __init__(self, *args, **kwargs): pass
-
-# --- SecurityExchangeHours ---
-SecurityExchangeHours = ExchangeHours
-
-# --- Compression ---
-class Compression:
- UNCOMPRESSED = 0; ZIP = 1; GZIP = 2; ZIP_BYTES = 3
- Uncompressed = 0; Zip = 1; GZip = 2; ZipBytes = 3
-
- @staticmethod
- def zip_bytes(data, entry_name='data'):
- """Compress data bytes into a zip archive."""
- import io, zipfile
- buf = io.BytesIO()
- with zipfile.ZipFile(buf, 'w', zipfile.ZIP_DEFLATED) as zf:
- zf.writestr(entry_name, data if isinstance(data, bytes) else str(data).encode('utf-8'))
- return buf.getvalue()
-
- @staticmethod
- def unzip_bytes(data, entry_name=None):
- """Decompress zip archive bytes."""
- import io, zipfile
- buf = io.BytesIO(data)
- with zipfile.ZipFile(buf, 'r') as zf:
- names = zf.namelist()
- target = entry_name if entry_name else names[0]
- return zf.read(target)
-
- ZipBytes = zip_bytes
- UnzipBytes = unzip_bytes
-
-# --- IntrinioConfig ---
-class IntrinioConfig:
- def __init__(self):
- self.api_key = ""
- @staticmethod
- def set_user_and_password(user="", password=""):
- pass
- @staticmethod
- def set_api_key(key=""):
- pass
- @staticmethod
- def set_time_interval_between_calls(interval=None):
- pass
- SetTimeIntervalBetweenCalls = set_time_interval_between_calls
-
-# --- FillModelParameters ---
-class FillModelParameters:
- def __init__(self, *args, **kwargs):
- self.security = None
- self.order = None
- self.config_provider = None
-
-# --- EmaCrossUniverseSelectionModel (Selection submodule) ---
-class EmaCrossUniverseSelectionModel(UniverseSelectionModel):
- def __init__(self, *args, **kwargs): pass
-
-# --- MeanReversionPortfolioConstructionModel ---
-class MeanReversionPortfolioConstructionModel(PortfolioConstructionModel):
- def __init__(self, *args, **kwargs): pass
-
-# --- RiskParityPortfolioConstructionModel ---
-class RiskParityPortfolioConstructionModel(PortfolioConstructionModel):
- def __init__(self, *args, **kwargs): pass
-
-# --- VolumeShareSlippageModel ---
-class VolumeShareSlippageModel(SlippageModel):
- def __init__(self, *args, **kwargs): pass
-
-# --- Register additional Selection submodules ---
-import types as _types
-_sel_extras = {
- 'EmaCrossUniverseSelectionModel': {'EmaCrossUniverseSelectionModel': EmaCrossUniverseSelectionModel},
- 'ConstituentsUniverse': {'ConstituentsUniverse': ConstituentsUniverse},
- 'ScheduledUniverse': {'ScheduledUniverse': ScheduledUniverse},
- 'OptionChainedUniverseSelectionModel': {'OptionChainedUniverseSelectionModel': OptionChainedUniverseSelectionModel},
- 'InceptionDateUniverseSelectionModel': {'InceptionDateUniverseSelectionModel': InceptionDateUniverseSelectionModel},
-}
-for _name, _attrs in _sel_extras.items():
- _mod = _types.ModuleType(f'Selection.{_name}')
- for _attr_name, _attr_val in _attrs.items():
- setattr(_mod, _attr_name, _attr_val)
- import sys as _sys2
- _sys2.modules[f'Selection.{_name}'] = _mod
-
-# --- Register Portfolio submodules ---
-_port_extras = {
- 'MeanReversionPortfolioConstructionModel': {'MeanReversionPortfolioConstructionModel': MeanReversionPortfolioConstructionModel},
- 'RiskParityPortfolioConstructionModel': {'RiskParityPortfolioConstructionModel': RiskParityPortfolioConstructionModel},
-}
-for _name, _attrs in _port_extras.items():
- _mod = _types.ModuleType(f'Portfolio.{_name}')
- for _attr_name, _attr_val in _attrs.items():
- setattr(_mod, _attr_name, _attr_val)
- _sys2.modules[f'Portfolio.{_name}'] = _mod
-
-# --- Register Orders submodules ---
-_orders_slippage = _types.ModuleType('Orders.Slippage')
-_orders_slippage.VolumeShareSlippageModel = VolumeShareSlippageModel
-_sys2.modules['Orders.Slippage'] = _orders_slippage
-
-# Also register submodule path so 'from Orders.Slippage.VolumeShareSlippageModel import ...' works
-_orders_parent = _types.ModuleType('Orders')
-_orders_parent.Slippage = _orders_slippage
-_sys2.modules['Orders'] = _orders_parent
-_vsm_mod = _types.ModuleType('Orders.Slippage.VolumeShareSlippageModel')
-_vsm_mod.VolumeShareSlippageModel = VolumeShareSlippageModel
-_sys2.modules['Orders.Slippage.VolumeShareSlippageModel'] = _vsm_mod
-
-# --- Calendar (for consolidator CalendarType) ---
-class Calendar:
- """Calendar-based consolidation types."""
- @staticmethod
- def weekly(dt):
- return dt.weekday() == 4 # Friday
- @staticmethod
- def monthly(dt):
- import calendar as _cal
- _, last_day = _cal.monthrange(dt.year, dt.month)
- return dt.day == last_day
- Weekly = weekly
- Monthly = monthly
- WEEKLY = weekly
- MONTHLY = monthly
-
- @staticmethod
- def quarterly(dt):
- import calendar as _cal
- _, last_day = _cal.monthrange(dt.year, dt.month)
- return dt.month in (3, 6, 9, 12) and dt.day == last_day
- QUARTERLY = quarterly
- Quarterly = quarterly
-
- @staticmethod
- def yearly(dt):
- return dt.month == 12 and dt.day == 31
- YEARLY = yearly
- Yearly = yearly
-
-# --- WilderAccumulativeSwingIndex indicator ---
-class WilderAccumulativeSwingIndex(IndicatorBase):
- def __init__(self, name="WASI", limit_move=0):
- super().__init__(name, limit_move or 14)
- def _compute(self, value: float) -> float:
- return value
-
-# --- Beta indicator ---
-class Beta(IndicatorBase):
- def __init__(self, *args, **kwargs):
- name = args[0] if args else kwargs.get('name', 'BETA')
- period = args[1] if len(args) > 1 else kwargs.get('period', 20)
- if isinstance(name, str):
- super().__init__(name, period)
- else:
- super().__init__('BETA', 20)
- def _compute(self, value: float) -> float:
- return 1.0 # Default beta = 1
-
-# --- WilderSwingIndex indicator ---
-class WilderSwingIndex(IndicatorBase):
- def __init__(self, name="WSI", limit_move=0):
- super().__init__(name, limit_move or 14)
- def _compute(self, value: float) -> float:
- return value
-
-# --- Identity indicator ---
-class Identity(IndicatorBase):
- def __init__(self, name="ID"):
- super().__init__(name, 1)
- def _compute(self, value: float) -> float:
- return value
-
-# --- IntrinioEconomicData ---
-class IntrinioEconomicData(PythonData):
- pass
-
-# --- FundamentalUniverse ---
-class FundamentalUniverse:
- @staticmethod
- def usa(*args, **kwargs):
- return None
- USA = usa
-
-# --- Futures.Dairy patch ---
-class FuturesDairy:
- BUTTER = "butter"; CLASS_III_MILK = "class_iii_milk"; CASH_SETTLED_CHEESE = "cash_settled_cheese"
- Butter = "butter"; ClassIIIMilk = "class_iii_milk"; CashSettledCheese = "cash_settled_cheese"
-
-if not hasattr(Futures, 'Dairy'):
- Futures.Dairy = FuturesDairy
-
-# --- SecurityIdentifier.upper() / generate_constituent_identifier ---
-if not hasattr(SecurityIdentifier, 'upper'):
- SecurityIdentifier.upper = lambda self: str(self)
-
-if not hasattr(SecurityIdentifier, 'generate_constituent_identifier'):
- SecurityIdentifier.generate_constituent_identifier = staticmethod(
- lambda data_mapping_symbol, constituent_symbol, *args: SecurityIdentifier()
- )
- SecurityIdentifier.GenerateConstituentIdentifier = SecurityIdentifier.generate_constituent_identifier
-
-# --- ImpliedVolatility indicator ---
-class ImpliedVolatility(IndicatorBase):
- def __init__(self, *args, **kwargs):
- name = args[0] if args and isinstance(args[0], str) else 'IV'
- super().__init__(name, 1)
- def _compute(self, value: float) -> float:
- return 0.25 # Default IV
-
-# --- Tiingo alias ---
-class Tiingo:
- """Tiingo data type stub."""
- def __init__(self):
- self.symbol = None; self.time = None; self.close = 0; self.value = 0
- self.high = 0; self.low = 0; self.open = 0; self.volume = 0
-
-class TiingoPrice(Tiingo):
- pass
-
-class TiingoDailyData(Tiingo):
- pass
-
-# --- LeanData ---
-class LeanData:
- @staticmethod
- def generate_zip_file_name(symbol, date, resolution, tick_type=None):
- return f"{str(symbol).lower()}.zip"
- @staticmethod
- def generate_zip_entry_name(symbol, date, resolution, tick_type=None):
- return f"{str(symbol).lower()}.csv"
- GenerateZipFileName = generate_zip_file_name
- GenerateZipEntryName = generate_zip_entry_name
-
-# --- SymbolPropertiesDatabase ---
-class SymbolPropertiesDatabase:
- @staticmethod
- def from_data_folder():
- return SymbolPropertiesDatabase()
- def get_symbol_properties(self, market, symbol, security_type, currency="USD"):
- from .securities import SymbolProperties as SP
- return SP()
- def set_entry(self, *args, **kwargs):
- pass
- SetEntry = set_entry
- GetSymbolProperties = get_symbol_properties
-
-# --- MarketHoursDatabase (alias from algorithm.py) ---
-from .algorithm import _MarketHoursDatabase, _SymbolPropertiesDatabase
-
-# --- InterestRateProvider ---
-class InterestRateProvider:
- def __init__(self, *args, **kwargs):
- pass
- def get_interest_rate(self, date):
- return 0.05 # 5% default rate
-
-# --- Tiingo top-level alias ---
-class Tiingo:
- def __init__(self):
- self.symbol = None; self.time = None; self.close = 0; self.value = 0
- @staticmethod
- def set_auth_code(code):
- pass
- SetAuthCode = set_auth_code
-
-class TiingoPrice(Tiingo):
- pass
-
-# --- SymbolPropertiesDatabase alias ---
-SymbolPropertiesDatabase = _SymbolPropertiesDatabase
-
-# --- OptionChain (single underlying chain result type) ---
-OptionChain = type('OptionChain', (), {
- '__init__': lambda self, *a, **kw: None,
- 'underlying': None,
- 'contracts': {},
- '__iter__': lambda self: iter([]),
- '__len__': lambda self: 0,
-})
-
-# --- BrokerageModel ---
-class BrokerageModel:
- def __init__(self, *args, **kwargs): pass
- def get_fee_model(self, security): return FeeModel()
- def get_fill_model(self, security): return FillModel()
- def get_slippage_model(self, security): return SlippageModel()
- def can_submit_order(self, security, order, message=None): return True
-
-class DefaultBrokerageModel2(BrokerageModel):
- pass
-
-# --- CustomData alias (for IndicatorSuiteAlgorithm) ---
-CustomData = type('CustomData', (), {
- '__init__': lambda self: None,
- 'symbol': None, 'time': None, 'value': 0,
- 'get_source': lambda self, *a: None,
- 'reader': lambda self, *a: None,
-})
-
-# --- DividendYieldProvider ---
-class DividendYieldProvider:
- def __init__(self, *args, **kwargs): pass
- def get_dividend_yield(self, date, *args): return 0.02
-
-# --- LocalDiskMapFileProvider ---
-class LocalDiskMapFileProvider:
- def __init__(self, *args, **kwargs): pass
- def initialize(self, *args, **kwargs): pass
- def get(self, *args, **kwargs): return None
-
-# --- OptionAssignmentRegressionAlgorithm (referenced by subclass strategies) ---
-# Stub base class so subclasses can inherit
-class OptionAssignmentRegressionAlgorithm(QCAlgorithm):
- """Stub base for option assignment regression tests."""
- pass
-
-# --- BaseVolatilityModel ---
-class BaseVolatilityModel:
- """Base volatility model for securities."""
- def __init__(self, *args, **kwargs):
- self.volatility = 0.0
- def update(self, security, data): pass
- def get_history_requirements(self, security, utc_time):
- return []
- @staticmethod
- def null():
- return BaseVolatilityModel()
-
-# --- DefaultOptionAssignmentModel ---
-class DefaultOptionAssignmentModel:
- """Default option assignment model."""
- def __init__(self, *args, **kwargs): pass
- def get_assignment(self, parameters):
- return type('AssignmentResult', (), {'is_assigned': False})()
-
-# --- DefaultExerciseModel ---
-class DefaultExerciseModel:
- """Default option exercise model."""
- def __init__(self, *args, **kwargs): pass
- def get_exercise(self, parameters):
- return []
-
-# --- ImpliedVolatility with set_smoothing_function ---
-# Override the one defined earlier
-class ImpliedVolatility(IndicatorBase):
- def __init__(self, *args, **kwargs):
- name = args[0] if args and isinstance(args[0], str) else 'IV'
- super().__init__(name, 1)
- self._smoothing_func = None
- def _compute(self, value: float) -> float:
- return 0.25
- def set_smoothing_function(self, func):
- self._smoothing_func = func
- def SetSmoothingFunction(self, func):
- self._smoothing_func = func
-
-# --- OptionExerciseOrder ---
-class OptionExerciseOrder:
- """Represents an option exercise order."""
- def __init__(self, symbol=None, quantity=0, tag=""):
- self.symbol = symbol
- self.quantity = quantity
- self.tag = tag
- self.type = 0
- self.status = 0
- self.direction = 0
-
-# --- LocalDiskFactorFileProvider ---
-class _FactorFile:
- """Stub factor file."""
- def get_price_scale_factor(self, time):
- return 1.0
- def GetPriceScaleFactor(self, time):
- return 1.0
-
-class LocalDiskFactorFileProvider:
- """Local disk factor file provider stub."""
- def __init__(self, *args, **kwargs): pass
- def initialize(self, *args, **kwargs): pass
- def get(self, *args, **kwargs): return _FactorFile()
-
-# --- CustomImpliedVolatility (for OptionIndicatorsMirror strategies) ---
-class CustomImpliedVolatility(IndicatorBase):
- """Custom IV indicator that accepts option, mirror, rate model, yield model."""
- def __init__(self, *args, **kwargs):
- name = 'CustomIV'
- super().__init__(name, 1)
- self._smoothing_func = None
- def _compute(self, value: float) -> float:
- return 0.25
- def set_smoothing_function(self, func):
- self._smoothing_func = func
- def SetSmoothingFunction(self, func):
- self._smoothing_func = func
diff --git a/fincept-qt/scripts/strategies/fincept_engine/consolidators.py b/fincept-qt/scripts/strategies/fincept_engine/consolidators.py
deleted file mode 100644
index 15c3cccce..000000000
--- a/fincept-qt/scripts/strategies/fincept_engine/consolidators.py
+++ /dev/null
@@ -1,232 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine Consolidators
-# Aggregate data into larger bars (minute->hour, tick->bar, renko, range)
-# ============================================================================
-
-from datetime import datetime, timedelta
-from typing import Callable, Optional
-from .types import TradeBar, QuoteBar, Tick
-
-
-class EventHandler:
- """Supports += and -= for event registration like C# events."""
- def __init__(self):
- self._handlers = []
-
- def __iadd__(self, handler):
- self._handlers.append(handler)
- return self
-
- def __isub__(self, handler):
- if handler in self._handlers:
- self._handlers.remove(handler)
- return self
-
- def __call__(self, *args, **kwargs):
- for h in self._handlers:
- h(*args, **kwargs)
-
- def __bool__(self):
- return len(self._handlers) > 0
-
-
-class ConsolidatorBase:
- """Base class for data consolidators."""
-
- def __init__(self):
- self.data_consolidated = EventHandler()
- self._working_bar = None
- self.consolidated = None
-
- def __getattr__(self, name):
- # Ensure data_consolidated always exists even if subclass skips super().__init__
- if name == 'data_consolidated':
- self.data_consolidated = EventHandler()
- return self.data_consolidated
- if name == '_working_bar':
- self._working_bar = None
- return None
- if name == 'consolidated':
- self.consolidated = None
- return None
- raise AttributeError(f"'{type(self).__name__}' object has no attribute '{name}'")
-
- def update(self, data):
- raise NotImplementedError
-
- def scan(self, time: datetime):
- pass
-
-
-class TradeBarConsolidator(ConsolidatorBase):
- """Consolidates trade bars into larger period bars."""
-
- def __init__(self, period=None, max_count: int = None):
- super().__init__()
- if isinstance(period, timedelta):
- self._period = period
- self._max_count = None
- elif isinstance(period, int):
- self._period = None
- self._max_count = period
- else:
- self._period = period
- self._max_count = max_count
-
- self._count = 0
- self._period_start = None
-
- def update(self, bar: TradeBar):
- if self._working_bar is None:
- self._working_bar = TradeBar(
- time=bar.time, symbol=bar.symbol,
- open=bar.open, high=bar.high,
- low=bar.low, close=bar.close, volume=bar.volume
- )
- self._period_start = bar.time
- self._count = 1
- else:
- self._working_bar.high = max(self._working_bar.high, bar.high)
- self._working_bar.low = min(self._working_bar.low, bar.low)
- self._working_bar.close = bar.close
- self._working_bar.volume += bar.volume
- self._working_bar.end_time = bar.time
- self._count += 1
-
- should_emit = False
- if self._max_count and self._count >= self._max_count:
- should_emit = True
- elif self._period and self._period_start:
- if bar.time - self._period_start >= self._period:
- should_emit = True
-
- if should_emit:
- self.consolidated = self._working_bar
- if self.data_consolidated:
- self.data_consolidated(self, self._working_bar)
- self._working_bar = None
- self._count = 0
- self._period_start = None
-
-
-class QuoteBarConsolidator(ConsolidatorBase):
- """Consolidates quote bars into larger period bars."""
-
- def __init__(self, period=None):
- super().__init__()
- self._period = period if isinstance(period, timedelta) else timedelta(minutes=period or 1)
- self._period_start = None
-
- def update(self, bar: QuoteBar):
- if self._working_bar is None:
- self._working_bar = bar
- self._period_start = bar.time
- else:
- self._working_bar.close = bar.close
- self._working_bar.value = bar.value
-
- if bar.time - self._period_start >= self._period:
- self.consolidated = self._working_bar
- if self.data_consolidated:
- self.data_consolidated(self, self._working_bar)
- self._working_bar = None
- self._period_start = None
-
-
-class RenkoConsolidator(ConsolidatorBase):
- """Renko bar consolidator."""
-
- def __init__(self, bar_size: float, renko_type=None, force_classic=None):
- super().__init__()
- self._bar_size = bar_size
- self._last_close = None
-
- def update(self, data):
- price = data.close if hasattr(data, 'close') else float(data)
-
- if self._last_close is None:
- self._last_close = price
- return
-
- diff = price - self._last_close
- bricks = int(abs(diff) / self._bar_size)
-
- for _ in range(bricks):
- direction = 1 if diff > 0 else -1
- new_close = self._last_close + (direction * self._bar_size)
- bar = TradeBar(
- time=data.time if hasattr(data, 'time') else datetime.now(),
- symbol=data.symbol if hasattr(data, 'symbol') else None,
- open=self._last_close,
- high=max(self._last_close, new_close),
- low=min(self._last_close, new_close),
- close=new_close,
- volume=data.volume if hasattr(data, 'volume') else 0
- )
- self.consolidated = bar
- if self.data_consolidated:
- self.data_consolidated(self, bar)
- self._last_close = new_close
-
-
-class RangeConsolidator(ConsolidatorBase):
- """Range bar consolidator."""
-
- def __init__(self, range_size: float):
- super().__init__()
- self._range_size = range_size
-
- def update(self, data):
- price = data.close if hasattr(data, 'close') else float(data)
-
- if self._working_bar is None:
- self._working_bar = TradeBar(
- time=data.time if hasattr(data, 'time') else datetime.now(),
- symbol=data.symbol if hasattr(data, 'symbol') else None,
- open=price, high=price, low=price, close=price,
- volume=data.volume if hasattr(data, 'volume') else 0
- )
- return
-
- self._working_bar.high = max(self._working_bar.high, price)
- self._working_bar.low = min(self._working_bar.low, price)
- self._working_bar.close = price
- self._working_bar.volume += data.volume if hasattr(data, 'volume') else 0
-
- if self._working_bar.high - self._working_bar.low >= self._range_size:
- self.consolidated = self._working_bar
- if self.data_consolidated:
- self.data_consolidated(self, self._working_bar)
- self._working_bar = None
-
-
-class TickConsolidator(ConsolidatorBase):
- """Consolidates ticks into trade bars."""
-
- def __init__(self, max_count: int):
- super().__init__()
- self._max_count = max_count
- self._count = 0
-
- def update(self, tick: Tick):
- if self._working_bar is None:
- self._working_bar = TradeBar(
- time=tick.time, symbol=tick.symbol,
- open=tick.price, high=tick.price,
- low=tick.price, close=tick.price,
- volume=tick.quantity
- )
- self._count = 1
- else:
- self._working_bar.high = max(self._working_bar.high, tick.price)
- self._working_bar.low = min(self._working_bar.low, tick.price)
- self._working_bar.close = tick.price
- self._working_bar.volume += tick.quantity
- self._count += 1
-
- if self._count >= self._max_count:
- self.consolidated = self._working_bar
- if self.data_consolidated:
- self.data_consolidated(self, self._working_bar)
- self._working_bar = None
- self._count = 0
diff --git a/fincept-qt/scripts/strategies/fincept_engine/enums.py b/fincept-qt/scripts/strategies/fincept_engine/enums.py
deleted file mode 100644
index 87a04179e..000000000
--- a/fincept-qt/scripts/strategies/fincept_engine/enums.py
+++ /dev/null
@@ -1,299 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine Enums
-# Pure Python replacement for LEAN C# enums
-# ============================================================================
-
-from enum import Enum, IntEnum
-
-
-class Resolution(IntEnum):
- TICK = 0
- SECOND = 1
- MINUTE = 2
- HOUR = 3
- DAILY = 4
-
- # Aliases for compatibility
- @classmethod
- def _missing_(cls, value):
- aliases = {
- 'tick': cls.TICK, 'second': cls.SECOND,
- 'minute': cls.MINUTE, 'hour': cls.HOUR,
- 'daily': cls.DAILY, 'day': cls.DAILY
- }
- if isinstance(value, str):
- return aliases.get(value.lower())
- return None
-
- def to_timedelta(self):
- from datetime import timedelta
- mapping = {
- Resolution.TICK: timedelta(milliseconds=1),
- Resolution.SECOND: timedelta(seconds=1),
- Resolution.MINUTE: timedelta(minutes=1),
- Resolution.HOUR: timedelta(hours=1),
- Resolution.DAILY: timedelta(days=1),
- }
- return mapping[self]
-
- def to_pandas_freq(self):
- mapping = {
- Resolution.SECOND: '1s',
- Resolution.MINUTE: '1min',
- Resolution.HOUR: '1h',
- Resolution.DAILY: '1D',
- }
- return mapping.get(self, '1min')
-
-
-class SecurityType(IntEnum):
- BASE = 0
- EQUITY = 1
- OPTION = 2
- COMMODITY = 3
- FOREX = 4
- FUTURE = 5
- CFD = 6
- CRYPTO = 7
- INDEX = 8
- FUTURE_OPTION = 9
- INDEX_OPTION = 10
- CRYPTO_FUTURE = 11
-
- Base = 0
-
-
-class OrderType(IntEnum):
- MARKET = 0
- LIMIT = 1
- STOP_MARKET = 2
- STOP_LIMIT = 3
- MARKET_ON_OPEN = 4
- MARKET_ON_CLOSE = 5
- LIMIT_IF_TOUCHED = 6
- COMBO_MARKET = 7
- COMBO_LIMIT = 8
- COMBO_LEG_LIMIT = 9
- TRAILING_STOP = 10
-
-
-class OrderStatus(IntEnum):
- NEW = 0
- SUBMITTED = 1
- PARTIALLY_FILLED = 2
- FILLED = 3
- CANCELED = 5
- INVALID = 6
- CANCEL_PENDING = 7
- UPDATE_SUBMITTED = 8
-
-
-class OrderDirection(IntEnum):
- BUY = 0
- SELL = 1
- HOLD = 2
-
-
-class Market:
- USA = "usa"
- INDIA = "india"
- NSE = "nse"
- BSE = "bse"
- CME = "cme"
- COMEX = "comex"
- EUREX = "eurex"
- OANDA = "oanda"
- BINANCE = "binance"
- GDAX = "gdax"
- INTERACTIVE_BROKERS = "interactive_brokers"
- KRAKEN = "kraken"
- BYBIT = "bybit"
- MCX = "mcx"
- NFO = "nfo"
-
-
-class InsightDirection(IntEnum):
- UP = 1
- DOWN = -1
- FLAT = 0
-
-
-class InsightType(IntEnum):
- PRICE = 0
- VOLATILITY = 1
-
-
-class TimeInForce:
- GOOD_TIL_CANCELED = "gtc"
- DAY = "day"
- GOOD_TIL_DATE = "gtd"
- IMMEDIATE_OR_CANCEL = "ioc"
- FILL_OR_KILL = "fok"
-
- @staticmethod
- def good_til_canceled():
- return TimeInForce.GOOD_TIL_CANCELED
-
- @staticmethod
- def day():
- return TimeInForce.DAY
-
-
-class DataNormalizationMode(IntEnum):
- RAW = 0
- ADJUSTED = 1
- SPLIT_ADJUSTED = 2
- TOTAL_RETURN = 3
- BACKWARDS_RATIO = 4
- BACKWARDS_PANAMA_CANAL = 5
- FORWARD_PANAMA_CANAL = 6
-
- # Aliases
- Raw = 0
- Adjusted = 1
- SplitAdjusted = 2
- TotalReturn = 3
- BackwardsRatio = 4
- BackwardsPanamaCanal = 5
- ForwardPanamaCanal = 6
-
-
-class MovingAverageType(IntEnum):
- """Type of moving average for indicators"""
- SIMPLE = 0
- EXPONENTIAL = 1
- WILDERS = 2
- LINEAR_WEIGHTED = 3
- DOUBLE_EXPONENTIAL = 4
- TRIPLE_EXPONENTIAL = 5
- TRIANGULAR = 6
- T3 = 7
- KAMA = 8
- HULL = 9
- ALMA = 10
-
- # Aliases
- Simple = 0
- Exponential = 1
- Wilders = 2
- LinearWeightedMovingAverage = 3
- DoubleExponential = 4
- TripleExponential = 5
- Triangular = 6
- Kama = 8
- Hull = 9
-
-
-class OptionRight(IntEnum):
- """Option right (call or put)"""
- CALL = 0
- PUT = 1
-
- # Aliases
- Call = 0
- Put = 1
-
-
-class OptionStyle(IntEnum):
- """Option exercise style"""
- AMERICAN = 0
- EUROPEAN = 1
-
- # Aliases
- American = 0
- European = 1
-
-
-class BrokerageName(IntEnum):
- """Brokerage names for configuration"""
- DEFAULT = 0
- INTERACTIVE_BROKERS_BROKERAGE = 1
- TRADIER_BROKERAGE = 2
- OANDA_BROKERAGE = 3
- FXCM_BROKERAGE = 4
- BITFINEX_BROKERAGE = 5
- BINANCE_BROKERAGE = 6
- GDAX_BROKERAGE = 7
- ALPACA_BROKERAGE = 8
- ZERODHA_BROKERAGE = 9
- SAMCO_BROKERAGE = 10
- KRAKEN_BROKERAGE = 11
- FYERS_BROKERAGE = 12
- BYBIT = 13
- BYBIT_BROKERAGE = 13
- COINBASE = 14
- AXOS = 15
- AXOS_BROKERAGE = 15
- GDAX = 7
- BINANCE_FUTURES = 16
- BINANCE_COIN_FUTURES = 17
- EXANTE = 18
- FTX = 19
- FTX_US = 20
- WOLVERINE = 21
- TD_AMERITRADE = 22
- TERMINAL_LINK = 23
- TRADING_TECHNOLOGIES = 24
- QUANTCONNECT = 25
- ALPHA_STREAMS = 26
- BINANCE = 6
-
- # Aliases
- Default = 0
- InteractiveBrokersBrokerage = 1
- TradierBrokerage = 2
- OandaBrokerage = 3
- FxcmBrokerage = 4
- BitfinexBrokerage = 5
- BinanceBrokerage = 6
- GDAXBrokerage = 7
- AlpacaBrokerage = 8
- ZerodhaBrokerage = 9
- SamcoBrokerage = 10
- KrakenBrokerage = 11
- FyersBrokerage = 12
- BybitBrokerage = 13
- CoinbaseBrokerage = 14
- AxosBrokerage = 15
- BinanceFuturesBrokerage = 16
- BinanceCoinFuturesBrokerage = 17
- ExanteBrokerage = 18
- FTXBrokerage = 19
- FTXUSBrokerage = 20
- WolverineBrokerage = 21
- TDAmeritradeBrokerage = 22
- TerminalLinkBrokerage = 23
- TradingTechnologiesBrokerage = 24
- QuantConnectBrokerage = 25
- AlphaStreamsBrokerage = 26
- Binance = 6
-
-
-class AccountType(IntEnum):
- """Account type for trading"""
- MARGIN = 0
- CASH = 1
-
- # Aliases
- Margin = 0
- Cash = 1
-
-
-class PositionSide(IntEnum):
- """Position side"""
- LONG = 0
- SHORT = 1
-
- # Aliases
- Long = 0
- Short = 1
-
-
-class SettlementType(IntEnum):
- """Settlement type for trades"""
- IMMEDIATE = 0
- DELAYED = 1
-
- # Aliases
- Immediate = 0
- Delayed = 1
diff --git a/fincept-qt/scripts/strategies/fincept_engine/extensions.py b/fincept-qt/scripts/strategies/fincept_engine/extensions.py
deleted file mode 100644
index 8e5219ebb..000000000
--- a/fincept-qt/scripts/strategies/fincept_engine/extensions.py
+++ /dev/null
@@ -1,449 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine Extensions
-# Pure Python replacement for LEAN C# extension methods
-# ============================================================================
-
-from datetime import datetime, timedelta, time as dt_time, timezone
-from typing import Optional, List, Any
-import math
-
-
-class Time:
- """Utility class for time-related operations (replaces LEAN's Time class)"""
-
- # Common time spans
- ONE_MINUTE = timedelta(minutes=1)
- ONE_HOUR = timedelta(hours=1)
- ONE_DAY = timedelta(days=1)
- ONE_SECOND = timedelta(seconds=1)
-
- @staticmethod
- def multiply(td: timedelta, factor: float) -> timedelta:
- """Multiply a timedelta by a factor"""
- return timedelta(seconds=td.total_seconds() * factor)
-
- @staticmethod
- def parse(time_str: str) -> dt_time:
- """Parse a time string to time object"""
- if ':' in time_str:
- parts = time_str.split(':')
- hour = int(parts[0])
- minute = int(parts[1]) if len(parts) > 1 else 0
- second = int(parts[2]) if len(parts) > 2 else 0
- return dt_time(hour, minute, second)
- return dt_time(int(time_str), 0, 0)
-
- @staticmethod
- def end_of_day(dt: datetime) -> datetime:
- """Get end of day for a datetime"""
- return dt.replace(hour=23, minute=59, second=59, microsecond=999999)
-
- @staticmethod
- def start_of_day(dt: datetime) -> datetime:
- """Get start of day for a datetime"""
- return dt.replace(hour=0, minute=0, second=0, microsecond=0)
-
- @staticmethod
- def each_tradeable_day_in_time_zone(exchange_hours, start, end, time_zone=None, include_extended=False):
- """Yield each tradeable day between start and end."""
- current = start
- while current <= end:
- if current.weekday() < 5: # Mon-Fri
- yield current
- current += timedelta(days=1)
-
- EachTradeableDayInTimeZone = each_tradeable_day_in_time_zone
-
-
-class TimeZones:
- """Common timezone definitions (replaces LEAN's TimeZones)"""
-
- NEW_YORK = timezone(timedelta(hours=-5))
- CHICAGO = timezone(timedelta(hours=-6))
- LOS_ANGELES = timezone(timedelta(hours=-8))
- LONDON = timezone(timedelta(hours=0))
- TOKYO = timezone(timedelta(hours=9))
- HONG_KONG = timezone(timedelta(hours=8))
- SINGAPORE = timezone(timedelta(hours=8))
- SYDNEY = timezone(timedelta(hours=10))
- MUMBAI = timezone(timedelta(hours=5, minutes=30))
- UTC = timezone.utc
-
- # Aliases
- NewYork = NEW_YORK
- Chicago = CHICAGO
- LosAngeles = LOS_ANGELES
- London = LONDON
- Tokyo = TOKYO
- HongKong = HONG_KONG
- Singapore = SINGAPORE
- Sydney = SYDNEY
- Mumbai = MUMBAI
- Utc = UTC
-
- @staticmethod
- def get_timezone(name: str) -> timezone:
- """Get timezone by name"""
- tz_map = {
- 'new_york': TimeZones.NEW_YORK,
- 'chicago': TimeZones.CHICAGO,
- 'los_angeles': TimeZones.LOS_ANGELES,
- 'london': TimeZones.LONDON,
- 'tokyo': TimeZones.TOKYO,
- 'hong_kong': TimeZones.HONG_KONG,
- 'singapore': TimeZones.SINGAPORE,
- 'sydney': TimeZones.SYDNEY,
- 'mumbai': TimeZones.MUMBAI,
- 'utc': TimeZones.UTC,
- }
- return tz_map.get(name.lower().replace(' ', '_'), TimeZones.UTC)
-
-
-class Extensions:
- """Extension methods for various LEAN types (static utility class)"""
-
- @staticmethod
- def to_time_span(minutes: int = 0, hours: int = 0, days: int = 0,
- seconds: int = 0) -> timedelta:
- """Convert to timedelta (TimeSpan equivalent)"""
- return timedelta(days=days, hours=hours, minutes=minutes, seconds=seconds)
-
- @staticmethod
- def _resolve_tz(tz):
- """Resolve timezone: accept string or tzinfo object."""
- if isinstance(tz, str):
- try:
- from zoneinfo import ZoneInfo
- return ZoneInfo(tz)
- except (ImportError, KeyError):
- return timezone.utc
- return tz if tz is not None else timezone.utc
-
- @staticmethod
- def convert_from_utc(dt: datetime, tz) -> datetime:
- """Convert UTC datetime to specified timezone"""
- if dt.tzinfo is None:
- dt = dt.replace(tzinfo=timezone.utc)
- return dt.astimezone(Extensions._resolve_tz(tz))
-
- @staticmethod
- def convert_to_utc(dt: datetime, tz) -> datetime:
- """Convert datetime from specified timezone to UTC"""
- resolved_tz = Extensions._resolve_tz(tz)
- if dt.tzinfo is None:
- dt = dt.replace(tzinfo=resolved_tz)
- return dt.astimezone(timezone.utc)
-
- @staticmethod
- def read_lines(file_path: str) -> List[str]:
- """Read all lines from a file"""
- try:
- with open(file_path, 'r') as f:
- return f.readlines()
- except Exception:
- return []
-
- @staticmethod
- def round_to_significant_digits(value: float, digits: int) -> float:
- """Round a number to specified significant digits"""
- if value == 0:
- return 0
- return round(value, digits - int(math.floor(math.log10(abs(value)))) - 1)
-
- @staticmethod
- def is_null_or_empty(s: Optional[str]) -> bool:
- """Check if string is null or empty"""
- return s is None or len(s) == 0
-
- @staticmethod
- def safe_multiply(a: float, b: float) -> float:
- """Safe multiplication handling edge cases"""
- if math.isnan(a) or math.isnan(b):
- return float('nan')
- if math.isinf(a) or math.isinf(b):
- return float('inf') if (a > 0) == (b > 0) else float('-inf')
- return a * b
-
- @staticmethod
- def is_option(security_type) -> bool:
- """Check if security type is an option type."""
- val = int(security_type) if hasattr(security_type, '__int__') else security_type
- return val in (2, 9, 10) # OPTION, FUTURE_OPTION, INDEX_OPTION
-
- @staticmethod
- def get_order_direction(quantity) -> int:
- """Get order direction from quantity."""
- if quantity > 0:
- return 0 # BUY
- elif quantity < 0:
- return 1 # SELL
- return 2 # HOLD
-
- # PascalCase aliases
- IsOption = is_option
- GetOrderDirection = get_order_direction
-
-
-class IndicatorExtensions:
- """Extension methods for indicators"""
-
- @staticmethod
- def sma(indicator: Any, period: int) -> 'SimpleMovingAverageWrapper':
- """Create an SMA of another indicator's values"""
- return SimpleMovingAverageWrapper(indicator, period)
-
- @staticmethod
- def ema(indicator: Any, period: int) -> 'ExponentialMovingAverageWrapper':
- """Create an EMA of another indicator's values"""
- return ExponentialMovingAverageWrapper(indicator, period)
-
- @staticmethod
- def of(indicator: Any, selector: Any = None) -> Any:
- """Chain indicators together"""
- return indicator
-
- @staticmethod
- def over(indicator: Any, other: Any, selector: Any = None) -> Any:
- """Chain indicator over another (e.g., SMA over RSI)"""
- return indicator
-
- @staticmethod
- def minus(indicator: Any, other: Any) -> Any:
- """Subtract one indicator from another"""
- return indicator
-
- @staticmethod
- def plus(indicator: Any, other: Any) -> Any:
- """Add one indicator to another"""
- return indicator
-
- @staticmethod
- def times(indicator: Any, factor: float) -> Any:
- """Multiply indicator by factor"""
- return indicator
-
- Of = of
- Over = over
- SMA = sma
- EMA = ema
-
-
-class _WrapperEventHandler:
- """Supports += and -= for wrapper event registration."""
- def __init__(self):
- self._handlers = []
- def __iadd__(self, handler):
- self._handlers.append(handler)
- return self
- def __isub__(self, handler):
- if handler in self._handlers:
- self._handlers.remove(handler)
- return self
- def __call__(self, *args, **kwargs):
- for h in self._handlers:
- h(*args, **kwargs)
-
-
-class SimpleMovingAverageWrapper:
- """Wrapper to compute SMA of another indicator"""
-
- def __init__(self, source: Any, period: int):
- self.source = source
- self.period = period
- self._values: List[float] = []
- self._current = 0.0
- self.is_ready = False
- self.updated = _WrapperEventHandler()
-
- def update(self, value: float) -> bool:
- """Update with new value"""
- self._values.append(value)
- if len(self._values) > self.period:
- self._values.pop(0)
- if len(self._values) >= self.period:
- self._current = sum(self._values) / len(self._values)
- self.is_ready = True
- return True
- return False
-
- @property
- def current(self) -> float:
- return self._current
-
- @property
- def Current(self) -> Any:
- """LEAN-style property"""
- class Value:
- def __init__(self, val):
- self.Value = val
- return Value(self._current)
-
-
-class ExponentialMovingAverageWrapper:
- """Wrapper to compute EMA of another indicator"""
-
- def __init__(self, source: Any, period: int):
- self.source = source
- self.period = period
- self._current = 0.0
- self._count = 0
- self._multiplier = 2.0 / (period + 1)
- self.is_ready = False
- self.updated = _WrapperEventHandler()
-
- def update(self, value: float) -> bool:
- """Update with new value"""
- self._count += 1
- if self._count == 1:
- self._current = value
- else:
- self._current = (value - self._current) * self._multiplier + self._current
- if self._count >= self.period:
- self.is_ready = True
- return True
- return False
-
- @property
- def current(self) -> float:
- return self._current
-
-
-class BuyingPowerModelExtensions:
- """Extension methods for buying power models"""
-
- @staticmethod
- def get_leverage(security: Any) -> float:
- """Get leverage for a security"""
- if hasattr(security, 'leverage'):
- return security.leverage
- return 1.0
-
- @staticmethod
- def set_leverage(security: Any, leverage: float) -> None:
- """Set leverage for a security"""
- if hasattr(security, 'set_leverage'):
- security.set_leverage(leverage)
-
-
-class _BrokerageMarkets(dict):
- """Dict that supports both SecurityType enum and string keys for default_markets."""
- _STR_MAP = {
- 'equity': 1, 'option': 2, 'forex': 4, 'future': 5, 'crypto': 7,
- 'index': 6, 'index_option': 12, 'future_option': 13, 'cfd': 8,
- }
-
- def __getitem__(self, key):
- # Try direct lookup first
- try:
- return super().__getitem__(key)
- except KeyError:
- pass
- # Try by string name
- if isinstance(key, str):
- for k, v in super().items():
- if str(k).lower().replace('securitytype.', '') == key.lower():
- return v
- # Try by int value
- if isinstance(key, int):
- for k, v in super().items():
- if getattr(k, 'value', k) == key:
- return v
- raise KeyError(key)
-
- def __contains__(self, key):
- try:
- self[key]
- return True
- except KeyError:
- return False
-
-
-class DefaultBrokerageModel:
- """Default brokerage model implementation"""
-
- def __init__(self, account_type: int = 0):
- from .enums import AccountType, SecurityType, Market
- self.account_type = account_type
- # Support both string keys ('equity') and SecurityType enum keys
- self.default_markets = _BrokerageMarkets({
- SecurityType.EQUITY: Market.USA,
- SecurityType.OPTION: Market.USA,
- SecurityType.FUTURE: Market.CME,
- SecurityType.FOREX: Market.OANDA,
- SecurityType.CRYPTO: Market.BINANCE,
- SecurityType.INDEX: Market.USA,
- SecurityType.INDEX_OPTION: Market.USA,
- SecurityType.FUTURE_OPTION: Market.CME,
- SecurityType.CFD: Market.OANDA,
- })
-
- def get_leverage(self, security: Any) -> float:
- """Get default leverage for security type"""
- leverage_map = {
- 1: 2.0, # EQUITY
- 2: 1.0, # OPTION
- 4: 50.0, # FOREX
- 5: 1.0, # FUTURE
- 7: 1.0, # CRYPTO
- }
- sec_type = getattr(security, 'security_type', 1)
- return leverage_map.get(sec_type, 1.0)
-
- def can_submit_order(self, security: Any, order: Any) -> bool:
- """Check if order can be submitted"""
- return True
-
- def can_update_order(self, security: Any, order: Any) -> bool:
- """Check if order can be updated"""
- return True
-
-
-class RateOfChangePercent:
- """Rate of change percentage indicator"""
-
- def __init__(self, name_or_period=14, period=None):
- # Support both RateOfChangePercent(14) and RateOfChangePercent("name", 1)
- if isinstance(name_or_period, str):
- self.name = name_or_period
- self.period = period if period is not None else 14
- else:
- self.period = name_or_period
- self.name = f"ROCP({self.period})"
- self._values: List[float] = []
- self._current = 0.0
- self.is_ready = False
- self.updated = _WrapperEventHandler()
-
- def update(self, time: datetime, value: float) -> bool:
- """Update indicator with new value"""
- self._values.append(value)
- if len(self._values) > self.period + 1:
- self._values.pop(0)
-
- if len(self._values) > self.period:
- old_value = self._values[0]
- if old_value != 0:
- self._current = ((value - old_value) / old_value) * 100
- else:
- self._current = 0.0
- self.is_ready = True
- return True
- return False
-
- @property
- def current(self) -> float:
- return self._current
-
- @property
- def Current(self) -> Any:
- """LEAN-style property"""
- class Value:
- def __init__(self, val):
- self.Value = val
- return Value(self._current)
-
- def reset(self) -> None:
- """Reset indicator"""
- self._values.clear()
- self._current = 0.0
- self.is_ready = False
diff --git a/fincept-qt/scripts/strategies/fincept_engine/framework/__init__.py b/fincept-qt/scripts/strategies/fincept_engine/framework/__init__.py
deleted file mode 100644
index 4dbde6d50..000000000
--- a/fincept-qt/scripts/strategies/fincept_engine/framework/__init__.py
+++ /dev/null
@@ -1,20 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine Framework
-# LEAN-compatible framework models (Alpha, Portfolio, Execution, Risk, Selection)
-# ============================================================================
-
-from .alphas import (
- RsiAlphaModel, HistoricalReturnsAlphaModel, EmaCrossAlphaModel,
- MacdAlphaModel, PairsTradingAlphaModel, BasePairsTradingAlphaModel,
- PearsonCorrelationPairsTradingAlphaModel
-)
-from .portfolio_construction import (
- UnconstrainedMeanVariancePortfolioOptimizer
-)
-from .execution import (
- SpreadExecutionModel
-)
-from .selection import (
- OptionUniverseSelectionModel, FutureUniverseSelectionModel,
- ETFConstituentsUniverseSelectionModel, QC500UniverseSelectionModel
-)
diff --git a/fincept-qt/scripts/strategies/fincept_engine/framework/alphas.py b/fincept-qt/scripts/strategies/fincept_engine/framework/alphas.py
deleted file mode 100644
index ad6942eb5..000000000
--- a/fincept-qt/scripts/strategies/fincept_engine/framework/alphas.py
+++ /dev/null
@@ -1,49 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Alpha Models
-# Pre-built alpha models for the framework pipeline
-# ============================================================================
-
-from ..algorithm import AlphaModel, ConstantAlphaModel, CompositeAlphaModel
-
-
-class RsiAlphaModel(AlphaModel):
- """RSI-based alpha model."""
- def __init__(self, period=14, resolution=None):
- self._period = period
-
-
-class HistoricalReturnsAlphaModel(AlphaModel):
- """Historical returns alpha model."""
- def __init__(self, lookback=1, resolution=None):
- self._lookback = lookback
-
-
-class EmaCrossAlphaModel(AlphaModel):
- """EMA crossover alpha model."""
- def __init__(self, fast_period=12, slow_period=26, resolution=None):
- self._fast = fast_period
- self._slow = slow_period
-
-
-class MacdAlphaModel(AlphaModel):
- """MACD-based alpha model."""
- def __init__(self, fast_period=12, slow_period=26, signal_period=9, *args, **kwargs):
- pass
-
-
-class PairsTradingAlphaModel(AlphaModel):
- """Pairs trading alpha model."""
- def __init__(self, *args, **kwargs):
- pass
-
-
-class BasePairsTradingAlphaModel(AlphaModel):
- """Base class for pairs trading alpha models."""
- def __init__(self, *args, **kwargs):
- pass
-
-
-class PearsonCorrelationPairsTradingAlphaModel(AlphaModel):
- """Pearson correlation pairs trading alpha model."""
- def __init__(self, *args, **kwargs):
- pass
diff --git a/fincept-qt/scripts/strategies/fincept_engine/framework/execution.py b/fincept-qt/scripts/strategies/fincept_engine/framework/execution.py
deleted file mode 100644
index 53c3dc311..000000000
--- a/fincept-qt/scripts/strategies/fincept_engine/framework/execution.py
+++ /dev/null
@@ -1,19 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Execution Models
-# Order execution strategies for the framework pipeline
-# ============================================================================
-
-from ..algorithm import ExecutionModel
-
-
-class SpreadExecutionModel(ExecutionModel):
- """Spread-based execution model (stub)."""
- def __init__(self, accepting_spread_percent=0.005):
- self._spread = accepting_spread_percent
-
- def execute(self, algorithm, targets):
- for target in targets:
- existing = algorithm.portfolio[str(target.symbol)].quantity
- diff = target.quantity - existing
- if abs(diff) > 0:
- algorithm.market_order(target.symbol, diff)
diff --git a/fincept-qt/scripts/strategies/fincept_engine/framework/portfolio_construction.py b/fincept-qt/scripts/strategies/fincept_engine/framework/portfolio_construction.py
deleted file mode 100644
index da77c067e..000000000
--- a/fincept-qt/scripts/strategies/fincept_engine/framework/portfolio_construction.py
+++ /dev/null
@@ -1,14 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Portfolio Construction Models
-# Portfolio optimization and construction for the framework pipeline
-# ============================================================================
-
-
-class UnconstrainedMeanVariancePortfolioOptimizer:
- """Mean-variance optimizer (simplified stub)."""
- def __init__(self, *args, **kwargs):
- pass
-
- def optimize(self, returns, *args, **kwargs):
- n = len(returns) if returns is not None else 1
- return [1.0 / n] * n
diff --git a/fincept-qt/scripts/strategies/fincept_engine/framework/risk.py b/fincept-qt/scripts/strategies/fincept_engine/framework/risk.py
deleted file mode 100644
index de4479947..000000000
--- a/fincept-qt/scripts/strategies/fincept_engine/framework/risk.py
+++ /dev/null
@@ -1,16 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Risk Management Models
-# All core risk models are defined in algorithm.py.
-# This module re-exports them for organizational clarity.
-# ============================================================================
-
-from ..algorithm import (
- RiskManagementModel,
- NullRiskManagementModel,
- MaximumDrawdownPercentPortfolio,
- MaximumDrawdownPercentPerSecurity,
- MaximumUnrealizedProfitPercentPerSecurity,
- TrailingStopRiskManagementModel,
- MaximumSectorExposureRiskManagementModel,
- CompositeRiskManagementModel
-)
diff --git a/fincept-qt/scripts/strategies/fincept_engine/framework/selection.py b/fincept-qt/scripts/strategies/fincept_engine/framework/selection.py
deleted file mode 100644
index 10ee6edf5..000000000
--- a/fincept-qt/scripts/strategies/fincept_engine/framework/selection.py
+++ /dev/null
@@ -1,33 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Universe Selection Models
-# Dynamic security filtering and selection for the framework pipeline
-# ============================================================================
-
-from ..algorithm import (
- UniverseSelectionModel, FundamentalUniverseSelectionModel,
- ManualUniverseSelectionModel, ScheduledUniverseSelectionModel,
- CustomUniverseSelectionModel
-)
-
-
-class OptionUniverseSelectionModel(UniverseSelectionModel):
- """Option chain universe selection."""
- def __init__(self, *args, **kwargs):
- pass
-
-
-class FutureUniverseSelectionModel(UniverseSelectionModel):
- """Futures universe selection."""
- def __init__(self, *args, **kwargs):
- pass
-
-
-class ETFConstituentsUniverseSelectionModel(UniverseSelectionModel):
- """ETF constituents universe selection."""
- def __init__(self, *args, **kwargs):
- pass
-
-
-class QC500UniverseSelectionModel(FundamentalUniverseSelectionModel):
- """QC500 universe selection (top 500 by dollar volume)."""
- pass
diff --git a/fincept-qt/scripts/strategies/fincept_engine/indicators.py b/fincept-qt/scripts/strategies/fincept_engine/indicators.py
deleted file mode 100644
index f60c27876..000000000
--- a/fincept-qt/scripts/strategies/fincept_engine/indicators.py
+++ /dev/null
@@ -1,618 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine Indicators
-# Pure Python technical indicators (no C#/LEAN dependency)
-# ============================================================================
-
-from collections import deque
-from typing import Optional
-import math
-
-
-class _IndicatorEventHandler:
- """Supports += and -= for indicator event registration."""
- def __init__(self):
- self._handlers = []
- def __iadd__(self, handler):
- self._handlers.append(handler)
- return self
- def __isub__(self, handler):
- if handler in self._handlers:
- self._handlers.remove(handler)
- return self
- def __call__(self, *args, **kwargs):
- for h in self._handlers:
- h(*args, **kwargs)
-
-
-class _IndicatorWindow:
- """Rolling window for indicator values."""
- def __init__(self, size):
- self._size = size
- self._data = deque(maxlen=size)
- def __getitem__(self, index):
- return self._data[index] if index < len(self._data) else IndicatorDataPoint(0.0)
- def __len__(self):
- return len(self._data)
- @property
- def count(self):
- return len(self._data)
- @property
- def size(self):
- return self._size
- @size.setter
- def size(self, value):
- self._size = value
- self._data = deque(self._data, maxlen=value)
- @property
- def is_ready(self):
- return len(self._data) >= self._size
-
-
-class IndicatorDataPoint:
- """Single indicator value at a point in time."""
- def __init__(self, value: float = 0.0, time=None):
- self.value = value
- self.time = time
- self.window = _IndicatorWindow(1)
-
- @property
- def current(self):
- """Return self so that .current.value works on sub-band data points."""
- return self
-
- def __float__(self):
- return self.value
-
- def __repr__(self):
- return f"{self.value:.4f}"
-
-
-class IndicatorBase:
- """Base class for all indicators."""
-
- def __init__(self, name, period: int = None):
- # QuantConnect compat: if name is an int, treat it as period
- if isinstance(name, (int, float)) and period is None:
- period = int(name)
- name = type(self).__name__
- elif period is None:
- period = 14 # Default period
- self.name = str(name)
- self.period = period
- self.current = IndicatorDataPoint(0.0)
- self.previous = IndicatorDataPoint(0.0)
- self._samples = 0
- self._window = deque(maxlen=period)
- self.warm_up_period = period
- self._is_ready_override = False
- self.updated = _IndicatorEventHandler()
- self.window = _IndicatorWindow(period)
-
- @property
- def is_ready(self) -> bool:
- return self._is_ready_override or self._samples >= self.period
-
- @is_ready.setter
- def is_ready(self, value: bool):
- self._is_ready_override = value
-
- @property
- def samples(self) -> int:
- return self._samples
-
- def update(self, time_or_input, value: float = None) -> bool:
- # Support both update(time, value) and update(bar) patterns
- if value is not None:
- time = time_or_input
- val = float(value)
- elif isinstance(time_or_input, (int, float)):
- time = None
- val = float(time_or_input)
- elif hasattr(time_or_input, 'close'):
- # TradeBar / bar-like object
- time = getattr(time_or_input, 'time', getattr(time_or_input, 'end_time', None))
- val = float(time_or_input.close)
- elif hasattr(time_or_input, 'value'):
- time = getattr(time_or_input, 'time', None)
- val = float(time_or_input.value)
- elif hasattr(time_or_input, 'price'):
- time = getattr(time_or_input, 'time', None)
- val = float(time_or_input.price)
- else:
- time = None
- try:
- val = float(time_or_input)
- except (TypeError, ValueError):
- val = 0.0
- self.previous = IndicatorDataPoint(self.current.value, self.current.time)
- self._window.append(val)
- self._samples += 1
- result = self._compute(val)
- self.current = IndicatorDataPoint(result, time)
- return self.is_ready
-
- def _compute(self, value: float) -> float:
- raise NotImplementedError
-
- def reset(self):
- self._samples = 0
- self._window.clear()
- self.current = IndicatorDataPoint(0.0)
- self.previous = IndicatorDataPoint(0.0)
-
- def __float__(self):
- return self.current.value
-
- def __gt__(self, other):
- if isinstance(other, IndicatorBase):
- return self.current.value > other.current.value
- return self.current.value > float(other)
-
- def __lt__(self, other):
- if isinstance(other, IndicatorBase):
- return self.current.value < other.current.value
- return self.current.value < float(other)
-
- def __ge__(self, other):
- if isinstance(other, IndicatorBase):
- return self.current.value >= other.current.value
- return self.current.value >= float(other)
-
- def __le__(self, other):
- if isinstance(other, IndicatorBase):
- return self.current.value <= other.current.value
- return self.current.value <= float(other)
-
- def __sub__(self, other):
- if isinstance(other, IndicatorBase):
- return self.current.value - other.current.value
- return self.current.value - float(other)
-
- def __add__(self, other):
- if isinstance(other, IndicatorBase):
- return self.current.value + other.current.value
- return self.current.value + float(other)
-
- def __mul__(self, other):
- return self.current.value * float(other)
-
- def __truediv__(self, other):
- divisor = float(other)
- if divisor == 0:
- return 0
- return self.current.value / divisor
-
- def __repr__(self):
- return f"{self.name}({self.current.value:.4f})"
-
-
-class SimpleMovingAverage(IndicatorBase):
- """SMA indicator."""
-
- def __init__(self, name: str = "SMA", period: int = 14):
- super().__init__(name, period)
-
- def _compute(self, value: float) -> float:
- if len(self._window) == 0:
- return 0
- return sum(self._window) / len(self._window)
-
-
-class ExponentialMovingAverage(IndicatorBase):
- """EMA indicator."""
-
- def __init__(self, name: str = "EMA", period: int = 14, smoothing_factor: float = None):
- super().__init__(name, period)
- self._k = smoothing_factor or (2.0 / (period + 1))
- self._ema = None
-
- def _compute(self, value: float) -> float:
- if self._ema is None:
- self._ema = value
- else:
- self._ema = value * self._k + self._ema * (1 - self._k)
- return self._ema
-
- def reset(self):
- super().reset()
- self._ema = None
-
-
-class MovingAverageConvergenceDivergence(IndicatorBase):
- """MACD indicator with signal and histogram."""
-
- def __init__(self, name: str = "MACD", fast_period: int = 12,
- slow_period: int = 26, signal_period: int = 9):
- super().__init__(name, slow_period)
- self.fast = ExponentialMovingAverage("MACD_Fast", fast_period)
- self.slow = ExponentialMovingAverage("MACD_Slow", slow_period)
- self.signal = ExponentialMovingAverage("MACD_Signal", signal_period)
- self.histogram = IndicatorDataPoint(0.0)
- self.warm_up_period = slow_period + signal_period
-
- @property
- def is_ready(self) -> bool:
- return self.slow.is_ready
-
- def _compute(self, value: float) -> float:
- self.fast.update(None, value)
- self.slow.update(None, value)
- macd_val = self.fast.current.value - self.slow.current.value
- self.signal.update(None, macd_val)
- self.histogram = IndicatorDataPoint(macd_val - self.signal.current.value)
- return macd_val
-
- def reset(self):
- super().reset()
- self.fast.reset()
- self.slow.reset()
- self.signal.reset()
-
-
-class RelativeStrengthIndex(IndicatorBase):
- """RSI indicator."""
-
- def __init__(self, name: str = "RSI", period: int = 14, moving_average_type=None):
- super().__init__(name, period)
- self._avg_gain = 0
- self._avg_loss = 0
- self._prev_value = None
- self._gains = deque(maxlen=period)
- self._losses = deque(maxlen=period)
-
- def _compute(self, value: float) -> float:
- if self._prev_value is None:
- self._prev_value = value
- return 50.0
-
- change = value - self._prev_value
- self._prev_value = value
-
- gain = max(change, 0)
- loss = abs(min(change, 0))
- self._gains.append(gain)
- self._losses.append(loss)
-
- if len(self._gains) < self.period:
- return 50.0
-
- avg_gain = sum(self._gains) / len(self._gains)
- avg_loss = sum(self._losses) / len(self._losses)
-
- if avg_loss == 0:
- return 100.0
-
- rs = avg_gain / avg_loss
- return 100.0 - (100.0 / (1.0 + rs))
-
-
-class BollingerBands(IndicatorBase):
- """Bollinger Bands indicator."""
-
- def __init__(self, name: str = "BB", period: int = 20, k: float = 2.0):
- super().__init__(name, period)
- self._k = k
- self.middle_band = IndicatorDataPoint(0.0)
- self.upper_band = IndicatorDataPoint(0.0)
- self.lower_band = IndicatorDataPoint(0.0)
- self.band_width = IndicatorDataPoint(0.0)
- self.percent_b = IndicatorDataPoint(0.0)
- self.standard_deviation = IndicatorDataPoint(0.0)
-
- def _compute(self, value: float) -> float:
- if len(self._window) < 2:
- self.middle_band = IndicatorDataPoint(value)
- self.upper_band = IndicatorDataPoint(value)
- self.lower_band = IndicatorDataPoint(value)
- return value
-
- mean = sum(self._window) / len(self._window)
- variance = sum((x - mean) ** 2 for x in self._window) / len(self._window)
- std = math.sqrt(variance)
-
- self.middle_band = IndicatorDataPoint(mean)
- self.upper_band = IndicatorDataPoint(mean + self._k * std)
- self.lower_band = IndicatorDataPoint(mean - self._k * std)
- self.standard_deviation = IndicatorDataPoint(std)
-
- bw = self.upper_band.value - self.lower_band.value
- self.band_width = IndicatorDataPoint(bw / mean if mean != 0 else 0)
-
- if bw != 0:
- self.percent_b = IndicatorDataPoint((value - self.lower_band.value) / bw)
- else:
- self.percent_b = IndicatorDataPoint(0.5)
-
- return mean
-
-
-class AverageTrueRange(IndicatorBase):
- """ATR indicator."""
-
- def __init__(self, name: str = "ATR", period: int = 14):
- super().__init__(name, period)
- self._prev_close = None
- self._tr_values = deque(maxlen=period)
-
- def update(self, time_or_input, value: float = None) -> bool:
- # Support update(bar) where bar has high/low/close
- if value is None and hasattr(time_or_input, 'high') and hasattr(time_or_input, 'low') and hasattr(time_or_input, 'close'):
- bar = time_or_input
- return self.update_bar(
- getattr(bar, 'time', getattr(bar, 'end_time', None)),
- float(bar.high), float(bar.low), float(bar.close)
- )
- return super().update(time_or_input, value)
-
- def update_bar(self, time, high: float, low: float, close: float) -> bool:
- if self._prev_close is None:
- tr = high - low
- else:
- tr = max(high - low,
- abs(high - self._prev_close),
- abs(low - self._prev_close))
-
- self._prev_close = close
- self._tr_values.append(tr)
- self._samples += 1
-
- if len(self._tr_values) > 0:
- atr = sum(self._tr_values) / len(self._tr_values)
- else:
- atr = 0
-
- self.previous = IndicatorDataPoint(self.current.value, self.current.time)
- self.current = IndicatorDataPoint(atr, time)
- return self.is_ready
-
- def _compute(self, value: float) -> float:
- return self.current.value
-
-
-class Stochastic(IndicatorBase):
- """Stochastic oscillator."""
-
- def __init__(self, name: str = "STO", period: int = 14, k_period: int = 3, d_period: int = 3):
- super().__init__(name, period)
- self._highs = deque(maxlen=period)
- self._lows = deque(maxlen=period)
- self._k_values = deque(maxlen=k_period)
- self.fast_stoch = IndicatorDataPoint(0.0)
- self.stoch_k = IndicatorDataPoint(0.0)
- self.stoch_d = ExponentialMovingAverage("StochD", d_period)
- self.warm_up_period = period
- self._k_period = k_period
-
- @property
- def is_ready(self) -> bool:
- # Stochastic produces valid output once it has enough data in the window
- # LEAN's Stochastic is ready when all sub-components have data
- return self._is_ready_override or self._samples >= max(self._k_period, self.period - 1)
-
- @is_ready.setter
- def is_ready(self, value: bool):
- self._is_ready_override = value
-
- def update(self, time_or_input, value: float = None) -> bool:
- # Support update(bar) where bar has high/low/close
- if value is None and hasattr(time_or_input, 'high') and hasattr(time_or_input, 'low') and hasattr(time_or_input, 'close'):
- bar = time_or_input
- return self.update_bar(
- getattr(bar, 'time', getattr(bar, 'end_time', None)),
- float(bar.high), float(bar.low), float(bar.close)
- )
- return super().update(time_or_input, value)
-
- def update_bar(self, time, high: float, low: float, close: float) -> bool:
- self._highs.append(high)
- self._lows.append(low)
- self._samples += 1
-
- highest = max(self._highs)
- lowest = min(self._lows)
- range_val = highest - lowest
-
- if range_val > 0:
- k = ((close - lowest) / range_val) * 100
- else:
- k = 50.0
-
- self.fast_stoch = IndicatorDataPoint(k, time)
- self._k_values.append(k)
- k_avg = sum(self._k_values) / len(self._k_values)
- self.stoch_k = IndicatorDataPoint(k_avg, time)
- self.stoch_d.update(time, k_avg)
-
- self.current = self.stoch_k
- return self.is_ready
-
- def _compute(self, value: float) -> float:
- return self.current.value
-
-
-class RateOfChange(IndicatorBase):
- """Rate of Change indicator."""
-
- def __init__(self, name: str = "ROC", period: int = 14):
- super().__init__(name, period)
-
- def _compute(self, value: float) -> float:
- if len(self._window) < self.period:
- return 0
- old_value = self._window[0]
- if old_value == 0:
- return 0
- return ((value - old_value) / old_value) * 100
-
-
-class Momentum(IndicatorBase):
- """Momentum indicator."""
-
- def __init__(self, name: str = "MOM", period: int = 14):
- super().__init__(name, period)
-
- def _compute(self, value: float) -> float:
- if len(self._window) < self.period:
- return 0
- return value - self._window[0]
-
-
-class WilliamsPercentR(IndicatorBase):
- """Williams %R indicator."""
-
- def __init__(self, name: str = "WILLR", period: int = 14):
- super().__init__(name, period)
- self._highs = deque(maxlen=period)
- self._lows = deque(maxlen=period)
-
- def update(self, time_or_input, value: float = None) -> bool:
- if value is None and hasattr(time_or_input, 'high') and hasattr(time_or_input, 'low') and hasattr(time_or_input, 'close'):
- bar = time_or_input
- return self.update_bar(
- getattr(bar, 'time', getattr(bar, 'end_time', None)),
- float(bar.high), float(bar.low), float(bar.close)
- )
- return super().update(time_or_input, value)
-
- def update_bar(self, time, high: float, low: float, close: float) -> bool:
- self._highs.append(high)
- self._lows.append(low)
- self._samples += 1
-
- highest = max(self._highs)
- lowest = min(self._lows)
- range_val = highest - lowest
-
- if range_val > 0:
- wr = ((highest - close) / range_val) * -100
- else:
- wr = -50.0
-
- self.previous = IndicatorDataPoint(self.current.value, self.current.time)
- self.current = IndicatorDataPoint(wr, time)
- return self.is_ready
-
- def _compute(self, value: float) -> float:
- return self.current.value
-
-
-class CommodityChannelIndex(IndicatorBase):
- """CCI indicator."""
-
- def __init__(self, name: str = "CCI", period: int = 20):
- super().__init__(name, period)
- self._tp_values = deque(maxlen=period)
-
- def update(self, time_or_input, value: float = None) -> bool:
- if value is None and hasattr(time_or_input, 'high') and hasattr(time_or_input, 'low') and hasattr(time_or_input, 'close'):
- bar = time_or_input
- return self.update_bar(
- getattr(bar, 'time', getattr(bar, 'end_time', None)),
- float(bar.high), float(bar.low), float(bar.close)
- )
- return super().update(time_or_input, value)
-
- def update_bar(self, time, high: float, low: float, close: float) -> bool:
- tp = (high + low + close) / 3.0
- self._tp_values.append(tp)
- self._samples += 1
-
- if len(self._tp_values) < self.period:
- self.current = IndicatorDataPoint(0, time)
- return False
-
- mean_tp = sum(self._tp_values) / len(self._tp_values)
- mean_dev = sum(abs(x - mean_tp) for x in self._tp_values) / len(self._tp_values)
-
- if mean_dev > 0:
- cci = (tp - mean_tp) / (0.015 * mean_dev)
- else:
- cci = 0
-
- self.previous = IndicatorDataPoint(self.current.value, self.current.time)
- self.current = IndicatorDataPoint(cci, time)
- return self.is_ready
-
- def _compute(self, value: float) -> float:
- return self.current.value
-
-
-class AverageDirectionalIndex(IndicatorBase):
- """ADX indicator."""
-
- def __init__(self, name: str = "ADX", period: int = 14):
- super().__init__(name, period)
- self._prev_high = None
- self._prev_low = None
- self._prev_close = None
- self._plus_dm = deque(maxlen=period)
- self._minus_dm = deque(maxlen=period)
- self._tr = deque(maxlen=period)
- self._dx_values = deque(maxlen=period)
- self.positive_directional_index = IndicatorDataPoint(0.0)
- self.negative_directional_index = IndicatorDataPoint(0.0)
-
- def update(self, time_or_input, value: float = None) -> bool:
- if value is None and hasattr(time_or_input, 'high') and hasattr(time_or_input, 'low') and hasattr(time_or_input, 'close'):
- bar = time_or_input
- return self.update_bar(
- getattr(bar, 'time', getattr(bar, 'end_time', None)),
- float(bar.high), float(bar.low), float(bar.close)
- )
- return super().update(time_or_input, value)
-
- def update_bar(self, time, high: float, low: float, close: float) -> bool:
- if self._prev_high is None:
- self._prev_high = high
- self._prev_low = low
- self._prev_close = close
- self._samples += 1
- return False
-
- up_move = high - self._prev_high
- down_move = self._prev_low - low
-
- plus_dm = up_move if (up_move > down_move and up_move > 0) else 0
- minus_dm = down_move if (down_move > up_move and down_move > 0) else 0
-
- tr = max(high - low,
- abs(high - self._prev_close),
- abs(low - self._prev_close))
-
- self._plus_dm.append(plus_dm)
- self._minus_dm.append(minus_dm)
- self._tr.append(tr)
- self._samples += 1
-
- self._prev_high = high
- self._prev_low = low
- self._prev_close = close
-
- if len(self._tr) < self.period:
- return False
-
- atr = sum(self._tr) / len(self._tr)
- if atr == 0:
- return False
-
- plus_di = (sum(self._plus_dm) / len(self._plus_dm)) / atr * 100
- minus_di = (sum(self._minus_dm) / len(self._minus_dm)) / atr * 100
-
- self.positive_directional_index = IndicatorDataPoint(plus_di, time)
- self.negative_directional_index = IndicatorDataPoint(minus_di, time)
-
- di_sum = plus_di + minus_di
- if di_sum == 0:
- dx = 0
- else:
- dx = abs(plus_di - minus_di) / di_sum * 100
-
- self._dx_values.append(dx)
- adx = sum(self._dx_values) / len(self._dx_values)
-
- self.previous = IndicatorDataPoint(self.current.value, self.current.time)
- self.current = IndicatorDataPoint(adx, time)
- return self.is_ready
-
- def _compute(self, value: float) -> float:
- return self.current.value
diff --git a/fincept-qt/scripts/strategies/fincept_engine/portfolio.py b/fincept-qt/scripts/strategies/fincept_engine/portfolio.py
deleted file mode 100644
index 26cdba041..000000000
--- a/fincept-qt/scripts/strategies/fincept_engine/portfolio.py
+++ /dev/null
@@ -1,178 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine Portfolio Manager
-# Tracks holdings, cash, P&L, and portfolio metrics
-# ============================================================================
-
-from typing import Dict
-from .types import Symbol, SecurityHolding
-
-
-class SecurityPortfolioManager:
- """Manages portfolio holdings and cash. Dict-like access by ticker."""
-
- def __init__(self, initial_cash: float = 100000):
- self._holdings: Dict[str, SecurityHolding] = {}
- self._cash = initial_cash
- self._initial_cash = initial_cash
- self._total_fees = 0.0
- self._total_profit = 0.0
- self._margin_used = 0.0
-
- @property
- def cash(self) -> float:
- return self._cash
-
- @cash.setter
- def cash(self, value: float):
- self._cash = value
-
- @property
- def invested(self) -> bool:
- return any(h.invested for h in self._holdings.values())
-
- @property
- def total_holdings_value(self) -> float:
- return sum(h.holdings_value for h in self._holdings.values())
-
- @property
- def total_portfolio_value(self) -> float:
- return self._cash + self.total_holdings_value
-
- @property
- def total_unrealized_profit(self) -> float:
- return sum(h.unrealized_profit for h in self._holdings.values())
-
- @property
- def total_profit(self) -> float:
- return self._total_profit + self.total_unrealized_profit
-
- @property
- def total_fees(self) -> float:
- return self._total_fees
-
- @property
- def margin_remaining(self) -> float:
- return self._cash
-
- @property
- def total_margin_used(self) -> float:
- return self._margin_used
-
- def __getitem__(self, key) -> SecurityHolding:
- ticker = str(key).upper()
- if ticker not in self._holdings:
- self._holdings[ticker] = SecurityHolding(Symbol(ticker))
- return self._holdings[ticker]
-
- def __setitem__(self, key, value):
- self._holdings[str(key).upper()] = value
-
- def __contains__(self, key) -> bool:
- return str(key).upper() in self._holdings
-
- def __iter__(self):
- return iter(self._holdings.values())
-
- def keys(self):
- return self._holdings.keys()
-
- def values(self):
- return self._holdings.values()
-
- def items(self):
- return self._holdings.items()
-
- def set_cash(self, amount: float):
- self._cash = amount
- self._initial_cash = amount
-
- def process_fill(self, symbol: str, quantity: float, fill_price: float, fee: float = 0.0):
- """Process an order fill and update holdings."""
- ticker = symbol.upper()
- if ticker not in self._holdings:
- self._holdings[ticker] = SecurityHolding(Symbol(ticker))
-
- holding = self._holdings[ticker]
-
- # Closing or reducing position
- if holding.quantity != 0:
- if (holding.quantity > 0 and quantity < 0) or (holding.quantity < 0 and quantity > 0):
- close_qty = min(abs(quantity), abs(holding.quantity))
- if holding.quantity > 0:
- profit = close_qty * (fill_price - holding.average_price)
- else:
- profit = close_qty * (holding.average_price - fill_price)
- self._total_profit += profit
- holding._total_close_profit += profit
-
- # Update position
- old_qty = holding.quantity
- new_qty = old_qty + quantity
-
- if new_qty == 0:
- holding.average_price = 0
- elif (old_qty >= 0 and quantity > 0) or (old_qty <= 0 and quantity < 0):
- # Adding to position - weighted average
- total_cost = (abs(old_qty) * holding.average_price) + (abs(quantity) * fill_price)
- holding.average_price = total_cost / abs(new_qty) if new_qty != 0 else 0
- elif abs(new_qty) > 0 and ((old_qty > 0 and new_qty < 0) or (old_qty < 0 and new_qty > 0)):
- # Flipped sides
- holding.average_price = fill_price
-
- holding.quantity = new_qty
- holding.market_price = fill_price
-
- # Update cash
- cost = quantity * fill_price + fee
- self._cash -= cost
- self._total_fees += fee
-
- def update_market_prices(self, prices: Dict[str, float]):
- """Update market prices for all holdings."""
- for ticker, price in prices.items():
- ticker = ticker.upper()
- if ticker in self._holdings:
- self._holdings[ticker].update_market_price(price)
-
- def get_holdings_summary(self) -> dict:
- """Get summary of all positions."""
- return {
- ticker: {
- 'quantity': h.quantity,
- 'avg_price': h.average_price,
- 'market_price': h.market_price,
- 'unrealized_pnl': h.unrealized_profit,
- 'value': h.holdings_value
- }
- for ticker, h in self._holdings.items()
- if h.quantity != 0
- }
-
- def set_margin_call_model(self, *args, **kwargs):
- """Set margin call model (stub)."""
- pass
-
- def set_positions(self, positions):
- """Set positions (stub)."""
- pass
-
- # PascalCase aliases
- def SetMarginCallModel(self, *args, **kwargs):
- return self.set_margin_call_model(*args, **kwargs)
-
- def SetPositions(self, positions):
- return self.set_positions(positions)
-
- Cash = property(lambda self: self.cash)
- Invested = property(lambda self: self.invested)
- TotalHoldingsValue = property(lambda self: self.total_holdings_value)
- TotalPortfolioValue = property(lambda self: self.total_portfolio_value)
- TotalUnrealizedProfit = property(lambda self: self.total_unrealized_profit)
- TotalProfit = property(lambda self: self.total_profit)
- TotalFees = property(lambda self: self.total_fees)
- MarginRemaining = property(lambda self: self.margin_remaining)
-
- def __repr__(self):
- return (f"Portfolio(cash={self._cash:.2f}, "
- f"holdings_value={self.total_holdings_value:.2f}, "
- f"total={self.total_portfolio_value:.2f})")
diff --git a/fincept-qt/scripts/strategies/fincept_engine/scheduling.py b/fincept-qt/scripts/strategies/fincept_engine/scheduling.py
deleted file mode 100644
index e1c0f8ab6..000000000
--- a/fincept-qt/scripts/strategies/fincept_engine/scheduling.py
+++ /dev/null
@@ -1,187 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine Scheduling
-# Date rules, time rules, and scheduled events
-# ============================================================================
-
-from datetime import datetime, timedelta, time
-from typing import Callable, List, Optional
-
-
-class DateRules:
- """Rules for when scheduled events fire (date component)."""
-
- def __init__(self, algorithm=None):
- self._algorithm = algorithm
-
- def every_day(self, symbol=None):
- return DateRule("every_day", symbol)
-
- def every(self, *days):
- return DateRule("every", days=days)
-
- def month_start(self, days_offset: int = 0):
- return DateRule("month_start", days_offset=days_offset)
-
- def month_end(self, days_offset: int = 0):
- return DateRule("month_end", days_offset=days_offset)
-
- def week_start(self, days_offset: int = 0):
- return DateRule("week_start", days_offset=days_offset)
-
- def week_end(self, days_offset: int = 0):
- return DateRule("week_end", days_offset=days_offset)
-
- def on(self, year_or_date=None, month=None, day=None):
- if isinstance(year_or_date, datetime):
- return DateRule("on", date=year_or_date)
- elif year_or_date is not None and month is not None and day is not None:
- return DateRule("on", date=datetime(year_or_date, month, day))
- return DateRule("on", date=datetime.now())
-
- def today(self):
- return DateRule("today")
-
- def tomorrow(self):
- return DateRule("tomorrow")
-
- def year_start(self, days_offset: int = 0):
- return DateRule("year_start", days_offset=days_offset)
-
- def year_end(self, days_offset: int = 0):
- return DateRule("year_end", days_offset=days_offset)
-
-
-class DateRule:
- """A specific date rule."""
- def __init__(self, rule_type: str, symbol=None, days_offset: int = 0,
- date: datetime = None, days=None):
- self.rule_type = rule_type
- self.symbol = symbol
- self.days_offset = days_offset
- self.date = date
- self.days = days
-
- def matches(self, dt: datetime) -> bool:
- if self.rule_type == "every_day":
- return dt.weekday() < 5 # Mon-Fri
- elif self.rule_type == "month_start":
- return dt.day == 1 + self.days_offset
- elif self.rule_type == "month_end":
- next_month = dt.replace(day=28) + timedelta(days=4)
- last_day = (next_month - timedelta(days=next_month.day)).day
- return dt.day == last_day - self.days_offset
- elif self.rule_type == "week_start":
- return dt.weekday() == 0 + self.days_offset
- elif self.rule_type == "week_end":
- return dt.weekday() == 4 - self.days_offset
- elif self.rule_type == "on":
- return dt.date() == self.date.date()
- elif self.rule_type == "today":
- return dt.date() == datetime.now().date()
- return True
-
-
-class TimeRules:
- """Rules for when scheduled events fire (time component)."""
-
- def __init__(self, algorithm=None):
- self._algorithm = algorithm
-
- def at(self, hour: int, minute: int = 0, second_or_tz=0):
- # Third arg can be seconds (int) or timezone (ignored)
- sec = second_or_tz if isinstance(second_or_tz, int) else 0
- return TimeRule("at", time=time(hour, minute, sec))
-
- def after_market_open(self, symbol=None, minutes_after: float = 0):
- # Default market open: 9:30 AM
- open_time = time(9, 30)
- actual = datetime.combine(datetime.today(), open_time) + timedelta(minutes=minutes_after)
- return TimeRule("after_market_open", time=actual.time(), symbol=symbol)
-
- def before_market_close(self, symbol=None, minutes_before: float = 0):
- # Default market close: 4:00 PM
- close_time = time(16, 0)
- actual = datetime.combine(datetime.today(), close_time) - timedelta(minutes=minutes_before)
- return TimeRule("before_market_close", time=actual.time(), symbol=symbol)
-
- def every(self, interval: timedelta):
- return TimeRule("every", interval=interval)
-
- @property
- def midnight(self):
- return TimeRule("at", time=time(0, 0))
-
- @property
- def noon(self):
- return TimeRule("at", time=time(12, 0))
-
- @property
- def market_open(self):
- return TimeRule("at", time=time(9, 30))
-
- @property
- def market_close(self):
- return TimeRule("at", time=time(16, 0))
-
-
-class TimeRule:
- """A specific time rule."""
- def __init__(self, rule_type: str, time: time = None,
- interval: timedelta = None, symbol=None):
- self.rule_type = rule_type
- self.time = time
- self.interval = interval
- self.symbol = symbol
-
- def matches(self, dt: datetime) -> bool:
- if self.rule_type == "at":
- return dt.hour == self.time.hour and dt.minute == self.time.minute
- elif self.rule_type == "every" and self.interval:
- return True # Handled by scheduler
- return False
-
-
-class ScheduledEvent:
- """A scheduled event with date rule, time rule, and callback."""
- def __init__(self, name: str, date_rule: DateRule, time_rule: TimeRule,
- callback: Callable):
- self.name = name
- self.date_rule = date_rule
- self.time_rule = time_rule
- self.callback = callback
- self.enabled = True
-
- def should_fire(self, dt: datetime) -> bool:
- if not self.enabled:
- return False
- return self.date_rule.matches(dt) and self.time_rule.matches(dt)
-
-
-class ScheduleManager:
- """Manages scheduled events."""
-
- def __init__(self, algorithm=None):
- self._algorithm = algorithm
- self._events: List[ScheduledEvent] = []
- self.date_rules = DateRules(algorithm)
- self.time_rules = TimeRules(algorithm)
-
- def on(self, date_rule, time_rule, callback: Callable, name: str = None):
- """Register a scheduled event."""
- event_name = name or f"event_{len(self._events)}"
- event = ScheduledEvent(event_name, date_rule, time_rule, callback)
- self._events.append(event)
- return event
-
- def event(self, name: str, date_rule, time_rule, callback: Callable):
- return self.on(date_rule, time_rule, callback, name)
-
- def check_and_fire(self, dt: datetime):
- """Check all events and fire those that match."""
- for event in self._events:
- if event.should_fire(dt):
- event.callback()
-
- def remove(self, event: ScheduledEvent):
- if event in self._events:
- self._events.remove(event)
diff --git a/fincept-qt/scripts/strategies/fincept_engine/securities.py b/fincept-qt/scripts/strategies/fincept_engine/securities.py
deleted file mode 100644
index ea5d93348..000000000
--- a/fincept-qt/scripts/strategies/fincept_engine/securities.py
+++ /dev/null
@@ -1,372 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine Securities Manager
-# Manages subscribed securities and their properties
-# ============================================================================
-
-from typing import Dict, Optional
-from .enums import SecurityType, Resolution, Market
-from .types import Symbol
-
-
-class Security:
- """Represents a subscribed security."""
-
- def __init__(self, symbol: Symbol, resolution: Resolution = Resolution.MINUTE,
- leverage: float = 1.0):
- self.symbol = symbol
- self.resolution = resolution
- self.leverage = leverage
- self.price = 0.0
- self.close = 0.0
- self.open = 0.0
- self.high = 0.0
- self.low = 0.0
- self.volume = 0.0
- self.bid_price = 0.0
- self.ask_price = 0.0
- self.bid_size = 0.0
- self.ask_size = 0.0
- self.is_tradable = True
- self.is_delisted = False
- self.has_data = False
- self.exchange = Exchange()
- self.fee_model = None
- self.fill_model = None
- self.slippage_model = None
- self.margin_model = None
- self.buying_power_model = None
- self.volatility_model = None
- self.settlement_model = None
- self.data_filter = None
- self.price_variation_model = None
- self.margin_interest_rate_model = None
- self._custom_properties = {}
- self._option_chain_provider = None
- self.subscriptions = [] # List of subscription data configs
- self.holdings = SecurityHolding_(symbol)
- self.cache = _SecurityCache()
- self.data = _DynamicSecurityData()
- self.symbol_properties = SymbolProperties()
- self.quote_currency = QuoteCurrency()
- self.base_currency = QuoteCurrency()
- self.fundamentals = None
-
- def set_leverage(self, leverage: float):
- self.leverage = leverage
-
- def set_fee_model(self, model):
- self.fee_model = model
-
- def set_fill_model(self, model):
- self.fill_model = model
-
- def set_slippage_model(self, model):
- self.slippage_model = model
-
- def set_buying_power_model(self, model):
- self.buying_power_model = model
-
- def set_margin_model(self, model):
- self.margin_model = model
-
- def set_data_filter(self, data_filter):
- self.data_filter = data_filter
-
- def set_settlement_model(self, model):
- self.settlement_model = model
-
- def set_margin_interest_rate_model(self, model):
- self.margin_interest_rate_model = model
-
- def set_volatility_model(self, model):
- self.volatility_model = model
-
- def set_shortable_provider(self, provider):
- self._shortable_provider = provider
-
- def set_option_exercise_model(self, model):
- self._option_exercise_model = model
-
- def set_option_assignment_model(self, model):
- self._option_assignment_model = model
-
- def add(self, key, value):
- """Add custom property to security."""
- self._custom_properties[key] = value
-
- @property
- def key(self):
- """Security key for subscriptions."""
- return str(self.symbol)
-
- # PascalCase aliases
- def SetFilter(self, *args, **kwargs):
- return self.set_filter(*args, **kwargs)
-
- def SetLeverage(self, leverage):
- return self.set_leverage(leverage)
-
- def SetFeeModel(self, model):
- return self.set_fee_model(model)
-
- def SetFillModel(self, model):
- return self.set_fill_model(model)
-
- def SetSlippageModel(self, model):
- return self.set_slippage_model(model)
-
- def SetBuyingPowerModel(self, model):
- return self.set_buying_power_model(model)
-
- def SetVolatilityModel(self, model):
- return self.set_volatility_model(model)
-
- def set_filter(self, *args, **kwargs):
- """Set option/future chain filter. Accepts filter function or min/max params."""
- if args and callable(args[0]):
- self._filter_func = args[0]
- else:
- self._filter_func = None
- return self
-
- def set_data_normalization_mode(self, mode):
- """Set data normalization mode."""
- self._data_normalization_mode = mode
-
- @property
- def mapped(self):
- """Get mapped symbol (for continuous futures)."""
- return self.symbol
-
- @property
- def mappable(self):
- """Whether this security is mappable."""
- return True
-
- @property
- def settled_bar_count(self):
- return 0
-
- @property
- def local_time(self):
- from datetime import datetime
- return datetime.now()
-
- def update_price(self, price: float, open_: float = 0, high: float = 0,
- low: float = 0, volume: float = 0):
- self.price = price
- self.close = price
- if open_:
- self.open = open_
- if high:
- self.high = high
- if low:
- self.low = low
- if volume:
- self.volume = volume
- self.has_data = True
-
- def __getitem__(self, key):
- return self._custom_properties.get(key)
-
- def __setitem__(self, key, value):
- self._custom_properties[key] = value
-
- @property
- def Symbol(self):
- return self.symbol
-
- def __repr__(self):
- return f"Security({self.symbol}, price={self.price:.2f})"
-
-
-class Exchange:
- """Security exchange information."""
-
- # Exchange constants
- NSE = "NSE"
- BSE = "BSE"
- NYSE = "NYSE"
- NASDAQ = "NASDAQ"
- AMEX = "AMEX"
- CME = "CME"
- COMEX = "COMEX"
- NYMEX = "NYMEX"
- CBOT = "CBOT"
- ICE = "ICE"
- EUREX = "EUREX"
- LSE = "LSE"
- TSE = "TSE"
- HKEX = "HKEX"
- SGX = "SGX"
- ASX = "ASX"
-
- def __init__(self):
- self.exchange_open = True
- self.hours = ExchangeHours()
- self.time_zone = "America/New_York"
-
- @property
- def local_time(self):
- from datetime import datetime
- return datetime.now()
-
-
-class ExchangeHours:
- """Exchange trading hours."""
- def __init__(self):
- self.is_open = True
- self.regular_market_duration = None
-
- @staticmethod
- def always_open(time_zone=None):
- """Return exchange hours that are always open."""
- eh = ExchangeHours()
- eh.is_open = True
- return eh
-
- AlwaysOpen = always_open
-
- def is_date_open(self, date) -> bool:
- return True
-
- def get_next_market_open(self, time, extended_market=False):
- return time
-
- def get_next_market_close(self, time, extended_market=False):
- from datetime import timedelta
- return time + timedelta(hours=6, minutes=30)
-
-
-class SecurityManager:
- """Manages all subscribed securities. Dict-like access by ticker."""
-
- def __init__(self):
- self._securities: Dict[str, Security] = {}
-
- def __getitem__(self, key) -> Security:
- ticker = str(key).upper()
- if ticker not in self._securities:
- sym = Symbol(ticker)
- self._securities[ticker] = Security(sym)
- return self._securities[ticker]
-
- def __setitem__(self, key, value):
- self._securities[str(key).upper()] = value
-
- def __contains__(self, key) -> bool:
- return str(key).upper() in self._securities
-
- def __iter__(self):
- return iter(self._securities.values())
-
- def __len__(self):
- return len(self._securities)
-
- def keys(self):
- return self._securities.keys()
-
- def values(self):
- return self._securities.values()
-
- def items(self):
- return self._securities.items()
-
- def add(self, symbol: Symbol, resolution: Resolution = Resolution.MINUTE,
- leverage: float = 1.0) -> Security:
- ticker = str(symbol).upper()
- sec = Security(symbol, resolution, leverage)
- self._securities[ticker] = sec
- return sec
-
- def remove(self, symbol) -> bool:
- ticker = str(symbol).upper()
- if ticker in self._securities:
- del self._securities[ticker]
- return True
- return False
-
- def get(self, key, default=None):
- return self._securities.get(str(key).upper(), default)
-
-
-class SecurityHolding_:
- """Lightweight holdings tracker on Security object."""
- def __init__(self, symbol):
- self.symbol = symbol
- self.quantity = 0
- self.average_price = 0.0
- self.invested = False
- self.is_long = False
- self.is_short = False
- self.unrealized_profit = 0.0
- self.unrealized_profit_percent = 0.0
-
-
-class SymbolProperties:
- """Symbol properties like lot size, minimum price variation."""
- def __init__(self, description="", quote_currency="USD", contract_multiplier=1.0,
- minimum_price_variation=0.01, lot_size=1, market_ticker=None):
- self.description = description
- self.quote_currency_symbol = quote_currency
- self.contract_multiplier = contract_multiplier
- self.minimum_price_variation = minimum_price_variation
- self.lot_size = lot_size
- self.market_ticker = market_ticker or ""
- self.minimum_order_size = 1
- self.priceMagnifier = 1
-
-
-class _SecurityCache:
- """Security data cache."""
- def __init__(self):
- self._data = {}
- def add_data(self, data):
- pass
- def add_data_list(self, data_list, data_type=None, from_subscription=False):
- if data_type is not None:
- self._data[data_type] = list(data_list) if data_list else []
- def get_data(self):
- return self._data
-
-
-class _DynamicSecurityData:
- """Dynamic security data providing access to custom data types."""
- def __init__(self):
- self._store = {}
- def get(self, data_type=None):
- if data_type and data_type in self._store:
- items = self._store[data_type]
- return items[-1] if items else None
- return None
- def get_all(self, data_type=None):
- if data_type and data_type in self._store:
- return self._store[data_type]
- return []
- def has_data(self, data_type=None):
- if data_type:
- return data_type in self._store and len(self._store[data_type]) > 0
- return len(self._store) > 0
- def __getattr__(self, name):
- if name.startswith('_'):
- raise AttributeError(name)
- return None
-
- # PascalCase aliases
- Get = get
- GetAll = get_all
- HasData = has_data
-
-
-class QuoteCurrency:
- """Quote currency info for a security."""
- def __init__(self):
- self.symbol = "USD"
- self.conversion_rate = 1.0
- self.amount = 0.0
-
- def set_amount(self, amount):
- self.amount = amount
-
- def SetAmount(self, amount):
- self.amount = amount
diff --git a/fincept-qt/scripts/strategies/fincept_engine/types.py b/fincept-qt/scripts/strategies/fincept_engine/types.py
deleted file mode 100644
index e45690767..000000000
--- a/fincept-qt/scripts/strategies/fincept_engine/types.py
+++ /dev/null
@@ -1,428 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine Types
-# Core data types: Symbol, Slice, TradeBar, Holdings, Orders, Insights
-# ============================================================================
-
-from datetime import datetime, timedelta
-from typing import Optional, Dict, List, Any
-from .enums import SecurityType, OrderType, OrderStatus, InsightDirection, InsightType, Market
-
-
-class IndicatorValue:
- """Wrapper for indicator current value."""
- def __init__(self, value: float = 0.0):
- self.value = value
-
- def __float__(self):
- return self.value
-
- def __repr__(self):
- return f"IndicatorValue({self.value})"
-
-
-class Symbol:
- """Represents a security identifier."""
-
- def __init__(self, ticker: str, security_type: SecurityType = SecurityType.EQUITY,
- market: str = Market.USA):
- self.value = ticker.upper()
- self.id = ticker.upper()
- self.security_type = security_type
- self.market = market
- # Stub industry-standard identifiers (non-empty for compatibility)
- self.cusip = f"{ticker.upper()[:6]:0<9}"[:9]
- self.sedol = f"{ticker.upper()[:5]:0<7}"[:7]
- self.isin = f"US{ticker.upper()[:6]:0<10}"[:12]
- self.figi = f"BBG{ticker.upper()[:6]:0<9}"[:12]
- self.composite_figi = f"BBG{ticker.upper()[:6]:0<9}"[:12]
- self.cik = abs(hash(ticker.upper())) % 9999999 + 1000000
-
- def __str__(self):
- return self.value
-
- def __repr__(self):
- return f"Symbol({self.value})"
-
- def __eq__(self, other):
- if isinstance(other, Symbol):
- return self.value == other.value
- if isinstance(other, str):
- return self.value == other.upper()
- return False
-
- def __hash__(self):
- return hash(self.value)
-
- def upper(self):
- """Allow Symbol to be used where string.upper() is called."""
- return self.value
-
- @staticmethod
- def create(ticker: str, security_type: SecurityType = SecurityType.EQUITY,
- market: str = Market.USA, *args, **kwargs):
- return Symbol(ticker, security_type, market)
-
- @staticmethod
- def create_future(ticker: str, market: str = "cme", *args, **kwargs):
- """Create a future symbol. Args: ticker, market, [expiry datetime]."""
- sym = Symbol(ticker.upper(), SecurityType.FUTURE, market)
- # Optional expiry datetime
- for a in args:
- if isinstance(a, datetime):
- sym.expiry = a
- break
- return sym
-
- @staticmethod
- def create_option(underlying, market: str = "usa", *args, **kwargs):
- """Create option symbol. Signature: (underlying, market, style, right, strike, expiry).
- underlying can be a string or Symbol."""
- from .enums import OptionRight as _OR
- underlying_sym = underlying if isinstance(underlying, Symbol) else Symbol(str(underlying).upper())
- underlying_ticker = str(underlying_sym).upper()
- # Parse positional args: style, right, strike, expiry
- style = args[0] if len(args) > 0 else 0 # AMERICAN=0
- right = args[1] if len(args) > 1 else _OR.CALL
- strike = args[2] if len(args) > 2 else 0
- expiry = args[3] if len(args) > 3 else None
-
- # Determine security type based on underlying
- sec_type = SecurityType.OPTION
- if underlying_sym.security_type == SecurityType.FUTURE:
- sec_type = SecurityType.FUTURE_OPTION
- elif underlying_sym.security_type == SecurityType.INDEX:
- sec_type = SecurityType.INDEX_OPTION
-
- # Generate a consistent ticker for the option
- right_char = 'C' if (hasattr(right, 'value') and right.value == 0) or right == 0 else 'P'
- if expiry:
- ticker_val = f"{underlying_ticker}{expiry.strftime('%y%m%d')}{right_char}{int(strike)}"
- else:
- ticker_val = f"{underlying_ticker}{right_char}{int(strike)}"
-
- sym = Symbol(ticker_val, sec_type, market)
- sym._underlying = underlying_sym
- sym.strike_price = float(strike)
- sym.right = right
- sym.expiry = expiry
- sym.option_style = style
- sym.id = type('SymbolId', (), {
- 'strike_price': float(strike), 'option_right': right,
- 'date': expiry, 'expiration': expiry,
- 'underlying': underlying_sym
- })()
- return sym
-
- @staticmethod
- def create_canonical_option(underlying, market: str = "usa", alias=None):
- ticker = str(underlying).upper()
- return Symbol(ticker, SecurityType.OPTION, market)
-
- @property
- def underlying(self):
- """Get underlying symbol (for options/futures)."""
- return getattr(self, '_underlying', self)
-
- @underlying.setter
- def underlying(self, value):
- self._underlying = value
-
- @property
- def has_underlying(self):
- """Check if this symbol has an underlying. True for options/derivatives or if explicitly set."""
- if hasattr(self, '_underlying') and self._underlying is not self:
- return True
- return self.security_type in (SecurityType.OPTION, SecurityType.FUTURE_OPTION,
- SecurityType.INDEX_OPTION)
-
- @property
- def is_canonical(self):
- return not hasattr(self, 'strike_price') or not hasattr(self, 'expiry')
-
-
-class TradeBar:
- """OHLCV bar data."""
-
- def __init__(self, time: datetime = None, symbol: Symbol = None,
- open: float = 0, high: float = 0, low: float = 0,
- close: float = 0, volume: float = 0):
- self.time = time or datetime.now()
- self.symbol = symbol
- self.open = open
- self.high = high
- self.low = low
- self.close = close
- self.volume = volume
- self.end_time = self.time
- self.value = close
- self.price = close
- self.period = timedelta(minutes=1)
-
- def __repr__(self):
- return f"TradeBar({self.symbol} O:{self.open} H:{self.high} L:{self.low} C:{self.close} V:{self.volume})"
-
-
-class QuoteBar:
- """Quote (bid/ask) bar data."""
-
- def __init__(self, time: datetime = None, symbol: Symbol = None,
- bid_open: float = 0, bid_high: float = 0,
- bid_low: float = 0, bid_close: float = 0,
- ask_open: float = 0, ask_high: float = 0,
- ask_low: float = 0, ask_close: float = 0,
- last_bid_size: float = 0, last_ask_size: float = 0):
- self.time = time or datetime.now()
- self.symbol = symbol
- self.bid = TradeBar(time, symbol, bid_open, bid_high, bid_low, bid_close)
- self.ask = TradeBar(time, symbol, ask_open, ask_high, ask_low, ask_close)
- self.last_bid_size = last_bid_size
- self.last_ask_size = last_ask_size
- self.value = (bid_close + ask_close) / 2 if (bid_close + ask_close) else 0
- self.price = self.value
- self.close = self.value
-
-
-class Tick:
- """Single tick data point."""
-
- def __init__(self, time: datetime = None, symbol: Symbol = None,
- bid_price: float = 0, ask_price: float = 0,
- last_price: float = 0, quantity: float = 0):
- self.time = time or datetime.now()
- self.symbol = symbol
- self.bid_price = bid_price
- self.ask_price = ask_price
- self.last_price = last_price
- self.value = last_price
- self.price = last_price
- self.quantity = quantity
-
-
-class Slice:
- """Time-sliced data container. Keyed by symbol."""
-
- def __init__(self, time: datetime = None):
- self.time = time or datetime.now()
- self._data: Dict[str, TradeBar] = {}
- self.bars = self._data
- self.quote_bars: Dict[str, QuoteBar] = {}
- self.ticks: Dict[str, List[Tick]] = {}
- self.has_data = False
- self.keys = []
- self.values = []
-
- def __getitem__(self, symbol):
- key = str(symbol).upper()
- return self._data.get(key)
-
- def __contains__(self, symbol):
- key = str(symbol).upper()
- return key in self._data
-
- def contains_key(self, symbol) -> bool:
- return str(symbol).upper() in self._data
-
- def get(self, symbol_type, default=None):
- return self._data
-
- def add(self, symbol: str, bar: TradeBar):
- key = symbol.upper()
- self._data[key] = bar
- self.has_data = True
- self.keys = list(self._data.keys())
- self.values = list(self._data.values())
-
-
-class SecurityHolding:
- """Tracks holdings for a single security."""
-
- def __init__(self, symbol: Symbol, quantity: float = 0,
- average_price: float = 0, market_price: float = 0):
- self.symbol = symbol
- self.quantity = quantity
- self.average_price = average_price
- self.market_price = market_price
-
- @property
- def invested(self) -> bool:
- return self.quantity != 0
-
- @property
- def is_long(self) -> bool:
- return self.quantity > 0
-
- @property
- def is_short(self) -> bool:
- return self.quantity < 0
-
- @property
- def holdings_value(self) -> float:
- return self.quantity * self.market_price
-
- @property
- def unrealized_profit(self) -> float:
- return self.quantity * (self.market_price - self.average_price)
-
- @property
- def unrealized_profit_percent(self) -> float:
- if self.average_price == 0:
- return 0
- return (self.market_price - self.average_price) / self.average_price
-
- @property
- def absolute_quantity(self) -> float:
- return abs(self.quantity)
-
- @property
- def total_close_profit(self) -> float:
- return self._total_close_profit
-
- def __init__(self, symbol: Symbol, quantity: float = 0,
- average_price: float = 0, market_price: float = 0):
- self.symbol = symbol
- self.quantity = quantity
- self.average_price = average_price
- self.market_price = market_price
- self._total_close_profit = 0.0
-
- def update_market_price(self, price: float):
- self.market_price = price
-
- def __repr__(self):
- return f"Holding({self.symbol}: qty={self.quantity}, avg={self.average_price:.2f}, mkt={self.market_price:.2f})"
-
-
-class OrderTicket:
- """Represents a submitted order."""
-
- def __init__(self, order_id: int, symbol: Symbol, quantity: float,
- order_type: OrderType = OrderType.MARKET,
- limit_price: float = 0, stop_price: float = 0,
- tag: str = ""):
- self.order_id = order_id
- self.symbol = symbol
- self.quantity = quantity
- self.order_type = order_type
- self.limit_price = limit_price
- self.stop_price = stop_price
- self.tag = tag
- self.status = OrderStatus.SUBMITTED
- self.average_fill_price = 0.0
- self.quantity_filled = 0.0
- self.time = datetime.now()
- self.submit_request = self
-
- def update(self, fields):
- """Update order fields."""
- if hasattr(fields, 'limit_price') and fields.limit_price:
- self.limit_price = fields.limit_price
- if hasattr(fields, 'stop_price') and fields.stop_price:
- self.stop_price = fields.stop_price
- if hasattr(fields, 'quantity') and fields.quantity:
- self.quantity = fields.quantity
- if hasattr(fields, 'tag') and fields.tag:
- self.tag = fields.tag
-
- def cancel(self, tag: str = ""):
- self.status = OrderStatus.CANCELED
- self.tag = tag
-
- def get(self, field, default=None):
- return getattr(self, field, default)
-
- def __repr__(self):
- return f"OrderTicket(id={self.order_id}, {self.symbol}, qty={self.quantity}, status={self.status.name})"
-
-
-class UpdateOrderFields:
- """Fields for updating an existing order."""
- def __init__(self):
- self.limit_price = None
- self.stop_price = None
- self.quantity = None
- self.tag = None
-
-
-class OrderEvent:
- """Event fired when an order's status changes."""
-
- def __init__(self, order_id: int, symbol: Symbol, status: OrderStatus,
- fill_price: float = 0, fill_quantity: float = 0,
- direction: int = 0, message: str = ""):
- self.order_id = order_id
- self.symbol = symbol
- self.status = status
- self.fill_price = fill_price
- self.fill_quantity = fill_quantity
- self.direction = direction
- self.message = message
- self.utc_time = datetime.utcnow()
- self.is_assignment = False
-
- @property
- def absolute_fill_quantity(self):
- return abs(self.fill_quantity)
-
-
-class Insight:
- """Alpha model signal."""
-
- def __init__(self, symbol, period: timedelta, insight_type: InsightType = InsightType.PRICE,
- direction: InsightDirection = InsightDirection.FLAT,
- magnitude: float = None, confidence: float = None,
- source_model: str = "", weight: float = None):
- self.symbol = symbol
- self.period = period
- self.type = insight_type
- self.direction = direction
- self.magnitude = magnitude
- self.confidence = confidence
- self.source_model = source_model
- self.weight = weight
- self.generated_time_utc = datetime.utcnow()
- self.close_time_utc = self.generated_time_utc + period
- self.score = InsightScore()
- self.tag = ""
-
- @staticmethod
- def price(symbol, period, direction, magnitude=None, confidence=None,
- source_model="", weight=None):
- if isinstance(period, (int, float)):
- period = timedelta(days=period)
- return Insight(symbol, period, InsightType.PRICE, direction,
- magnitude, confidence, source_model, weight)
-
- @staticmethod
- def group(insights):
- return insights
-
-
-class InsightScore:
- """Score for an insight."""
- def __init__(self):
- self.direction = 0.0
- self.magnitude = 0.0
- self.final_score = 0.0
- self.is_final_score = False
-
-
-class PortfolioTarget:
- """Target portfolio allocation."""
-
- def __init__(self, symbol, quantity: float, tag: str = ""):
- self.symbol = symbol
- self.quantity = quantity
- self.tag = tag
-
- @staticmethod
- def percent(algorithm, symbol, percent: float, return_delta_quantity: bool = False, tag: str = ""):
- portfolio_value = algorithm.portfolio.total_portfolio_value
- price = algorithm.securities[str(symbol)].price if str(symbol) in algorithm.securities else 0
- if price == 0:
- return PortfolioTarget(symbol, 0, tag)
- target_value = portfolio_value * percent
- target_qty = int(target_value / price)
- return PortfolioTarget(symbol, target_qty, tag)
-
- def __repr__(self):
- return f"PortfolioTarget({self.symbol}, {self.quantity})"
diff --git a/fincept-qt/scripts/strategies/fincept_engine/universe.py b/fincept-qt/scripts/strategies/fincept_engine/universe.py
deleted file mode 100644
index 9acbcc301..000000000
--- a/fincept-qt/scripts/strategies/fincept_engine/universe.py
+++ /dev/null
@@ -1,220 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine Universe Selection
-# Dynamic security filtering and selection
-# ============================================================================
-
-from typing import List, Callable, Optional
-from .enums import Resolution, SecurityType, Market
-from .types import Symbol
-
-
-class _ScheduleSettings:
- """Schedule settings for universe."""
- def __init__(self):
- self._on_rule = None
- self._at_rule = None
- def on(self, date_rule=None):
- """Set date rule for scheduled universe selection."""
- self._on_rule = date_rule
- return self
- def at(self, time_rule=None):
- """Set time rule for scheduled universe selection."""
- self._at_rule = time_rule
- return self
-
-class _ETFSettings:
- """ETF universe settings."""
- _is_etf = True
- def __init__(self):
- self.symbol = None
- self._filter_func = None
- def __call__(self, *args, **kwargs):
- # Called as self.universe.etf(spy, universe_settings, filter_func)
- for a in args:
- if isinstance(a, Symbol):
- self.symbol = a
- elif callable(a) and not isinstance(a, type) and not isinstance(a, UniverseSettings):
- self._filter_func = a
- return self
-
-class _QC500Settings:
- """QC500 universe settings."""
- def __init__(self):
- pass
- def __call__(self, *args, **kwargs):
- return self
-
-class _TopSettings:
- """Top N universe settings."""
- def __init__(self):
- pass
- def __call__(self, *args, **kwargs):
- return self
-
-class UniverseSettings:
- """Settings for universe subscriptions."""
-
- def __init__(self, *args):
- self.resolution = Resolution.MINUTE
- self.leverage = 1.0
- self.fill_forward = True
- self.extended_market_hours = False
- self.minimum_time_in_universe = None
- self.data_normalization_mode = 0
- self.asynchronous = False
- self.schedule = _ScheduleSettings()
- self.etf = _ETFSettings()
- self.qc_500 = _QC500Settings()
- self.top = _TopSettings()
-
-
-class CoarseFundamental:
- """Coarse fundamental data for universe selection."""
-
- def __init__(self, symbol: Symbol, dollar_volume: float = 0,
- price: float = 0, volume: float = 0,
- has_fundamental_data: bool = False):
- self.symbol = symbol
- self.dollar_volume = dollar_volume
- self.price = price
- self.volume = volume
- self.has_fundamental_data = has_fundamental_data
- self.market = symbol.market if symbol else Market.USA
- self.value = price
-
-
-class FineFundamental:
- """Fine fundamental data for universe selection."""
-
- def __init__(self, symbol: Symbol):
- self.symbol = symbol
- self.company_reference = CompanyReference()
- self.security_reference = SecurityReference()
- self.financial_statements = FinancialStatements()
- self.earning_reports = EarningReports()
- self.operation_ratios = OperationRatios()
- self.earning_ratios = EarningRatios()
- self.valuation_ratios = ValuationRatios()
- self.asset_classification = AssetClassification()
- self.market_cap = 0
-
-
-class CompanyReference:
- def __init__(self):
- self.industry_template_code = ""
- self.primary_exchange_id = ""
- self.country_id = ""
-
-
-class SecurityReference:
- def __init__(self):
- self.security_type = ""
- self.listing_exchange = ""
- self.ipo_date = None
-
-
-class FinancialStatements:
- def __init__(self):
- self.income_statement = IncomeStatement()
- self.balance_sheet = BalanceSheet()
- self.cash_flow_statement = CashFlowStatement()
-
-
-class IncomeStatement:
- def __init__(self):
- self.total_revenue = FinancialValue()
- self.net_income = FinancialValue()
- self.ebit = FinancialValue()
- self.ebitda = FinancialValue()
- self.gross_profit = FinancialValue()
-
-
-class BalanceSheet:
- def __init__(self):
- self.total_assets = FinancialValue()
- self.total_debt = FinancialValue()
- self.stockholders_equity = FinancialValue()
- self.current_assets = FinancialValue()
- self.current_liabilities = FinancialValue()
- self.working_capital = FinancialValue()
-
-
-class CashFlowStatement:
- def __init__(self):
- self.free_cash_flow = FinancialValue()
- self.operating_cash_flow = FinancialValue()
-
-
-class FinancialValue:
- def __init__(self, value: float = 0):
- self.value = value
- self.three_months = value
- self.six_months = value
- self.twelve_months = value
-
- def __float__(self):
- return self.value
-
-
-class EarningReports:
- def __init__(self):
- self.basic_eps = FinancialValue()
- self.diluted_eps = FinancialValue()
- self.basic_average_shares = FinancialValue()
-
-
-class OperationRatios:
- def __init__(self):
- self.roe = FinancialValue()
- self.roa = FinancialValue()
- self.revenue_growth = FinancialValue()
- self.net_margin = FinancialValue()
- self.operating_margin = FinancialValue()
- self.gross_margin = FinancialValue()
-
-
-class EarningRatios:
- def __init__(self):
- self.equity_per_share_growth = FinancialValue()
- self.diluted_eps_growth = FinancialValue()
-
-
-class ValuationRatios:
- def __init__(self):
- self.pe_ratio = 0
- self.pb_ratio = 0
- self.ps_ratio = 0
- self.pcf_ratio = 0
- self.forward_pe = 0
- self.peg_ratio = 0
- self.dividend_yield = 0
- self.earnings_yield = 0
- self.book_value_per_share = 0
- self.sales_per_share = 0
- self.ev_to_ebitda = 0
-
-
-class AssetClassification:
- def __init__(self):
- self.morningstar_sector_code = 0
- self.morningstar_industry_group_code = 0
- self.morningstar_industry_code = 0
- self.style_box = 0
- self.growth_grade = ""
- self.profitability_grade = ""
- self.financial_health_grade = ""
- self.stock_type = 0
-
-
-class Universe:
- """Base universe class."""
-
- UNCHANGED = "unchanged"
-
- def __init__(self):
- self.members = {}
- self.settings = UniverseSettings()
-
- @staticmethod
- def unchanged():
- return Universe.UNCHANGED
diff --git a/fincept-qt/scripts/strategies/live_runner.py b/fincept-qt/scripts/strategies/live_runner.py
deleted file mode 100644
index 74f39f126..000000000
--- a/fincept-qt/scripts/strategies/live_runner.py
+++ /dev/null
@@ -1,757 +0,0 @@
-#!/usr/bin/env python3
-"""
-Fincept Terminal - Live Strategy Runner
-Manages strategy deployment for paper/live trading with SQLite persistence.
-All state is stored in SQLite only - no in-memory state in the host.
-
-Price data comes from the main app's strategy_price_cache table (written by
-the WebSocket router on every tick). Falls back to yfinance if no cached price.
-
-Commands:
- deploy <deploy_id> <strategy_id> <params_json> --db <path> --strategies-dir <path> --app-db <path>
- stop <deploy_id> --db <path>
- stop_all <asset_type> --db <path>
- list <asset_type> --db <path>
- check_duplicate <strategy_id> <symbol> --db <path>
- update <deploy_id> <params_json> --db <path>
-"""
-
-import sys
-import os
-import json
-import sqlite3
-import time
-import signal
-from datetime import datetime, timezone
-
-# ============================================================================
-# SQLite Schema & DB Helpers
-# ============================================================================
-
-SCHEMA = """
-CREATE TABLE IF NOT EXISTS deployed_strategies (
- deploy_id TEXT PRIMARY KEY,
- strategy_id TEXT NOT NULL,
- strategy_name TEXT NOT NULL,
- symbol TEXT NOT NULL,
- asset_type TEXT NOT NULL DEFAULT 'equity',
- mode TEXT NOT NULL DEFAULT 'paper',
- status TEXT NOT NULL DEFAULT 'starting',
- params TEXT,
- created_at TEXT NOT NULL,
- updated_at TEXT NOT NULL,
- stopped_at TEXT,
- pid INTEGER
-);
-
-CREATE TABLE IF NOT EXISTS strategy_trades (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- deploy_id TEXT NOT NULL,
- symbol TEXT NOT NULL,
- side TEXT NOT NULL,
- quantity REAL NOT NULL,
- price REAL NOT NULL,
- timestamp TEXT NOT NULL,
- order_id TEXT,
- pnl REAL DEFAULT 0,
- FOREIGN KEY (deploy_id) REFERENCES deployed_strategies(deploy_id)
-);
-
-CREATE TABLE IF NOT EXISTS strategy_metrics (
- deploy_id TEXT PRIMARY KEY,
- total_pnl REAL DEFAULT 0,
- total_trades INTEGER DEFAULT 0,
- win_rate REAL DEFAULT 0,
- max_drawdown REAL DEFAULT 0,
- sharpe_ratio REAL DEFAULT 0,
- current_position_qty REAL DEFAULT 0,
- current_position_side TEXT DEFAULT '',
- current_position_entry REAL DEFAULT 0,
- updated_at TEXT NOT NULL,
- FOREIGN KEY (deploy_id) REFERENCES deployed_strategies(deploy_id)
-);
-"""
-
-
-def get_db(db_path: str) -> sqlite3.Connection:
- """Open SQLite connection and ensure schema exists."""
- conn = sqlite3.connect(db_path)
- conn.row_factory = sqlite3.Row
- conn.executescript(SCHEMA)
- return conn
-
-
-# ============================================================================
-# Deploy Command - Main strategy execution loop
-# ============================================================================
-
-def cmd_deploy(deploy_id: str, strategy_id: str, params_json: str, db_path: str, strategies_dir: str, app_db_path: str = ""):
- """Deploy a strategy as a long-running process."""
- params = json.loads(params_json)
- strategy_name = params.get("strategy_name", strategy_id)
- symbol = params.get("symbol", "")
- asset_type = params.get("asset_type", "equity")
- mode = params.get("mode", "paper")
- timeframe = params.get("timeframe", "1d")
- quantity = float(params.get("quantity", 1))
-
- # Risk params (user-defined, not hardcoded)
- stop_loss = float(params.get("stop_loss", 0) or 0)
- take_profit = float(params.get("take_profit", 0) or 0)
- max_daily_loss = float(params.get("max_daily_loss", 0) or 0)
-
- now = datetime.now(timezone.utc).isoformat()
- pid = os.getpid()
-
- # Persist to SQLite - status starts as "waiting" (waits for conditions)
- conn = get_db(db_path)
- conn.execute(
- """INSERT OR REPLACE INTO deployed_strategies
- (deploy_id, strategy_id, strategy_name, symbol, asset_type, mode, status, params, created_at, updated_at, pid)
- VALUES (?, ?, ?, ?, ?, ?, 'waiting', ?, ?, ?, ?)""",
- (deploy_id, strategy_id, strategy_name, symbol, asset_type, mode, params_json, now, now, pid)
- )
- conn.execute(
- """INSERT OR REPLACE INTO strategy_metrics
- (deploy_id, total_pnl, total_trades, win_rate, max_drawdown, sharpe_ratio,
- current_position_qty, current_position_side, current_position_entry, updated_at)
- VALUES (?, 0, 0, 0, 0, 0, 0, '', 0, ?)""",
- (deploy_id, now)
- )
- conn.commit()
-
- # Load the strategy class
- try:
- if strategies_dir and strategies_dir not in sys.path:
- sys.path.insert(0, strategies_dir)
-
- # Find strategy file from registry
- registry_path = os.path.join(strategies_dir, "_registry.py") if strategies_dir else ""
- strategy_path = None
-
- if os.path.exists(registry_path):
- with open(registry_path, "r") as f:
- for line in f:
- if strategy_id in line and '"path":' in line:
- start = line.index('"path":') + len('"path":')
- rest = line[start:].strip().strip('"').rstrip('",}')
- strategy_path = rest
- break
-
- if not strategy_path:
- _update_status(conn, deploy_id, "error", f"Strategy {strategy_id} not found in registry")
- conn.close()
- return
-
- full_path = os.path.join(strategies_dir, strategy_path)
- if not os.path.exists(full_path):
- _update_status(conn, deploy_id, "error", f"Strategy file not found: {strategy_path}")
- conn.close()
- return
-
- # Load strategy module
- with open(full_path, "r") as f:
- source = f.read()
-
- module_globals = {}
- exec(compile(source, full_path, "exec"), module_globals)
-
- # Find the QCAlgorithm subclass
- algo_class = None
- for name, obj in module_globals.items():
- if isinstance(obj, type) and name != "QCAlgorithm":
- try:
- from fincept_engine.algorithm import QCAlgorithm
- if issubclass(obj, QCAlgorithm):
- algo_class = obj
- break
- except ImportError:
- pass
-
- if not algo_class:
- _update_status(conn, deploy_id, "error", "No QCAlgorithm subclass found in strategy")
- conn.close()
- return
-
- # Instantiate and initialize
- algo = algo_class()
- algo.set_cash(float(params.get("initial_cash", 100000)))
-
- # Inject user params via the parameter system
- algo.set_parameters({
- "symbol": symbol,
- "quantity": str(quantity),
- "mode": mode,
- "timeframe": timeframe,
- })
-
- if symbol:
- algo._live_symbol = symbol
- algo._live_quantity = quantity
-
- algo.initialize()
-
- except Exception as e:
- _update_status(conn, deploy_id, "error", str(e))
- conn.close()
- return
-
- # Graceful shutdown
- running = True
- def signal_handler(signum, frame):
- nonlocal running
- running = False
-
- signal.signal(signal.SIGTERM, signal_handler)
- signal.signal(signal.SIGINT, signal_handler)
-
- # ---- Main loop ----
- total_pnl = 0.0
- total_trades = 0
- wins = 0
- peak_equity = float(params.get("initial_cash", 100000))
- max_drawdown = 0.0
- current_position = {"qty": 0, "side": "", "entry": 0.0}
- daily_pnl = 0.0
- has_first_signal = False # Track when we move from "waiting" to "running"
-
- try:
- while running:
- try:
- # Re-read status and params from DB (allows live updates + stop detection)
- row = conn.execute(
- "SELECT status, params FROM deployed_strategies WHERE deploy_id = ?",
- (deploy_id,)
- ).fetchone()
- if not row or row["status"] in ("stopped", "error"):
- break
-
- # Dynamic param reload - user can change params while running
- if row["params"]:
- try:
- live_params = json.loads(row["params"])
- stop_loss = float(live_params.get("stop_loss", 0) or 0)
- take_profit = float(live_params.get("take_profit", 0) or 0)
- max_daily_loss = float(live_params.get("max_daily_loss", 0) or 0)
- quantity = float(live_params.get("quantity", quantity) or quantity)
- timeframe = live_params.get("timeframe", timeframe)
- except (json.JSONDecodeError, ValueError):
- pass
-
- # Fetch current market data from WebSocket cache (main app DB), fallback to yfinance
- market_data = _fetch_price(symbol, asset_type, app_db_path)
- if market_data is None:
- time.sleep(5)
- continue
-
- current_price = market_data["price"]
-
- # Feed full OHLCV data to algorithm as a TradeBar
- try:
- from fincept_engine.types import TradeBar, Symbol as FSymbol, Slice
- from fincept_engine.enums import SecurityType, Market as FMarket
-
- sec_type = SecurityType.EQUITY if asset_type == "equity" else SecurityType.CRYPTO
- market = FMarket.USA if asset_type == "equity" else FMarket.GDAX
-
- sym = FSymbol.create(symbol, sec_type, market)
- bar = TradeBar(
- time=datetime.now(timezone.utc),
- symbol=sym,
- open=market_data["open"],
- high=market_data["high"],
- low=market_data["low"],
- close=current_price,
- volume=market_data["volume"]
- )
-
- if hasattr(algo, "on_data"):
- slice_data = Slice(datetime.now(timezone.utc), {symbol: bar})
- algo.on_data(slice_data)
- except Exception:
- pass
-
- # Check for pending orders from the algorithm
- pending_orders = getattr(algo, "_pending_orders", [])
-
- # Transition from "waiting" to "running" on first signal
- if pending_orders and not has_first_signal:
- has_first_signal = True
- _update_status(conn, deploy_id, "running")
-
- for order in pending_orders:
- side = "buy" if order.get("quantity", 0) > 0 else "sell"
- qty = abs(order.get("quantity", 0))
- if qty == 0:
- qty = quantity
-
- trade_pnl = 0.0
- if current_position["qty"] > 0 and side == "sell" and current_position["side"] == "long":
- trade_pnl = (current_price - current_position["entry"]) * min(qty, current_position["qty"])
- elif current_position["qty"] > 0 and current_position["side"] == "short" and side == "buy":
- trade_pnl = (current_position["entry"] - current_price) * min(qty, current_position["qty"])
-
- # Record trade
- trade_time = datetime.now(timezone.utc).isoformat()
- conn.execute(
- """INSERT INTO strategy_trades
- (deploy_id, symbol, side, quantity, price, timestamp, pnl)
- VALUES (?, ?, ?, ?, ?, ?, ?)""",
- (deploy_id, symbol, side, qty, current_price, trade_time, trade_pnl)
- )
-
- total_trades += 1
- total_pnl += trade_pnl
- daily_pnl += trade_pnl
- if trade_pnl > 0:
- wins += 1
-
- # Update position tracking
- if side == "buy":
- if current_position["side"] == "long":
- # Add to long position
- total_qty = current_position["qty"] + qty
- avg_entry = (current_position["entry"] * current_position["qty"] + current_price * qty) / total_qty
- current_position = {"qty": total_qty, "side": "long", "entry": avg_entry}
- else:
- current_position = {"qty": qty, "side": "long", "entry": current_price}
- elif side == "sell":
- if current_position["side"] == "long":
- remaining = current_position["qty"] - qty
- if remaining <= 0:
- current_position = {"qty": 0, "side": "", "entry": 0.0}
- else:
- current_position["qty"] = remaining
- else:
- current_position = {"qty": qty, "side": "short", "entry": current_price}
-
- # Clear pending orders
- if hasattr(algo, "_pending_orders"):
- algo._pending_orders = []
-
- # Calculate unrealized PnL
- unrealized = 0.0
- if current_position["qty"] > 0 and current_position["entry"] > 0:
- if current_position["side"] == "long":
- unrealized = (current_price - current_position["entry"]) * current_position["qty"]
- else:
- unrealized = (current_position["entry"] - current_price) * current_position["qty"]
-
- # Drawdown calculation
- equity = float(params.get("initial_cash", 100000)) + total_pnl + unrealized
- if equity > peak_equity:
- peak_equity = equity
- dd = (peak_equity - equity) / peak_equity if peak_equity > 0 else 0
- if dd > max_drawdown:
- max_drawdown = dd
-
- # Risk checks (user-defined, dynamic)
- if stop_loss > 0 and unrealized < -stop_loss:
- _update_status(conn, deploy_id, "stopped", "Stop loss hit")
- break
- if take_profit > 0 and unrealized > take_profit:
- _update_status(conn, deploy_id, "stopped", "Take profit hit")
- break
- if max_daily_loss > 0 and daily_pnl < -max_daily_loss:
- _update_status(conn, deploy_id, "stopped", "Max daily loss hit")
- break
-
- # Update metrics in DB
- win_rate = (wins / total_trades * 100) if total_trades > 0 else 0
- now = datetime.now(timezone.utc).isoformat()
- conn.execute(
- """UPDATE strategy_metrics SET
- total_pnl = ?, total_trades = ?, win_rate = ?,
- max_drawdown = ?, current_position_qty = ?,
- current_position_side = ?, current_position_entry = ?,
- updated_at = ?
- WHERE deploy_id = ?""",
- (total_pnl + unrealized, total_trades, win_rate,
- max_drawdown * 100, current_position["qty"],
- current_position["side"], current_position["entry"],
- now, deploy_id)
- )
- conn.execute(
- "UPDATE deployed_strategies SET updated_at = ? WHERE deploy_id = ?",
- (now, deploy_id)
- )
- conn.commit()
-
- # Sleep based on timeframe
- sleep_map = {
- "1s": 1, "5s": 5, "10s": 10, "30s": 30,
- "1m": 60, "5m": 300, "15m": 900, "1h": 3600,
- "4h": 14400, "1d": 60, "1w": 300,
- }
- time.sleep(sleep_map.get(timeframe, 60))
-
- except Exception:
- conn.execute(
- "UPDATE deployed_strategies SET updated_at = ? WHERE deploy_id = ?",
- (datetime.now(timezone.utc).isoformat(), deploy_id)
- )
- conn.commit()
- time.sleep(5)
-
- except Exception as e:
- _update_status(conn, deploy_id, "error", str(e))
- finally:
- if conn:
- _update_status(conn, deploy_id, "stopped")
- conn.close()
-
-
-def _fetch_price(symbol: str, asset_type: str, app_db_path: str = ""):
- """Fetch current market data from WebSocket price cache (main app DB).
-
- The host WebSocket router writes every tick to strategy_price_cache in the
- main fincept_terminal.db. This function reads from that table so strategies
- use the same real-time data as the rest of the app.
-
- Returns a dict with full OHLCV + bid/ask data:
- {"price", "open", "high", "low", "volume", "bid", "ask", "change_percent"}
- Or None if no data available.
-
- Falls back to yfinance HTTP if no cached price is found (e.g. WebSocket not
- connected or symbol not subscribed).
- """
- def _row_to_dict(row):
- """Convert a cache row to a market data dict."""
- return {
- "price": float(row["price"]),
- "open": float(row["open"] or row["price"]),
- "high": float(row["high"] or row["price"]),
- "low": float(row["low"] or row["price"]),
- "volume": float(row["volume"] or 0),
- "bid": float(row["bid"] or 0),
- "ask": float(row["ask"] or 0),
- "change_percent": float(row["change_percent"] or 0),
- }
-
- # 1. Try reading from WebSocket price cache in main app DB (normalized lookup)
- if app_db_path and os.path.exists(app_db_path):
- try:
- cache_conn = sqlite3.connect(app_db_path, timeout=2)
- cache_conn.row_factory = sqlite3.Row
- # Normalize symbol for lookup: strip slashes/dashes/underscores, uppercase
- normalized = symbol.replace("/", "").replace("-", "").replace("_", "").upper()
- row = cache_conn.execute(
- """SELECT price, bid, ask, volume, high, low, open, change_percent, updated_at
- FROM strategy_price_cache
- WHERE UPPER(REPLACE(REPLACE(REPLACE(symbol, '/', ''), '-', ''), '_', '')) = ?
- LIMIT 1""",
- (normalized,)
- ).fetchone()
- cache_conn.close()
-
- if row and row["price"] and row["price"] > 0:
- # Check staleness: if updated_at is a unix timestamp, ensure it's recent
- updated_at = row["updated_at"]
- if updated_at and isinstance(updated_at, (int, float)):
- age_seconds = time.time() - (updated_at / 1000 if updated_at > 1e12 else updated_at)
- # Accept if less than 5 minutes old
- if age_seconds < 300:
- return _row_to_dict(row)
- else:
- return _row_to_dict(row)
- except Exception:
- pass
-
- # 2. Fallback: try without normalization (exact match)
- if app_db_path and os.path.exists(app_db_path):
- try:
- cache_conn = sqlite3.connect(app_db_path, timeout=2)
- cache_conn.row_factory = sqlite3.Row
- row = cache_conn.execute(
- """SELECT price, bid, ask, volume, high, low, open, change_percent, updated_at
- FROM strategy_price_cache WHERE symbol = ? LIMIT 1""",
- (symbol,)
- ).fetchone()
- cache_conn.close()
-
- if row and row["price"] and row["price"] > 0:
- return _row_to_dict(row)
- except Exception:
- pass
-
- # 3. Final fallback: yfinance HTTP (slow, rate-limited)
- try:
- import yfinance as yf
- ticker = yf.Ticker(symbol)
- info = ticker.fast_info
- price = getattr(info, "last_price", None)
- if price is None:
- hist = ticker.history(period="1d")
- if not hist.empty:
- price = float(hist["Close"].iloc[-1])
- if price:
- return {"price": price, "open": price, "high": price, "low": price,
- "volume": 0, "bid": 0, "ask": 0, "change_percent": 0}
- return None
- except Exception:
- return None
-
-
-def _update_status(conn, deploy_id: str, status: str, error: str = None):
- """Update deployment status in DB."""
- now = datetime.now(timezone.utc).isoformat()
- if status == "stopped":
- conn.execute(
- "UPDATE deployed_strategies SET status = ?, stopped_at = ?, updated_at = ? WHERE deploy_id = ?",
- (status, now, now, deploy_id)
- )
- elif error:
- conn.execute(
- "UPDATE deployed_strategies SET status = ?, updated_at = ? WHERE deploy_id = ?",
- (status, now, deploy_id)
- )
- # Store error in a separate way that doesn't break params JSON
- try:
- row = conn.execute("SELECT params FROM deployed_strategies WHERE deploy_id = ?", (deploy_id,)).fetchone()
- if row and row["params"]:
- p = json.loads(row["params"])
- p["_error"] = error
- conn.execute("UPDATE deployed_strategies SET params = ? WHERE deploy_id = ?", (json.dumps(p), deploy_id))
- except Exception:
- pass
- else:
- conn.execute(
- "UPDATE deployed_strategies SET status = ?, updated_at = ? WHERE deploy_id = ?",
- (status, now, deploy_id)
- )
- conn.commit()
-
-
-# ============================================================================
-# Stop Command - reads PID from DB, kills process, updates status
-# ============================================================================
-
-def cmd_stop(deploy_id: str, db_path: str):
- """Stop a deployed strategy by reading PID from DB and killing it."""
- conn = get_db(db_path)
-
- # Read PID from DB
- row = conn.execute(
- "SELECT pid FROM deployed_strategies WHERE deploy_id = ?",
- (deploy_id,)
- ).fetchone()
-
- if row and row["pid"]:
- try:
- os.kill(row["pid"], signal.SIGTERM)
- except (ProcessLookupError, PermissionError, OSError):
- pass
-
- _update_status(conn, deploy_id, "stopped")
- conn.close()
- print(json.dumps({"success": True, "deploy_id": deploy_id}))
-
-
-# ============================================================================
-# Stop All Command
-# ============================================================================
-
-def cmd_stop_all(asset_type: str, db_path: str):
- """Stop all strategies of a given asset type."""
- conn = get_db(db_path)
- now = datetime.now(timezone.utc).isoformat()
- cursor = conn.execute(
- "SELECT deploy_id, pid FROM deployed_strategies WHERE asset_type = ? AND status IN ('running', 'waiting', 'starting')",
- (asset_type,)
- )
- stopped = []
- for row in cursor.fetchall():
- conn.execute(
- "UPDATE deployed_strategies SET status = 'stopped', stopped_at = ?, updated_at = ? WHERE deploy_id = ?",
- (now, now, row["deploy_id"])
- )
- stopped.append(row["deploy_id"])
- if row["pid"]:
- try:
- os.kill(row["pid"], signal.SIGTERM)
- except (ProcessLookupError, PermissionError, OSError):
- pass
-
- conn.commit()
- conn.close()
- print(json.dumps({"success": True, "stopped": stopped, "count": len(stopped)}))
-
-
-# ============================================================================
-# List Command
-# ============================================================================
-
-def cmd_list(asset_type: str, db_path: str):
- """List deployed strategies with metrics."""
- conn = get_db(db_path)
- cursor = conn.execute(
- """SELECT d.*, m.total_pnl, m.total_trades, m.win_rate, m.max_drawdown,
- m.sharpe_ratio, m.current_position_qty, m.current_position_side,
- m.current_position_entry
- FROM deployed_strategies d
- LEFT JOIN strategy_metrics m ON d.deploy_id = m.deploy_id
- WHERE d.asset_type = ? AND d.status IN ('running', 'starting', 'waiting', 'error')
- ORDER BY d.created_at DESC""",
- (asset_type,)
- )
- results = []
- for row in cursor.fetchall():
- item = dict(row)
- # Check if process is still alive
- if item.get("pid") and item["status"] in ("running", "waiting"):
- try:
- os.kill(item["pid"], 0)
- except (ProcessLookupError, OSError):
- item["status"] = "stopped"
- conn.execute(
- "UPDATE deployed_strategies SET status = 'stopped', updated_at = ? WHERE deploy_id = ?",
- (datetime.now(timezone.utc).isoformat(), item["deploy_id"])
- )
- results.append(item)
-
- conn.commit()
- conn.close()
- print(json.dumps({"success": True, "data": results, "source": "sqlite"}))
-
-
-# ============================================================================
-# Check Duplicate Command
-# ============================================================================
-
-def cmd_check_duplicate(strategy_id: str, symbol: str, db_path: str):
- """Check if a strategy+symbol combo is already deployed."""
- conn = get_db(db_path)
- row = conn.execute(
- """SELECT deploy_id FROM deployed_strategies
- WHERE strategy_id = ? AND symbol = ? AND status IN ('running', 'waiting', 'starting')
- LIMIT 1""",
- (strategy_id, symbol)
- ).fetchone()
- conn.close()
- is_dup = row is not None
- print(json.dumps({"success": True, "is_duplicate": is_dup, "existing_deploy_id": row["deploy_id"] if is_dup else None}))
-
-
-# ============================================================================
-# Update Command - update params of a running strategy
-# ============================================================================
-
-def cmd_update(deploy_id: str, params_json: str, db_path: str):
- """Update parameters of a deployed strategy. Runner picks up changes on next loop."""
- conn = get_db(db_path)
-
- # Merge new params with existing
- row = conn.execute(
- "SELECT params, status FROM deployed_strategies WHERE deploy_id = ?",
- (deploy_id,)
- ).fetchone()
-
- if not row:
- conn.close()
- print(json.dumps({"success": False, "error": "Strategy not found"}))
- return
-
- if row["status"] not in ("running", "waiting"):
- conn.close()
- print(json.dumps({"success": False, "error": f"Cannot update strategy in '{row['status']}' state"}))
- return
-
- try:
- existing = json.loads(row["params"]) if row["params"] else {}
- updates = json.loads(params_json)
- existing.update(updates)
- now = datetime.now(timezone.utc).isoformat()
- conn.execute(
- "UPDATE deployed_strategies SET params = ?, updated_at = ? WHERE deploy_id = ?",
- (json.dumps(existing), now, deploy_id)
- )
- conn.commit()
- except Exception as e:
- conn.close()
- print(json.dumps({"success": False, "error": str(e)}))
- return
-
- conn.close()
- print(json.dumps({"success": True, "deploy_id": deploy_id}))
-
-
-# ============================================================================
-# CLI Entry Point
-# ============================================================================
-
-def main():
- if len(sys.argv) < 2:
- print(json.dumps({"success": False, "error": "No command provided"}))
- sys.exit(1)
-
- command = sys.argv[1]
-
- # Parse --db, --strategies-dir, and --app-db flags
- db_path = None
- strategies_dir = None
- app_db_path = ""
- args = sys.argv[2:]
- positional = []
-
- i = 0
- while i < len(args):
- if args[i] == "--db" and i + 1 < len(args):
- db_path = args[i + 1]
- i += 2
- elif args[i] == "--strategies-dir" and i + 1 < len(args):
- strategies_dir = args[i + 1]
- i += 2
- elif args[i] == "--app-db" and i + 1 < len(args):
- app_db_path = args[i + 1]
- i += 2
- else:
- positional.append(args[i])
- i += 1
-
- if not db_path:
- print(json.dumps({"success": False, "error": "--db path is required"}))
- sys.exit(1)
-
- if command == "deploy":
- if len(positional) < 3:
- print(json.dumps({"success": False, "error": "Usage: deploy <deploy_id> <strategy_id> <params_json>"}))
- sys.exit(1)
- cmd_deploy(positional[0], positional[1], positional[2], db_path, strategies_dir or "", app_db_path)
-
- elif command == "stop":
- if len(positional) < 1:
- print(json.dumps({"success": False, "error": "Usage: stop <deploy_id>"}))
- sys.exit(1)
- cmd_stop(positional[0], db_path)
-
- elif command == "stop_all":
- if len(positional) < 1:
- print(json.dumps({"success": False, "error": "Usage: stop_all <asset_type>"}))
- sys.exit(1)
- cmd_stop_all(positional[0], db_path)
-
- elif command == "list":
- if len(positional) < 1:
- print(json.dumps({"success": False, "error": "Usage: list <asset_type>"}))
- sys.exit(1)
- cmd_list(positional[0], db_path)
-
- elif command == "check_duplicate":
- if len(positional) < 2:
- print(json.dumps({"success": False, "error": "Usage: check_duplicate <strategy_id> <symbol>"}))
- sys.exit(1)
- cmd_check_duplicate(positional[0], positional[1], db_path)
-
- elif command == "update":
- if len(positional) < 2:
- print(json.dumps({"success": False, "error": "Usage: update <deploy_id> <params_json>"}))
- sys.exit(1)
- cmd_update(positional[0], positional[1], db_path)
-
- else:
- print(json.dumps({"success": False, "error": f"Unknown command: {command}"}))
- sys.exit(1)
-
-
-if __name__ == "__main__":
- main()
diff --git a/fincept-qt/scripts/strategies/main.py b/fincept-qt/scripts/strategies/main.py
deleted file mode 100644
index 1ee692866..000000000
--- a/fincept-qt/scripts/strategies/main.py
+++ /dev/null
@@ -1,33 +0,0 @@
-# ============================================================================
-# Fincept Terminal - Strategy Engine
-# Copyright (c) 2024-2026 Fincept Corporation. All rights reserved.
-# Licensed under the MIT License.
-# https://github.com/Fincept-Corporation/FinceptTerminal
-#
-# Strategy ID: FCT-FAD58DE7
-# Category: General Strategy
-# Description: Basic template algorithm simply initializes the date range and cash
-# Compatibility: Backtesting | Paper Trading | Live Deployment
-# ============================================================================
-from AlgorithmImports import *
-
-class BasicTemplateAlgorithm(QCAlgorithm):
- '''Basic template algorithm simply initializes the date range and cash'''
-
- def initialize(self):
- '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
-
- self.set_start_date(2013,10,7) #Set Start Date
- self.set_end_date(2013,10,11) #Set End Date
- self.set_cash(100000) #Set Strategy Cash
- # Fincept Terminal Strategy Engine - Symbol Configuration
- self.add_equity("SPY", Resolution.SECOND)
-
- def on_data(self, data):
- '''on_data event is the primary entry point for your algorithm. Each new data point will be pumped in here.
-
- Arguments:
- data: Slice object keyed by symbol containing the stock data
- '''
- if not self.portfolio.invested:
- self.set_holdings("SPY", 1)
diff --git a/fincept-qt/scripts/strategies/registry_index.json b/fincept-qt/scripts/strategies/registry_index.json
deleted file mode 100644
index 6438f7951..000000000
--- a/fincept-qt/scripts/strategies/registry_index.json
+++ /dev/null
@@ -1 +0,0 @@
-{"strategies":[{"id":"FCT-19E8A564","name":"AccumulativeInsightPortfolioRegressionAlgorithm","description":"Portfolio Management","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"AccumulativeInsightPortfolioRegressionAlgorithm.py"},{"id":"FCT-761339E9","name":"AddAlphaModelAlgorithm","description":"Alpha Model","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"AddAlphaModelAlgorithm.py"},{"id":"FCT-3CCF5CE2","name":"AddFutureOptionContractDataStreamingRegressionAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"AddFutureOptionContractDataStreamingRegressionAlgorithm.py"},{"id":"FCT-2EF41B6D","name":"AddFutureOptionSingleOptionChainSelectedInUniverseFilterRegressionAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"AddFutureOptionSingleOptionChainSelectedInUniverseFilterRegressionAlgorithm.py"},{"id":"FCT-5CED3309","name":"AddOptionContractExpiresRegressionAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"AddOptionContractExpiresRegressionAlgorithm.py"},{"id":"FCT-202B8187","name":"AddOptionContractFromUniverseRegressionAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"AddOptionContractFromUniverseRegressionAlgorithm.py"},{"id":"FCT-DA228821","name":"AddRemoveSecurityRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"AddRemoveSecurityRegressionAlgorithm.py"},{"id":"FCT-9874FF18","name":"AddRiskManagementAlgorithm","description":"Risk Management","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"AddRiskManagementAlgorithm.py"},{"id":"FCT-8AB253F8","name":"AddUniverseSelectionModelAlgorithm","description":"Universe Selection","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"AddUniverseSelectionModelAlgorithm.py"},{"id":"FCT-D137348C","name":"AlgorithmModeAndDeploymentTargetAlgorithm","description":"General Strategy","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"AlgorithmModeAndDeploymentTargetAlgorithm.py"},{"id":"FCT-6C937E43","name":"AllShortableSymbolsCoarseSelectionRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"AllShortableSymbolsCoarseSelectionRegressionAlgorithm.py"},{"id":"FCT-F9837218","name":"AsynchronousUniverseRegressionAlgorithm","description":"Universe Selection","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"AsynchronousUniverseRegressionAlgorithm.py"},{"id":"FCT-5FF79273","name":"AutoRegressiveIntegratedMovingAverageRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"AutoRegressiveIntegratedMovingAverageRegressionAlgorithm.py"},{"id":"FCT-C395D1D2","name":"AuxiliaryDataHandlersRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"AuxiliaryDataHandlersRegressionAlgorithm.py"},{"id":"FCT-0A7F740C","name":"BaseFrameworkRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"BaseFrameworkRegressionAlgorithm.py"},{"id":"FCT-3B2A7C04","name":"BasicCSharpIntegrationTemplateAlgorithm","description":"Template","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"BasicCSharpIntegrationTemplateAlgorithm.py"},{"id":"FCT-07DF2AB7","name":"BasicSetAccountCurrencyAlgorithm","description":"General Strategy","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"BasicSetAccountCurrencyAlgorithm.py"},{"id":"FCT-9A26B9BE","name":"BasicSetAccountCurrencyWithAmountAlgorithm","description":"General Strategy","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"BasicSetAccountCurrencyWithAmountAlgorithm.py"},{"id":"FCT-82A09B26","name":"BasicTemplateAlgorithm","description":"Template","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"BasicTemplateAlgorithm.py"},{"id":"FCT-0FAA6BDF","name":"BasicTemplateAxosAlgorithm","description":"Template","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"BasicTemplateAxosAlgorithm.py"},{"id":"FCT-07CF5BDC","name":"BasicTemplateCfdAlgorithm","description":"Template","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"BasicTemplateCfdAlgorithm.py"},{"id":"FCT-CED11838","name":"BasicTemplateContinuousFutureAlgorithm","description":"Futures","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"BasicTemplateContinuousFutureAlgorithm.py"},{"id":"FCT-34321EAB","name":"BasicTemplateContinuousFutureWithExtendedMarketAlgorithm","description":"Futures","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"BasicTemplateContinuousFutureWithExtendedMarketAlgorithm.py"},{"id":"FCT-C45FB406","name":"BasicTemplateCryptoAlgorithm","description":"Crypto","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"BasicTemplateCryptoAlgorithm.py"},{"id":"FCT-F09974A0","name":"BasicTemplateCryptoFutureAlgorithm","description":"Futures","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"BasicTemplateCryptoFutureAlgorithm.py"},{"id":"FCT-E96624E8","name":"BasicTemplateCryptoFutureHourlyAlgorithm","description":"Futures","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"BasicTemplateCryptoFutureHourlyAlgorithm.py"},{"id":"FCT-1ADBAC8E","name":"BasicTemplateDailyAlgorithm","description":"Template","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"BasicTemplateDailyAlgorithm.py"},{"id":"FCT-59CC070D","name":"BasicTemplateEurexFuturesAlgorithm","description":"Futures","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"BasicTemplateEurexFuturesAlgorithm.py"},{"id":"FCT-D7F55E8F","name":"BasicTemplateFillForwardAlgorithm","description":"Template","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"BasicTemplateFillForwardAlgorithm.py"},{"id":"FCT-DBF9152F","name":"BasicTemplateForexAlgorithm","description":"Forex","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"BasicTemplateForexAlgorithm.py"},{"id":"FCT-EE88AED1","name":"BasicTemplateFrameworkAlgorithm","description":"Template","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"BasicTemplateFrameworkAlgorithm.py"},{"id":"FCT-2426C5B7","name":"BasicTemplateFutureOptionAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"BasicTemplateFutureOptionAlgorithm.py"},{"id":"FCT-1DD3D3FC","name":"BasicTemplateFutureRolloverAlgorithm","description":"Futures","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"BasicTemplateFutureRolloverAlgorithm.py"},{"id":"FCT-D9822D5B","name":"BasicTemplateFuturesAlgorithm","description":"Futures","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"BasicTemplateFuturesAlgorithm.py"},{"id":"FCT-C0AB4825","name":"BasicTemplateFuturesConsolidationAlgorithm","description":"Futures","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"BasicTemplateFuturesConsolidationAlgorithm.py"},{"id":"FCT-B04B5965","name":"BasicTemplateFuturesDailyAlgorithm","description":"Futures","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"BasicTemplateFuturesDailyAlgorithm.py"},{"id":"FCT-3F20A848","name":"BasicTemplateFuturesFrameworkAlgorithm","description":"Futures","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"BasicTemplateFuturesFrameworkAlgorithm.py"},{"id":"FCT-456D112C","name":"BasicTemplateFuturesFrameworkWithExtendedMarketAlgorithm","description":"Futures","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"BasicTemplateFuturesFrameworkWithExtendedMarketAlgorithm.py"},{"id":"FCT-265D788C","name":"BasicTemplateFuturesHistoryAlgorithm","description":"Futures","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"BasicTemplateFuturesHistoryAlgorithm.py"},{"id":"FCT-9713D1F5","name":"BasicTemplateFuturesHistoryWithExtendedMarketHoursAlgorithm","description":"Futures","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"BasicTemplateFuturesHistoryWithExtendedMarketHoursAlgorithm.py"},{"id":"FCT-D52E449D","name":"BasicTemplateFuturesHourlyAlgorithm","description":"Futures","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"BasicTemplateFuturesHourlyAlgorithm.py"},{"id":"FCT-527E38F2","name":"BasicTemplateFuturesWithExtendedMarketAlgorithm","description":"Futures","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"BasicTemplateFuturesWithExtendedMarketAlgorithm.py"},{"id":"FCT-074CBF2C","name":"BasicTemplateFuturesWithExtendedMarketDailyAlgorithm","description":"Futures","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"BasicTemplateFuturesWithExtendedMarketDailyAlgorithm.py"},{"id":"FCT-006DF51F","name":"BasicTemplateFuturesWithExtendedMarketHourlyAlgorithm","description":"Futures","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"BasicTemplateFuturesWithExtendedMarketHourlyAlgorithm.py"},{"id":"FCT-A17DA593","name":"BasicTemplateIndexAlgorithm","description":"Index","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"BasicTemplateIndexAlgorithm.py"},{"id":"FCT-A8601615","name":"BasicTemplateIndexDailyAlgorithm","description":"Index","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"BasicTemplateIndexDailyAlgorithm.py"},{"id":"FCT-210273A6","name":"BasicTemplateIndexOptionsAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"BasicTemplateIndexOptionsAlgorithm.py"},{"id":"FCT-CB56992B","name":"BasicTemplateIndiaAlgorithm","description":"Template","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"BasicTemplateIndiaAlgorithm.py"},{"id":"FCT-77306E7F","name":"BasicTemplateIndiaIndexAlgorithm","description":"Index","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"BasicTemplateIndiaIndexAlgorithm.py"},{"id":"FCT-13F865B8","name":"BasicTemplateIntrinioEconomicData","description":"Template","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"BasicTemplateIntrinioEconomicData.py"},{"id":"FCT-A18CA8E6","name":"BasicTemplateLibrary","description":"Template","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"BasicTemplateLibrary.py"},{"id":"FCT-3EB6E68A","name":"BasicTemplateOptionEquityStrategyAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"BasicTemplateOptionEquityStrategyAlgorithm.py"},{"id":"FCT-185C6BF9","name":"BasicTemplateOptionStrategyAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"BasicTemplateOptionStrategyAlgorithm.py"},{"id":"FCT-29268ED2","name":"BasicTemplateOptionTradesAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"BasicTemplateOptionTradesAlgorithm.py"},{"id":"FCT-9970673F","name":"BasicTemplateOptionsAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"BasicTemplateOptionsAlgorithm.py"},{"id":"FCT-48AE2A59","name":"BasicTemplateOptionsConsolidationAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"BasicTemplateOptionsConsolidationAlgorithm.py"},{"id":"FCT-216E29F5","name":"BasicTemplateOptionsDailyAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"BasicTemplateOptionsDailyAlgorithm.py"},{"id":"FCT-702E8C68","name":"BasicTemplateOptionsFilterUniverseAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"BasicTemplateOptionsFilterUniverseAlgorithm.py"},{"id":"FCT-778FF392","name":"BasicTemplateOptionsFrameworkAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"BasicTemplateOptionsFrameworkAlgorithm.py"},{"id":"FCT-9F0275D6","name":"BasicTemplateOptionsHistoryAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"BasicTemplateOptionsHistoryAlgorithm.py"},{"id":"FCT-77549805","name":"BasicTemplateOptionsHourlyAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"BasicTemplateOptionsHourlyAlgorithm.py"},{"id":"FCT-79BA1C77","name":"BasicTemplateOptionsPriceModel","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"BasicTemplateOptionsPriceModel.py"},{"id":"FCT-DB3B5321","name":"BasicTemplateSPXWeeklyIndexOptionsAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"BasicTemplateSPXWeeklyIndexOptionsAlgorithm.py"},{"id":"FCT-88C8DA85","name":"BasicTemplateTradableIndexAlgorithm","description":"Index","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"BasicTemplateTradableIndexAlgorithm.py"},{"id":"FCT-8B86F74C","name":"BlackLittermanPortfolioOptimizationFrameworkAlgorithm","description":"Portfolio Management","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"BlackLittermanPortfolioOptimizationFrameworkAlgorithm.py"},{"id":"FCT-13992977","name":"BrokerageActivityEventHandlingAlgorithm","description":"Brokerage","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"BrokerageActivityEventHandlingAlgorithm.py"},{"id":"FCT-21FCDA65","name":"BrokerageModelAlgorithm","description":"Brokerage","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"BrokerageModelAlgorithm.py"},{"id":"FCT-181E0A50","name":"BubbleAlgorithm","description":"General Strategy","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"BubbleAlgorithm.py"},{"id":"FCT-C4535414","name":"BybitCryptoFuturesRegressionAlgorithm","description":"Futures","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"BybitCryptoFuturesRegressionAlgorithm.py"},{"id":"FCT-8205EE4A","name":"BybitCryptoRegressionAlgorithm","description":"Crypto","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"BybitCryptoRegressionAlgorithm.py"},{"id":"FCT-E8BBF79A","name":"BybitCustomDataCryptoRegressionAlgorithm","description":"Crypto","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"BybitCustomDataCryptoRegressionAlgorithm.py"},{"id":"FCT-E8875612","name":"CallbackCommandRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"CallbackCommandRegressionAlgorithm.py"},{"id":"FCT-D8FB9470","name":"CanLiquidateWithOrderPropertiesRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"CanLiquidateWithOrderPropertiesRegressionAlgorithm.py"},{"id":"FCT-65D25230","name":"CapmAlphaRankingFrameworkAlgorithm","description":"Alpha Model","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"CapmAlphaRankingFrameworkAlgorithm.py"},{"id":"FCT-F172EB67","name":"ClassicRangeConsolidatorAlgorithm","description":"Data Consolidation","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"ClassicRangeConsolidatorAlgorithm.py"},{"id":"FCT-5407C44C","name":"ClassicRangeConsolidatorWithTickAlgorithm","description":"Data Consolidation","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"ClassicRangeConsolidatorWithTickAlgorithm.py"},{"id":"FCT-D909F7DF","name":"ClassicRenkoConsolidatorAlgorithm","description":"Data Consolidation","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"ClassicRenkoConsolidatorAlgorithm.py"},{"id":"FCT-A0A879A8","name":"CoarseFineAsyncUniverseRegressionAlgorithm","description":"Universe Selection","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"CoarseFineAsyncUniverseRegressionAlgorithm.py"},{"id":"FCT-CE80899F","name":"CoarseFineFundamentalComboAlgorithm","description":"General Strategy","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"CoarseFineFundamentalComboAlgorithm.py"},{"id":"FCT-BF06E7EB","name":"CoarseFineFundamentalRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"CoarseFineFundamentalRegressionAlgorithm.py"},{"id":"FCT-5542D978","name":"CoarseFineOptionUniverseChainRegressionAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"CoarseFineOptionUniverseChainRegressionAlgorithm.py"},{"id":"FCT-F95F1806","name":"CoarseFundamentalTop3Algorithm","description":"General Strategy","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"CoarseFundamentalTop3Algorithm.py"},{"id":"FCT-5600B07D","name":"Collective2PortfolioSignalExportDemonstrationAlgorithm","description":"Portfolio Management","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"Collective2PortfolioSignalExportDemonstrationAlgorithm.py"},{"id":"FCT-8AEECDC1","name":"Collective2SignalExportDemonstrationAlgorithm","description":"General Strategy","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"Collective2SignalExportDemonstrationAlgorithm.py"},{"id":"FCT-EB692DBC","name":"ComboOrderTicketDemoAlgorithm","description":"General Strategy","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"ComboOrderTicketDemoAlgorithm.py"},{"id":"FCT-203BF5C3","name":"ComboOrdersFillModelAlgorithm","description":"General Strategy","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"ComboOrdersFillModelAlgorithm.py"},{"id":"FCT-5E302074","name":"CompleteOrderTagUpdateAlgorithm","description":"General Strategy","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"CompleteOrderTagUpdateAlgorithm.py"},{"id":"FCT-50C4F04D","name":"CompositeAlphaModelFrameworkAlgorithm","description":"Alpha Model","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"CompositeAlphaModelFrameworkAlgorithm.py"},{"id":"FCT-5A1D14B7","name":"CompositeRiskManagementModelFrameworkAlgorithm","description":"Risk Management","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"CompositeRiskManagementModelFrameworkAlgorithm.py"},{"id":"FCT-9EECE18B","name":"ConfidenceWeightedFrameworkAlgorithm","description":"General Strategy","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"ConfidenceWeightedFrameworkAlgorithm.py"},{"id":"FCT-C054C3D1","name":"ConsolidateDifferentTickTypesRegressionAlgorithm","description":"Data Consolidation","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"ConsolidateDifferentTickTypesRegressionAlgorithm.py"},{"id":"FCT-D4F95392","name":"ConsolidateHourBarsIntoDailyBarsRegressionAlgorithm","description":"Data Consolidation","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"ConsolidateHourBarsIntoDailyBarsRegressionAlgorithm.py"},{"id":"FCT-16F5EE2E","name":"ConsolidateRegressionAlgorithm","description":"Data Consolidation","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"ConsolidateRegressionAlgorithm.py"},{"id":"FCT-EFBD246D","name":"ConstituentsQC500GeneratorAlgorithm","description":"General Strategy","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"ConstituentsQC500GeneratorAlgorithm.py"},{"id":"FCT-DE244AD5","name":"ConstituentsUniverseRegressionAlgorithm","description":"Universe Selection","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"ConstituentsUniverseRegressionAlgorithm.py"},{"id":"FCT-E27B6A38","name":"ContinuousFutureModelsConsistencyRegressionAlgorithm","description":"Futures","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"ContinuousFutureModelsConsistencyRegressionAlgorithm.py"},{"id":"FCT-C573FB46","name":"ContinuousFutureRegressionAlgorithm","description":"Futures","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"ContinuousFutureRegressionAlgorithm.py"},{"id":"FCT-E9C47E95","name":"ConvertToFrameworkAlgorithm","description":"General Strategy","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"ConvertToFrameworkAlgorithm.py"},{"id":"FCT-C0F56022","name":"CorrectConsolidatedBarTypeForTickTypesAlgorithm","description":"Data Consolidation","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"CorrectConsolidatedBarTypeForTickTypesAlgorithm.py"},{"id":"FCT-0AD9A342","name":"CoveredAndProtectiveCallStrategiesAlgorithm","description":"General Strategy","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"CoveredAndProtectiveCallStrategiesAlgorithm.py"},{"id":"FCT-485EB46A","name":"CoveredAndProtectivePutStrategiesAlgorithm","description":"General Strategy","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"CoveredAndProtectivePutStrategiesAlgorithm.py"},{"id":"FCT-B5A1B412","name":"CrunchDAOSignalExportDemonstrationAlgorithm","description":"General Strategy","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"CrunchDAOSignalExportDemonstrationAlgorithm.py"},{"id":"FCT-390AE467","name":"CustomBenchmarkAlgorithm","description":"Benchmark","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"CustomBenchmarkAlgorithm.py"},{"id":"FCT-F72D9CA4","name":"CustomBenchmarkRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"CustomBenchmarkRegressionAlgorithm.py"},{"id":"FCT-BDF6639E","name":"CustomBrokerageModelRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"CustomBrokerageModelRegressionAlgorithm.py"},{"id":"FCT-D2A1A24A","name":"CustomBrokerageSideOrderHandlingRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"CustomBrokerageSideOrderHandlingRegressionAlgorithm.py"},{"id":"FCT-335819E6","name":"CustomBrokerageSideOrderHandlingRegressionPartialAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"CustomBrokerageSideOrderHandlingRegressionPartialAlgorithm.py"},{"id":"FCT-DC4DC088","name":"CustomBuyingPowerModelAlgorithm","description":"General Strategy","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"CustomBuyingPowerModelAlgorithm.py"},{"id":"FCT-DAAB71C9","name":"CustomChartingAlgorithm","description":"General Strategy","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"CustomChartingAlgorithm.py"},{"id":"FCT-5FE7DA42","name":"CustomConsolidatorRegressionAlgorithm","description":"Data Consolidation","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"CustomConsolidatorRegressionAlgorithm.py"},{"id":"FCT-23C6E607","name":"CustomDataBenchmarkRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"CustomDataBenchmarkRegressionAlgorithm.py"},{"id":"FCT-0D7003A5","name":"CustomDataBitcoinAlgorithm","description":"Custom Data","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"CustomDataBitcoinAlgorithm.py"},{"id":"FCT-52D9893F","name":"CustomDataIconicTypesAddDataRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"CustomDataIconicTypesAddDataRegressionAlgorithm.py"},{"id":"FCT-0021591C","name":"CustomDataIndicatorExtensionsAlgorithm","description":"Indicators","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"CustomDataIndicatorExtensionsAlgorithm.py"},{"id":"FCT-3EE829AC","name":"CustomDataLinkedIconicTypeAddDataCoarseSelectionRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"CustomDataLinkedIconicTypeAddDataCoarseSelectionRegressionAlgorithm.py"},{"id":"FCT-BAD0C3B3","name":"CustomDataLinkedIconicTypeAddDataOnSecuritiesChangedRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"CustomDataLinkedIconicTypeAddDataOnSecuritiesChangedRegressionAlgorithm.py"},{"id":"FCT-EA427FD2","name":"CustomDataMultiFileObjectStoreRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"CustomDataMultiFileObjectStoreRegressionAlgorithm.py"},{"id":"FCT-8C140F85","name":"CustomDataNIFTYAlgorithm","description":"Custom Data","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"CustomDataNIFTYAlgorithm.py"},{"id":"FCT-675A0EC6","name":"CustomDataObjectStoreRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"CustomDataObjectStoreRegressionAlgorithm.py"},{"id":"FCT-9147ECE5","name":"CustomDataPropertiesRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"CustomDataPropertiesRegressionAlgorithm.py"},{"id":"FCT-67CFD0CD","name":"CustomDataRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"CustomDataRegressionAlgorithm.py"},{"id":"FCT-1A4DBA47","name":"CustomDataTypeHistoryAlgorithm","description":"Custom Data","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"CustomDataTypeHistoryAlgorithm.py"},{"id":"FCT-A032E1EE","name":"CustomDataUniverseAlgorithm","description":"Universe Selection","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"CustomDataUniverseAlgorithm.py"},{"id":"FCT-FC1DA597","name":"CustomDataUniverseRegressionAlgorithm","description":"Universe Selection","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"CustomDataUniverseRegressionAlgorithm.py"},{"id":"FCT-72626C25","name":"CustomDataUniverseScheduledRegressionAlgorithm","description":"Universe Selection","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"CustomDataUniverseScheduledRegressionAlgorithm.py"},{"id":"FCT-BEF6D76E","name":"CustomDataUsingMapFileRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"CustomDataUsingMapFileRegressionAlgorithm.py"},{"id":"FCT-95644B6E","name":"CustomDataZippedObjectStoreRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"CustomDataZippedObjectStoreRegressionAlgorithm.py"},{"id":"FCT-0B5CD58B","name":"CustomIndicatorAlgorithm","description":"Indicators","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"CustomIndicatorAlgorithm.py"},{"id":"FCT-E42C0F2D","name":"CustomIndicatorWithExtensionAlgorithm","description":"Indicators","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"CustomIndicatorWithExtensionAlgorithm.py"},{"id":"FCT-F06C15CD","name":"CustomMarginInterestRateModelAlgorithm","description":"Margin","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"CustomMarginInterestRateModelAlgorithm.py"},{"id":"FCT-C77A7B18","name":"CustomModelsAlgorithm","description":"General Strategy","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"CustomModelsAlgorithm.py"},{"id":"FCT-3555D255","name":"CustomModelsPEP8Algorithm","description":"General Strategy","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"CustomModelsPEP8Algorithm.py"},{"id":"FCT-8C620280","name":"CustomOptionAssignmentRegressionAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"CustomOptionAssignmentRegressionAlgorithm.py"},{"id":"FCT-A7E25D46","name":"CustomOptionExerciseModelRegressionAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"CustomOptionExerciseModelRegressionAlgorithm.py"},{"id":"FCT-3E3DC670","name":"CustomPartialFillModelAlgorithm","description":"General Strategy","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"CustomPartialFillModelAlgorithm.py"},{"id":"FCT-9C9C9891","name":"CustomPortfolioOptimizerRegressionAlgorithm","description":"Portfolio Management","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"CustomPortfolioOptimizerRegressionAlgorithm.py"},{"id":"FCT-2F0E8AB5","name":"CustomSecurityDataFilterRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"CustomSecurityDataFilterRegressionAlgorithm.py"},{"id":"FCT-C15813B3","name":"CustomSecurityInitializerAlgorithm","description":"General Strategy","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"CustomSecurityInitializerAlgorithm.py"},{"id":"FCT-3D3166AE","name":"CustomSettlementModelRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"CustomSettlementModelRegressionAlgorithm.py"},{"id":"FCT-324DD834","name":"CustomShortableProviderRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"CustomShortableProviderRegressionAlgorithm.py"},{"id":"FCT-CB434E24","name":"CustomUniverseSelectionModelRegressionAlgorithm","description":"Universe Selection","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"CustomUniverseSelectionModelRegressionAlgorithm.py"},{"id":"FCT-57E3FCCE","name":"CustomVolatilityModelAlgorithm","description":"General Strategy","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"CustomVolatilityModelAlgorithm.py"},{"id":"FCT-223472B2","name":"CustomWarmUpPeriodIndicatorAlgorithm","description":"Indicators","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"CustomWarmUpPeriodIndicatorAlgorithm.py"},{"id":"FCT-DCA92403","name":"DailyAlgorithm","description":"General Strategy","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"DailyAlgorithm.py"},{"id":"FCT-5DD0A982","name":"DataConsolidationAlgorithm","description":"Data Consolidation","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"DataConsolidationAlgorithm.py"},{"id":"FCT-2D323EF8","name":"DelistingEventsAlgorithm","description":"Corporate Actions","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"DelistingEventsAlgorithm.py"},{"id":"FCT-6513B96C","name":"DescendingCustomDataObjectStoreRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"DescendingCustomDataObjectStoreRegressionAlgorithm.py"},{"id":"FCT-E476428A","name":"DisplacedMovingAverageRibbon","description":"General Strategy","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"DisplacedMovingAverageRibbon.py"},{"id":"FCT-3A64A758","name":"DividendAlgorithm","description":"Corporate Actions","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"DividendAlgorithm.py"},{"id":"FCT-FFA7AD77","name":"DropboxBaseDataUniverseSelectionAlgorithm","description":"Universe Selection","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"DropboxBaseDataUniverseSelectionAlgorithm.py"},{"id":"FCT-43A9D681","name":"DropboxCoarseFineAlgorithm","description":"General Strategy","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"DropboxCoarseFineAlgorithm.py"},{"id":"FCT-C02B7DE9","name":"DropboxUniverseSelectionAlgorithm","description":"Universe Selection","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"DropboxUniverseSelectionAlgorithm.py"},{"id":"FCT-D86D36A8","name":"DynamicSecurityDataRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"DynamicSecurityDataRegressionAlgorithm.py"},{"id":"FCT-2A9A1A33","name":"ETFConstituentUniverseCompositeDelistingRegressionAlgorithm","description":"ETF","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"ETFConstituentUniverseCompositeDelistingRegressionAlgorithm.py"},{"id":"FCT-D7673A55","name":"ETFConstituentUniverseCompositeDelistingRegressionAlgorithmNoAddEquityETF","description":"ETF","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"ETFConstituentUniverseCompositeDelistingRegressionAlgorithmNoAddEquityETF.py"},{"id":"FCT-9E29F41C","name":"ETFConstituentUniverseFilterFunctionRegressionAlgorithm","description":"ETF","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"ETFConstituentUniverseFilterFunctionRegressionAlgorithm.py"},{"id":"FCT-D46C4922","name":"ETFConstituentUniverseFrameworkRegressionAlgorithm","description":"ETF","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"ETFConstituentUniverseFrameworkRegressionAlgorithm.py"},{"id":"FCT-B97EAA99","name":"ETFConstituentUniverseMappedCompositeRegressionAlgorithm","description":"ETF","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"ETFConstituentUniverseMappedCompositeRegressionAlgorithm.py"},{"id":"FCT-4249AE56","name":"ETFConstituentUniverseRSIAlphaModelAlgorithm","description":"ETF","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"ETFConstituentUniverseRSIAlphaModelAlgorithm.py"},{"id":"FCT-A8E104E5","name":"ETFConstituentsFrameworkAlgorithm","description":"ETF","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"ETFConstituentsFrameworkAlgorithm.py"},{"id":"FCT-A7B56E18","name":"ETFConstituentsFrameworkWithDifferentSelectionModelAlgorithm","description":"ETF","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"ETFConstituentsFrameworkWithDifferentSelectionModelAlgorithm.py"},{"id":"FCT-D3112758","name":"ETFGlobalRotationAlgorithm","description":"ETF","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"ETFGlobalRotationAlgorithm.py"},{"id":"FCT-A3A4BE5B","name":"EmaCrossAlphaModelFrameworkRegressionAlgorithm","description":"Alpha Model","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"EmaCrossAlphaModelFrameworkRegressionAlgorithm.py"},{"id":"FCT-EE365736","name":"EmaCrossFuturesFrontMonthAlgorithm","description":"Futures","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"EmaCrossFuturesFrontMonthAlgorithm.py"},{"id":"FCT-E66F50F9","name":"EmaCrossUniverseSelectionAlgorithm","description":"Universe Selection","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"EmaCrossUniverseSelectionAlgorithm.py"},{"id":"FCT-AE32C215","name":"EmaCrossUniverseSelectionFrameworkAlgorithm","description":"Universe Selection","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"EmaCrossUniverseSelectionFrameworkAlgorithm.py"},{"id":"FCT-62C5A2BF","name":"ExpiryHelperAlphaModelFrameworkAlgorithm","description":"Alpha Model","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"ExpiryHelperAlphaModelFrameworkAlgorithm.py"},{"id":"FCT-47C778A4","name":"ExtendedMarketTradingRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"ExtendedMarketTradingRegressionAlgorithm.py"},{"id":"FCT-E75184B8","name":"FilterUniverseRegressionAlgorithm","description":"Universe Selection","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"FilterUniverseRegressionAlgorithm.py"},{"id":"FCT-F0179E57","name":"FilteredIdentityAlgorithm","description":"General Strategy","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"FilteredIdentityAlgorithm.py"},{"id":"FCT-29D656ED","name":"FinancialAdvisorDemoAlgorithm","description":"General Strategy","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"FinancialAdvisorDemoAlgorithm.py"},{"id":"FCT-BB3C695A","name":"FineFundamentalFilteredUniverseRegressionAlgorithm","description":"Universe Selection","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"FineFundamentalFilteredUniverseRegressionAlgorithm.py"},{"id":"FCT-0212DBCD","name":"ForwardDataOnlyFillModelAlgorithm","description":"General Strategy","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"ForwardDataOnlyFillModelAlgorithm.py"},{"id":"FCT-BA248F90","name":"FractionalQuantityRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"FractionalQuantityRegressionAlgorithm.py"},{"id":"FCT-1C8EF029","name":"FuncRiskFreeRateInterestRateModelWithPythonLambda","description":"Risk Management","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"FuncRiskFreeRateInterestRateModelWithPythonLambda.py"},{"id":"FCT-874367FD","name":"FundamentalCustomSelectionTimeRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"FundamentalCustomSelectionTimeRegressionAlgorithm.py"},{"id":"FCT-4A7607D6","name":"FundamentalRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"FundamentalRegressionAlgorithm.py"},{"id":"FCT-0A8C8781","name":"FundamentalUniverseSelectionAlgorithm","description":"Universe Selection","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"FundamentalUniverseSelectionAlgorithm.py"},{"id":"FCT-19976618","name":"FundamentalUniverseSelectionRegressionAlgorithm","description":"Universe Selection","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"FundamentalUniverseSelectionRegressionAlgorithm.py"},{"id":"FCT-E85797B9","name":"FutureContractsExtendedMarketHoursRegressionAlgorithm","description":"Futures","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"FutureContractsExtendedMarketHoursRegressionAlgorithm.py"},{"id":"FCT-1855F876","name":"FutureOptionBuySellCallIntradayRegressionAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"FutureOptionBuySellCallIntradayRegressionAlgorithm.py"},{"id":"FCT-DE2ACA2C","name":"FutureOptionCallITMExpiryRegressionAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"FutureOptionCallITMExpiryRegressionAlgorithm.py"},{"id":"FCT-B4342086","name":"FutureOptionCallOTMExpiryRegressionAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"FutureOptionCallOTMExpiryRegressionAlgorithm.py"},{"id":"FCT-16536530","name":"FutureOptionDailyRegressionAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"FutureOptionDailyRegressionAlgorithm.py"},{"id":"FCT-BC31D77F","name":"FutureOptionHourlyRegressionAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"FutureOptionHourlyRegressionAlgorithm.py"},{"id":"FCT-AA93FB6A","name":"FutureOptionMultipleContractsInDifferentContractMonthsWithSameUnderlyingFutureRegressionAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"FutureOptionMultipleContractsInDifferentContractMonthsWithSameUnderlyingFutureRegressionAlgorithm.py"},{"id":"FCT-88F9D2E8","name":"FutureOptionPutITMExpiryRegressionAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"FutureOptionPutITMExpiryRegressionAlgorithm.py"},{"id":"FCT-ADF65A2F","name":"FutureOptionPutOTMExpiryRegressionAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"FutureOptionPutOTMExpiryRegressionAlgorithm.py"},{"id":"FCT-129041A8","name":"FutureOptionShortCallITMExpiryRegressionAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"FutureOptionShortCallITMExpiryRegressionAlgorithm.py"},{"id":"FCT-68DA46AE","name":"FutureOptionShortCallOTMExpiryRegressionAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"FutureOptionShortCallOTMExpiryRegressionAlgorithm.py"},{"id":"FCT-97BFC0D6","name":"FutureOptionShortPutITMExpiryRegressionAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"FutureOptionShortPutITMExpiryRegressionAlgorithm.py"},{"id":"FCT-470C1BB3","name":"FutureOptionShortPutOTMExpiryRegressionAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"FutureOptionShortPutOTMExpiryRegressionAlgorithm.py"},{"id":"FCT-119E482D","name":"FutureStopMarketOrderOnExtendedHoursRegressionAlgorithm","description":"Futures","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"FutureStopMarketOrderOnExtendedHoursRegressionAlgorithm.py"},{"id":"FCT-2549D577","name":"FuturesAndFuturesOptionsExpiryTimeAndLiquidationRegressionAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"FuturesAndFuturesOptionsExpiryTimeAndLiquidationRegressionAlgorithm.py"},{"id":"FCT-4EE8D5FD","name":"FuturesExtendedMarketHoursRegressionAlgorithm","description":"Futures","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"FuturesExtendedMarketHoursRegressionAlgorithm.py"},{"id":"FCT-CA7ACD88","name":"FuturesMomentumAlgorithm","description":"Futures","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"FuturesMomentumAlgorithm.py"},{"id":"FCT-7CAB8ED5","name":"G10CurrencySelectionModelFrameworkAlgorithm","description":"General Strategy","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"G10CurrencySelectionModelFrameworkAlgorithm.py"},{"id":"FCT-4F55CFD9","name":"GetParameterRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"GetParameterRegressionAlgorithm.py"},{"id":"FCT-649F439A","name":"HistoricalReturnsAlphaModelFrameworkRegressionAlgorithm","description":"Alpha Model","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"HistoricalReturnsAlphaModelFrameworkRegressionAlgorithm.py"},{"id":"FCT-4F051700","name":"HistoryAlgorithm","description":"Historical Data","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"HistoryAlgorithm.py"},{"id":"FCT-17047AD3","name":"HistoryAuxiliaryDataRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"HistoryAuxiliaryDataRegressionAlgorithm.py"},{"id":"FCT-5077EFC4","name":"HistoryTickRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"HistoryTickRegressionAlgorithm.py"},{"id":"FCT-D55B4B0F","name":"HistoryWithCustomDataSourceRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"HistoryWithCustomDataSourceRegressionAlgorithm.py"},{"id":"FCT-52E3A84A","name":"HistoryWithDifferentContinuousContractDepthOffsetsRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"HistoryWithDifferentContinuousContractDepthOffsetsRegressionAlgorithm.py"},{"id":"FCT-8CB7F1CC","name":"HistoryWithDifferentDataMappingModeRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"HistoryWithDifferentDataMappingModeRegressionAlgorithm.py"},{"id":"FCT-25201E5E","name":"HistoryWithDifferentDataNormalizationModeRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"HistoryWithDifferentDataNormalizationModeRegressionAlgorithm.py"},{"id":"FCT-690AD750","name":"HourReverseSplitRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"HourReverseSplitRegressionAlgorithm.py"},{"id":"FCT-ADDA18D4","name":"HourSplitRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"HourSplitRegressionAlgorithm.py"},{"id":"FCT-5C005A63","name":"ImmediateExecutionModelWorksWithBinanceFeeModel","description":"Execution Model","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"ImmediateExecutionModelWorksWithBinanceFeeModel.py"},{"id":"FCT-BDFB56F1","name":"InceptionDateSelectionRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"InceptionDateSelectionRegressionAlgorithm.py"},{"id":"FCT-5B348FD6","name":"IndexOptionBearCallSpreadAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"IndexOptionBearCallSpreadAlgorithm.py"},{"id":"FCT-F75EB8E2","name":"IndexOptionBearPutSpreadAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"IndexOptionBearPutSpreadAlgorithm.py"},{"id":"FCT-82E65BB4","name":"IndexOptionBullCallSpreadAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"IndexOptionBullCallSpreadAlgorithm.py"},{"id":"FCT-1D8349B6","name":"IndexOptionBullPutSpreadAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"IndexOptionBullPutSpreadAlgorithm.py"},{"id":"FCT-C204FEB8","name":"IndexOptionBuySellCallIntradayRegressionAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"IndexOptionBuySellCallIntradayRegressionAlgorithm.py"},{"id":"FCT-DC3B31DA","name":"IndexOptionCallButterflyAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"IndexOptionCallButterflyAlgorithm.py"},{"id":"FCT-C629FC42","name":"IndexOptionCallCalendarSpreadAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"IndexOptionCallCalendarSpreadAlgorithm.py"},{"id":"FCT-EA1D90BB","name":"IndexOptionCallITMExpiryRegressionAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"IndexOptionCallITMExpiryRegressionAlgorithm.py"},{"id":"FCT-32C0EE95","name":"IndexOptionCallITMGreeksExpiryRegressionAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"IndexOptionCallITMGreeksExpiryRegressionAlgorithm.py"},{"id":"FCT-6AE00A81","name":"IndexOptionCallOTMExpiryRegressionAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"IndexOptionCallOTMExpiryRegressionAlgorithm.py"},{"id":"FCT-F859111A","name":"IndexOptionChainApisConsistencyRegressionAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"IndexOptionChainApisConsistencyRegressionAlgorithm.py"},{"id":"FCT-F5FE9B32","name":"IndexOptionIronCondorAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"IndexOptionIronCondorAlgorithm.py"},{"id":"FCT-02F5AEAE","name":"IndexOptionModelsConsistencyRegressionAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"IndexOptionModelsConsistencyRegressionAlgorithm.py"},{"id":"FCT-BFEF2627","name":"IndexOptionPutButterflyAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"IndexOptionPutButterflyAlgorithm.py"},{"id":"FCT-E0220F96","name":"IndexOptionPutCalendarSpreadAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"IndexOptionPutCalendarSpreadAlgorithm.py"},{"id":"FCT-48BF5359","name":"IndexOptionPutITMExpiryRegressionAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"IndexOptionPutITMExpiryRegressionAlgorithm.py"},{"id":"FCT-4666C54E","name":"IndexOptionPutOTMExpiryRegressionAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"IndexOptionPutOTMExpiryRegressionAlgorithm.py"},{"id":"FCT-300B9FC2","name":"IndexOptionShortCallITMExpiryRegressionAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"IndexOptionShortCallITMExpiryRegressionAlgorithm.py"},{"id":"FCT-57548DAA","name":"IndexOptionShortCallOTMExpiryRegressionAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"IndexOptionShortCallOTMExpiryRegressionAlgorithm.py"},{"id":"FCT-D0643727","name":"IndexOptionShortPutITMExpiryRegressionAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"IndexOptionShortPutITMExpiryRegressionAlgorithm.py"},{"id":"FCT-905BC971","name":"IndexOptionShortPutOTMExpiryRegressionAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"IndexOptionShortPutOTMExpiryRegressionAlgorithm.py"},{"id":"FCT-EB8CE077","name":"IndiaDataRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"IndiaDataRegressionAlgorithm.py"},{"id":"FCT-31D18328","name":"IndicatorExtensionsSMAWithCustomIndicatorsRegressionAlgorithm","description":"Indicators","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"IndicatorExtensionsSMAWithCustomIndicatorsRegressionAlgorithm.py"},{"id":"FCT-2BC353A9","name":"IndicatorHistoryAlgorithm","description":"Indicators","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"IndicatorHistoryAlgorithm.py"},{"id":"FCT-B3C67AEA","name":"IndicatorHistoryRegressionAlgorithm","description":"Indicators","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"IndicatorHistoryRegressionAlgorithm.py"},{"id":"FCT-9EF0798B","name":"IndicatorSelectorsWorkWithDifferentOptions","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"IndicatorSelectorsWorkWithDifferentOptions.py"},{"id":"FCT-71C08CCA","name":"IndicatorSuiteAlgorithm","description":"Indicators","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"IndicatorSuiteAlgorithm.py"},{"id":"FCT-935D3B5D","name":"IndicatorWarmupAlgorithm","description":"Indicators","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"IndicatorWarmupAlgorithm.py"},{"id":"FCT-B8EB6886","name":"IndicatorWithRenkoBarsRegressionAlgorithm","description":"Indicators","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"IndicatorWithRenkoBarsRegressionAlgorithm.py"},{"id":"FCT-77C48AE3","name":"IndustryStandardSecurityIdentifiersRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"IndustryStandardSecurityIdentifiersRegressionAlgorithm.py"},{"id":"FCT-E8E10658","name":"InsightScoringRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"InsightScoringRegressionAlgorithm.py"},{"id":"FCT-15D6B08D","name":"InsightTagAlphaRegressionAlgorithm","description":"Alpha Model","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"InsightTagAlphaRegressionAlgorithm.py"},{"id":"FCT-955EB562","name":"InsightWeightingFrameworkAlgorithm","description":"General Strategy","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"InsightWeightingFrameworkAlgorithm.py"},{"id":"FCT-FD19D095","name":"IronCondorStrategyAlgorithm","description":"General Strategy","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"IronCondorStrategyAlgorithm.py"},{"id":"FCT-8863BE2D","name":"KerasNeuralNetworkAlgorithm","description":"Machine Learning","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"KerasNeuralNetworkAlgorithm.py"},{"id":"FCT-C37858CB","name":"LimitFillRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"LimitFillRegressionAlgorithm.py"},{"id":"FCT-78D0ECA0","name":"LimitIfTouchedRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"LimitIfTouchedRegressionAlgorithm.py"},{"id":"FCT-1E792B32","name":"LiquidETFUniverseFrameworkAlgorithm","description":"ETF","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"LiquidETFUniverseFrameworkAlgorithm.py"},{"id":"FCT-C5F5B3E0","name":"LiveFeaturesAlgorithm","description":"General Strategy","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"LiveFeaturesAlgorithm.py"},{"id":"FCT-EC39F086","name":"LongAndShortButterflyCallStrategiesAlgorithm","description":"General Strategy","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"LongAndShortButterflyCallStrategiesAlgorithm.py"},{"id":"FCT-812F2B68","name":"LongAndShortButterflyPutStrategiesAlgorithm","description":"General Strategy","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"LongAndShortButterflyPutStrategiesAlgorithm.py"},{"id":"FCT-8F4CCF9F","name":"LongAndShortCallCalendarSpreadStrategiesAlgorithm","description":"General Strategy","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"LongAndShortCallCalendarSpreadStrategiesAlgorithm.py"},{"id":"FCT-27A6F4AF","name":"LongAndShortPutCalendarSpreadStrategiesAlgorithm","description":"General Strategy","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"LongAndShortPutCalendarSpreadStrategiesAlgorithm.py"},{"id":"FCT-9BF2DDCB","name":"LongAndShortStraddleStrategiesAlgorithm","description":"General Strategy","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"LongAndShortStraddleStrategiesAlgorithm.py"},{"id":"FCT-73CA6D31","name":"LongAndShortStrangleStrategiesAlgorithm","description":"General Strategy","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"LongAndShortStrangleStrategiesAlgorithm.py"},{"id":"FCT-BEFEB617","name":"LongOnlyAlphaStreamAlgorithm","description":"Alpha Model","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"LongOnlyAlphaStreamAlgorithm.py"},{"id":"FCT-F328066F","name":"MACDTrendAlgorithm","description":"Momentum","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"MACDTrendAlgorithm.py"},{"id":"FCT-EABA6096","name":"MacdAlphaModelFrameworkRegressionAlgorithm","description":"Alpha Model","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"MacdAlphaModelFrameworkRegressionAlgorithm.py"},{"id":"FCT-C0569D9C","name":"ManuallyRemovedConsolidatorsAlgorithm","description":"Data Consolidation","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"ManuallyRemovedConsolidatorsAlgorithm.py"},{"id":"FCT-A4B98519","name":"ManuallySetMarketHoursAndSymbolPropertiesDatabaseEntriesAlgorithm","description":"General Strategy","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"ManuallySetMarketHoursAndSymbolPropertiesDatabaseEntriesAlgorithm.py"},{"id":"FCT-FB2B7755","name":"MarginCallEventsAlgorithm","description":"Margin","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"MarginCallEventsAlgorithm.py"},{"id":"FCT-26E2B07B","name":"MarketImpactSlippageModelRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"MarketImpactSlippageModelRegressionAlgorithm.py"},{"id":"FCT-F8893107","name":"MarketOnCloseOrderBufferExtendedMarketHoursRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"MarketOnCloseOrderBufferExtendedMarketHoursRegressionAlgorithm.py"},{"id":"FCT-74AD11AC","name":"MarketOnCloseOrderBufferRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"MarketOnCloseOrderBufferRegressionAlgorithm.py"},{"id":"FCT-A5E1134A","name":"MarketOnOpenOnCloseAlgorithm","description":"General Strategy","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"MarketOnOpenOnCloseAlgorithm.py"},{"id":"FCT-791ECD54","name":"MaximumDrawdownPercentPerSecurityFrameworkRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"MaximumDrawdownPercentPerSecurityFrameworkRegressionAlgorithm.py"},{"id":"FCT-7A279BE5","name":"MaximumDrawdownPercentPortfolioFrameworkRegressionAlgorithm","description":"Portfolio Management","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"MaximumDrawdownPercentPortfolioFrameworkRegressionAlgorithm.py"},{"id":"FCT-C143732F","name":"MaximumSectorExposureRiskManagementModelFrameworkRegressionAlgorithm","description":"Risk Management","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"MaximumSectorExposureRiskManagementModelFrameworkRegressionAlgorithm.py"},{"id":"FCT-7E35ADAA","name":"MaximumUnrealizedProfitPercentPerSecurityFrameworkRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"MaximumUnrealizedProfitPercentPerSecurityFrameworkRegressionAlgorithm.py"},{"id":"FCT-98AE653C","name":"MeanReversionPortfolioAlgorithm","description":"Portfolio Management","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"MeanReversionPortfolioAlgorithm.py"},{"id":"FCT-C42B3790","name":"MeanVarianceOptimizationFrameworkAlgorithm","description":"General Strategy","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"MeanVarianceOptimizationFrameworkAlgorithm.py"},{"id":"FCT-B8F7654B","name":"MovingAverageCrossAlgorithm","description":"General Strategy","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"MovingAverageCrossAlgorithm.py"},{"id":"FCT-CFDE4C40","name":"MultipleSymbolConsolidationAlgorithm","description":"Data Consolidation","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"MultipleSymbolConsolidationAlgorithm.py"},{"id":"FCT-D2180B48","name":"NLTKSentimentTradingAlgorithm","description":"General Strategy","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"NLTKSentimentTradingAlgorithm.py"},{"id":"FCT-AE6C825A","name":"NakedCallStrategyAlgorithm","description":"General Strategy","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"NakedCallStrategyAlgorithm.py"},{"id":"FCT-82AD115E","name":"NakedPutStrategyAlgorithm","description":"General Strategy","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"NakedPutStrategyAlgorithm.py"},{"id":"FCT-94DBB773","name":"NamedArgumentsRegression","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"NamedArgumentsRegression.py"},{"id":"FCT-994B4750","name":"NoUniverseSelectorRegressionAlgorithm","description":"Universe Selection","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"NoUniverseSelectorRegressionAlgorithm.py"},{"id":"FCT-7F8D7895","name":"NullBuyingPowerOptionBullCallSpreadAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"NullBuyingPowerOptionBullCallSpreadAlgorithm.py"},{"id":"FCT-B9E54A12","name":"NullMarginMultipleOrdersRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"NullMarginMultipleOrdersRegressionAlgorithm.py"},{"id":"FCT-16C48497","name":"NullOptionAssignmentRegressionAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"NullOptionAssignmentRegressionAlgorithm.py"},{"id":"FCT-F5080AAC","name":"NumeraiSignalExportDemonstrationAlgorithm","description":"General Strategy","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"NumeraiSignalExportDemonstrationAlgorithm.py"},{"id":"FCT-6A2A6B6A","name":"ObjectStoreExampleAlgorithm","description":"General Strategy","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"ObjectStoreExampleAlgorithm.py"},{"id":"FCT-5B1C96E9","name":"OnEndOfDayRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"OnEndOfDayRegressionAlgorithm.py"},{"id":"FCT-7E0FD2EB","name":"OnWarmupFinishedNoWarmup","description":"Warmup","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"OnWarmupFinishedNoWarmup.py"},{"id":"FCT-BA4498F3","name":"OnWarmupFinishedRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"OnWarmupFinishedRegressionAlgorithm.py"},{"id":"FCT-370B9F0E","name":"OpenInterestFuturesRegressionAlgorithm","description":"Futures","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"OpenInterestFuturesRegressionAlgorithm.py"},{"id":"FCT-A5BE1849","name":"OptionChainApisConsistencyRegressionAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"OptionChainApisConsistencyRegressionAlgorithm.py"},{"id":"FCT-98E14661","name":"OptionChainConsistencyRegressionAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"OptionChainConsistencyRegressionAlgorithm.py"},{"id":"FCT-A05E4856","name":"OptionChainFullDataRegressionAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"OptionChainFullDataRegressionAlgorithm.py"},{"id":"FCT-662DC1F1","name":"OptionChainProviderAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"OptionChainProviderAlgorithm.py"},{"id":"FCT-1D2112EA","name":"OptionChainedUniverseSelectionModelRegressionAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"OptionChainedUniverseSelectionModelRegressionAlgorithm.py"},{"id":"FCT-90DAF80B","name":"OptionChainsMultipleFullDataRegressionAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"OptionChainsMultipleFullDataRegressionAlgorithm.py"},{"id":"FCT-4E7CF48A","name":"OptionDataNullReferenceRegressionAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"OptionDataNullReferenceRegressionAlgorithm.py"},{"id":"FCT-A9A9EB72","name":"OptionExerciseAssignRegressionAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"OptionExerciseAssignRegressionAlgorithm.py"},{"id":"FCT-CFC8C48B","name":"OptionIndicatorsMirrorContractsRegressionAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"OptionIndicatorsMirrorContractsRegressionAlgorithm.py"},{"id":"FCT-707335FB","name":"OptionIndicatorsRegressionAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"OptionIndicatorsRegressionAlgorithm.py"},{"id":"FCT-62B73DDD","name":"OptionModelsConsistencyRegressionAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"OptionModelsConsistencyRegressionAlgorithm.py"},{"id":"FCT-0FFCB469","name":"OptionOpenInterestRegressionAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"OptionOpenInterestRegressionAlgorithm.py"},{"id":"FCT-9520559C","name":"OptionPriceModelForOptionStylesBaseRegressionAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"OptionPriceModelForOptionStylesBaseRegressionAlgorithm.py"},{"id":"FCT-9884C10F","name":"OptionPriceModelForSupportedAmericanOptionRegressionAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"OptionPriceModelForSupportedAmericanOptionRegressionAlgorithm.py"},{"id":"FCT-B34DCB29","name":"OptionPriceModelForSupportedAmericanOptionTimeSpanWarmupRegressionAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"OptionPriceModelForSupportedAmericanOptionTimeSpanWarmupRegressionAlgorithm.py"},{"id":"FCT-B6D1CB41","name":"OptionPriceModelForSupportedEuropeanOptionRegressionAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"OptionPriceModelForSupportedEuropeanOptionRegressionAlgorithm.py"},{"id":"FCT-6812E1E8","name":"OptionPriceModelForSupportedEuropeanOptionTimeSpanWarmupRegressionAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"OptionPriceModelForSupportedEuropeanOptionTimeSpanWarmupRegressionAlgorithm.py"},{"id":"FCT-03E734EA","name":"OptionPriceModelForUnsupportedAmericanOptionRegressionAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"OptionPriceModelForUnsupportedAmericanOptionRegressionAlgorithm.py"},{"id":"FCT-850F1B89","name":"OptionPriceModelForUnsupportedAmericanOptionTimeSpanWarmupRegressionAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"OptionPriceModelForUnsupportedAmericanOptionTimeSpanWarmupRegressionAlgorithm.py"},{"id":"FCT-C99DFC04","name":"OptionPriceModelForUnsupportedEuropeanOptionRegressionAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"OptionPriceModelForUnsupportedEuropeanOptionRegressionAlgorithm.py"},{"id":"FCT-6FBD513A","name":"OptionPriceModelForUnsupportedEuropeanOptionTimeSpanWarmupRegressionAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"OptionPriceModelForUnsupportedEuropeanOptionTimeSpanWarmupRegressionAlgorithm.py"},{"id":"FCT-8E5F0BE5","name":"OptionRenameRegressionAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"OptionRenameRegressionAlgorithm.py"},{"id":"FCT-D07A1F27","name":"OptionSplitRegressionAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"OptionSplitRegressionAlgorithm.py"},{"id":"FCT-CB64E8E9","name":"OptionStrategyFactoryMethodsBaseAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"OptionStrategyFactoryMethodsBaseAlgorithm.py"},{"id":"FCT-876722D3","name":"OptionUniverseFilterGreeksRegressionAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"OptionUniverseFilterGreeksRegressionAlgorithm.py"},{"id":"FCT-AED01B14","name":"OptionUniverseFilterGreeksShortcutsRegressionAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"OptionUniverseFilterGreeksShortcutsRegressionAlgorithm.py"},{"id":"FCT-62274EA6","name":"OptionUniverseFilterOptionsDataRegressionAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"OptionUniverseFilterOptionsDataRegressionAlgorithm.py"},{"id":"FCT-61D659F8","name":"OptionUniverseHistoryRegressionAlgorithm","description":"Options","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"OptionUniverseHistoryRegressionAlgorithm.py"},{"id":"FCT-D1943028","name":"OrderTicketAssignmentDemoAlgorithm","description":"General Strategy","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"OrderTicketAssignmentDemoAlgorithm.py"},{"id":"FCT-4AD7FFC0","name":"OrderTicketDemoAlgorithm","description":"General Strategy","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"OrderTicketDemoAlgorithm.py"},{"id":"FCT-73AEBCB1","name":"PEP8StyleBasicAlgorithm","description":"General Strategy","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"PEP8StyleBasicAlgorithm.py"},{"id":"FCT-69B21AF4","name":"PandasDataFrameFromMultipleTickTypeTickHistoryRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"PandasDataFrameFromMultipleTickTypeTickHistoryRegressionAlgorithm.py"},{"id":"FCT-C16FBA05","name":"PandasDataFrameHistoryAlgorithm","description":"Historical Data","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"PandasDataFrameHistoryAlgorithm.py"},{"id":"FCT-3D4D4FC7","name":"ParameterizedAlgorithm","description":"General Strategy","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"ParameterizedAlgorithm.py"},{"id":"FCT-6689DBF5","name":"PearsonCorrelationPairsTradingAlphaModelFrameworkAlgorithm","description":"Alpha Model","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"PearsonCorrelationPairsTradingAlphaModelFrameworkAlgorithm.py"},{"id":"FCT-B9E58D2A","name":"PeriodBasedHistoryRequestNotAllowedWithTickResolutionRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"PeriodBasedHistoryRequestNotAllowedWithTickResolutionRegressionAlgorithm.py"},{"id":"FCT-B4A28E80","name":"PortfolioRebalanceOnCustomFuncRegressionAlgorithm","description":"Portfolio Management","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"PortfolioRebalanceOnCustomFuncRegressionAlgorithm.py"},{"id":"FCT-53259B36","name":"PortfolioRebalanceOnDateRulesRegressionAlgorithm","description":"Portfolio Management","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"PortfolioRebalanceOnDateRulesRegressionAlgorithm.py"},{"id":"FCT-1D170EBB","name":"PortfolioTargetTagsRegressionAlgorithm","description":"Portfolio Management","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"PortfolioTargetTagsRegressionAlgorithm.py"},{"id":"FCT-3E91D425","name":"PythonDictionaryFeatureRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"PythonDictionaryFeatureRegressionAlgorithm.py"},{"id":"FCT-3BE1BA87","name":"PytorchNeuralNetworkAlgorithm","description":"Machine Learning","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"PytorchNeuralNetworkAlgorithm.py"},{"id":"FCT-0CB9D7FA","name":"QuitAfterInitializationRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"QuitAfterInitializationRegressionAlgorithm.py"},{"id":"FCT-87512128","name":"QuitInInitializationRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"QuitInInitializationRegressionAlgorithm.py"},{"id":"FCT-052CED9D","name":"RangeConsolidatorAlgorithm","description":"Data Consolidation","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"RangeConsolidatorAlgorithm.py"},{"id":"FCT-0761902F","name":"RangeConsolidatorWithTickAlgorithm","description":"Data Consolidation","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"RangeConsolidatorWithTickAlgorithm.py"},{"id":"FCT-4C4ACA6D","name":"RawDataRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"RawDataRegressionAlgorithm.py"},{"id":"FCT-8426823A","name":"RawPricesCoarseUniverseAlgorithm","description":"Universe Selection","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"RawPricesCoarseUniverseAlgorithm.py"},{"id":"FCT-EEE07C98","name":"RawPricesUniverseRegressionAlgorithm","description":"Universe Selection","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"RawPricesUniverseRegressionAlgorithm.py"},{"id":"FCT-0D15187F","name":"RegisterIndicatorRegressionAlgorithm","description":"Indicators","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"RegisterIndicatorRegressionAlgorithm.py"},{"id":"FCT-D350E387","name":"RegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"RegressionAlgorithm.py"},{"id":"FCT-CB76FD5F","name":"RegressionChannelAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"RegressionChannelAlgorithm.py"},{"id":"FCT-4F8A816B","name":"RiskParityPortfolioAlgorithm","description":"Risk Management","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"RiskParityPortfolioAlgorithm.py"},{"id":"FCT-5A71E57F","name":"RollingWindowAlgorithm","description":"General Strategy","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"RollingWindowAlgorithm.py"},{"id":"FCT-2CBD0408","name":"RsiAlphaModelFrameworkRegressionAlgorithm","description":"Alpha Model","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"RsiAlphaModelFrameworkRegressionAlgorithm.py"},{"id":"FCT-9781F28A","name":"ScheduledEventsAlgorithm","description":"Scheduled Events","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"ScheduledEventsAlgorithm.py"},{"id":"FCT-BC10DFCE","name":"ScheduledQueuingAlgorithm","description":"Scheduled Events","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"ScheduledQueuingAlgorithm.py"},{"id":"FCT-AE6D38CF","name":"ScheduledUniverseRegressionAlgorithm","description":"Universe Selection","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"ScheduledUniverseRegressionAlgorithm.py"},{"id":"FCT-3F154B00","name":"ScheduledUniverseSelectionModelRegressionAlgorithm","description":"Universe Selection","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"ScheduledUniverseSelectionModelRegressionAlgorithm.py"},{"id":"FCT-1244BB8B","name":"ScikitLearnLinearRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"ScikitLearnLinearRegressionAlgorithm.py"},{"id":"FCT-9159A849","name":"SectorExposureRiskFrameworkAlgorithm","description":"Risk Management","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"SectorExposureRiskFrameworkAlgorithm.py"},{"id":"FCT-F578C144","name":"SectorWeightingFrameworkAlgorithm","description":"General Strategy","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"SectorWeightingFrameworkAlgorithm.py"},{"id":"FCT-B0B2E65B","name":"SecurityCustomPropertiesAlgorithm","description":"General Strategy","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"SecurityCustomPropertiesAlgorithm.py"},{"id":"FCT-B2BE2584","name":"SecurityDynamicPropertyPythonClassAlgorithm","description":"General Strategy","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"SecurityDynamicPropertyPythonClassAlgorithm.py"},{"id":"FCT-79957FB5","name":"SecuritySeederRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"SecuritySeederRegressionAlgorithm.py"},{"id":"FCT-BCEB1931","name":"SelectUniverseSymbolsFromIDRegressionAlgorithm","description":"Universe Selection","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"SelectUniverseSymbolsFromIDRegressionAlgorithm.py"},{"id":"FCT-86D91C89","name":"SetCustomSettlementModelRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"SetCustomSettlementModelRegressionAlgorithm.py"},{"id":"FCT-D64ED04F","name":"SetEquityDataNormalizationModeOnAddEquity","description":"General Strategy","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"SetEquityDataNormalizationModeOnAddEquity.py"},{"id":"FCT-36FF2819","name":"SetHoldingsLiquidateExistingHoldingsMultipleTargetsRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"SetHoldingsLiquidateExistingHoldingsMultipleTargetsRegressionAlgorithm.py"},{"id":"FCT-5A449593","name":"SetHoldingsMultipleTargetsRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"SetHoldingsMultipleTargetsRegressionAlgorithm.py"},{"id":"FCT-58C330FF","name":"SetHoldingsRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"SetHoldingsRegressionAlgorithm.py"},{"id":"FCT-EFDED6A6","name":"ShortableProviderOrdersRejectedRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"ShortableProviderOrdersRejectedRegressionAlgorithm.py"},{"id":"FCT-198E83AF","name":"SliceGetByTypeRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"SliceGetByTypeRegressionAlgorithm.py"},{"id":"FCT-9D3D6D8F","name":"SmaCrossUniverseSelectionAlgorithm","description":"Universe Selection","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"SmaCrossUniverseSelectionAlgorithm.py"},{"id":"FCT-E4FEA7D1","name":"SpreadExecutionModelRegressionAlgorithm","description":"Execution Model","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"SpreadExecutionModelRegressionAlgorithm.py"},{"id":"FCT-5C2FCFA1","name":"StableCoinsRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"StableCoinsRegressionAlgorithm.py"},{"id":"FCT-C7F868BA","name":"StandardDeviationExecutionModelRegressionAlgorithm","description":"Execution Model","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"StandardDeviationExecutionModelRegressionAlgorithm.py"},{"id":"FCT-99B5F510","name":"StatisticsResultsAlgorithm","description":"General Strategy","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"StatisticsResultsAlgorithm.py"},{"id":"FCT-1A300907","name":"StochasticIndicatorWarmsUpProperlyRegressionAlgorithm","description":"Indicators","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"StochasticIndicatorWarmsUpProperlyRegressionAlgorithm.py"},{"id":"FCT-58C9B30E","name":"StopLimitOrderRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"StopLimitOrderRegressionAlgorithm.py"},{"id":"FCT-8FAFCC5D","name":"StringToSymbolImplicitConversionRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"StringToSymbolImplicitConversionRegressionAlgorithm.py"},{"id":"FCT-D0F1B141","name":"TalibIndicatorsAlgorithm","description":"Indicators","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"TalibIndicatorsAlgorithm.py"},{"id":"FCT-42FC8E69","name":"TensorFlowNeuralNetworkAlgorithm","description":"Machine Learning","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"TensorFlowNeuralNetworkAlgorithm.py"},{"id":"FCT-84B15249","name":"TickDataFilteringAlgorithm","description":"General Strategy","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"TickDataFilteringAlgorithm.py"},{"id":"FCT-824A47D1","name":"TickHistoryRequestWithoutTickSubscriptionRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"TickHistoryRequestWithoutTickSubscriptionRegressionAlgorithm.py"},{"id":"FCT-B0BD73CA","name":"TiingoPriceAlgorithm","description":"General Strategy","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"TiingoPriceAlgorithm.py"},{"id":"FCT-F8E8016B","name":"TimeInForceAlgorithm","description":"General Strategy","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"TimeInForceAlgorithm.py"},{"id":"FCT-76B63DA7","name":"TrailingStopOrderRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"TrailingStopOrderRegressionAlgorithm.py"},{"id":"FCT-DD7ECCB4","name":"TrailingStopRiskFrameworkRegressionAlgorithm","description":"Risk Management","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"TrailingStopRiskFrameworkRegressionAlgorithm.py"},{"id":"FCT-4F56A3E5","name":"TrainingExampleAlgorithm","description":"General Strategy","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"TrainingExampleAlgorithm.py"},{"id":"FCT-95DFEFEB","name":"TrainingInitializeRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"TrainingInitializeRegressionAlgorithm.py"},{"id":"FCT-FED4E182","name":"TwoLegCurrencyConversionRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"TwoLegCurrencyConversionRegressionAlgorithm.py"},{"id":"FCT-953A6967","name":"UniverseOnlyRegressionAlgorithm","description":"Universe Selection","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"UniverseOnlyRegressionAlgorithm.py"},{"id":"FCT-BAF35694","name":"UniverseSelectedRegressionAlgorithm","description":"Universe Selection","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"UniverseSelectedRegressionAlgorithm.py"},{"id":"FCT-DBD4926F","name":"UniverseSelectionDefinitionsAlgorithm","description":"Universe Selection","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"UniverseSelectionDefinitionsAlgorithm.py"},{"id":"FCT-E51F70E4","name":"UniverseSelectionRegressionAlgorithm","description":"Universe Selection","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"UniverseSelectionRegressionAlgorithm.py"},{"id":"FCT-91035E43","name":"UniverseUnchangedRegressionAlgorithm","description":"Universe Selection","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"UniverseUnchangedRegressionAlgorithm.py"},{"id":"FCT-D8849489","name":"UnregisterIndicatorRegressionAlgorithm","description":"Indicators","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"UnregisterIndicatorRegressionAlgorithm.py"},{"id":"FCT-BFC09E5D","name":"UpdateOrderRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"UpdateOrderRegressionAlgorithm.py"},{"id":"FCT-90E557F4","name":"UserDefinedUniverseAlgorithm","description":"Universe Selection","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"UserDefinedUniverseAlgorithm.py"},{"id":"FCT-253853F6","name":"VolumeRenkoConsolidatorAlgorithm","description":"Data Consolidation","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"VolumeRenkoConsolidatorAlgorithm.py"},{"id":"FCT-8D857005","name":"VolumeShareSlippageModelAlgorithm","description":"General Strategy","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"VolumeShareSlippageModelAlgorithm.py"},{"id":"FCT-2D03F945","name":"VolumeWeightedAveragePriceExecutionModelRegressionAlgorithm","description":"Execution Model","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"VolumeWeightedAveragePriceExecutionModelRegressionAlgorithm.py"},{"id":"FCT-DB342081","name":"WarmupAlgorithm","description":"Warmup","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"WarmupAlgorithm.py"},{"id":"FCT-E048C42D","name":"WarmupHistoryAlgorithm","description":"Warmup","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"WarmupHistoryAlgorithm.py"},{"id":"FCT-161A4DE8","name":"WeeklyUniverseSelectionRegressionAlgorithm","description":"Universe Selection","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"WeeklyUniverseSelectionRegressionAlgorithm.py"},{"id":"FCT-F69688F5","name":"ZeroedBenchmarkRegressionAlgorithm","description":"Regression Test","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"ZeroedBenchmarkRegressionAlgorithm.py"},{"id":"FCT-FAD58DE7","name":"main","description":"General Strategy","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"main.py"},{"id":"FCT-70CBDC3D","name":"ContingentClaimsAnalysisDefaultPredictionAlpha","description":"Alpha Model","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"alphas/ContingentClaimsAnalysisDefaultPredictionAlpha.py"},{"id":"FCT-9D7FFCA4","name":"GasAndCrudeOilEnergyCorrelationAlpha","description":"Alpha Model","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"alphas/GasAndCrudeOilEnergyCorrelationAlpha.py"},{"id":"FCT-C3B2CF90","name":"GlobalEquityMeanReversionIBSAlpha","description":"Alpha Model","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"alphas/GlobalEquityMeanReversionIBSAlpha.py"},{"id":"FCT-46661FE6","name":"GreenblattMagicFormulaAlpha","description":"Alpha Model","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"alphas/GreenblattMagicFormulaAlpha.py"},{"id":"FCT-5596A325","name":"IntradayReversalCurrencyMarketsAlpha","description":"Alpha Model","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"alphas/IntradayReversalCurrencyMarketsAlpha.py"},{"id":"FCT-EAEEE69C","name":"MeanReversionLunchBreakAlpha","description":"Alpha Model","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"alphas/MeanReversionLunchBreakAlpha.py"},{"id":"FCT-B86663BE","name":"MortgageRateVolatilityAlpha","description":"Alpha Model","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"alphas/MortgageRateVolatilityAlpha.py"},{"id":"FCT-899805AE","name":"PriceGapMeanReversionAlpha","description":"Alpha Model","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"alphas/PriceGapMeanReversionAlpha.py"},{"id":"FCT-41404465","name":"RebalancingLeveragedETFAlpha","description":"Alpha Model","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"alphas/RebalancingLeveragedETFAlpha.py"},{"id":"FCT-B44500AA","name":"ShareClassMeanReversionAlpha","description":"Alpha Model","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"alphas/ShareClassMeanReversionAlpha.py"},{"id":"FCT-EEAA6B87","name":"SykesShortMicroCapAlpha","description":"Alpha Model","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"alphas/SykesShortMicroCapAlpha.py"},{"id":"FCT-217A291D","name":"TriangleExchangeRateArbitrageAlpha","description":"Alpha Model","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"alphas/TriangleExchangeRateArbitrageAlpha.py"},{"id":"FCT-A6C1E2B9","name":"TripleLeverageETFPairVolatilityDecayAlpha","description":"Alpha Model","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"alphas/TripleLeverageETFPairVolatilityDecayAlpha.py"},{"id":"FCT-7DFAE1BB","name":"VIXDualThrustAlpha","description":"Alpha Model","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"alphas/VIXDualThrustAlpha.py"},{"id":"FCT-B103DBA0","name":"BasicTemplateBenchmark","description":"Benchmark","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"benchmarks/BasicTemplateBenchmark.py"},{"id":"FCT-5B90E12B","name":"CoarseFineUniverseSelectionBenchmark","description":"Benchmark","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"benchmarks/CoarseFineUniverseSelectionBenchmark.py"},{"id":"FCT-9C878F2C","name":"EmptyEquityAndOptions400Benchmark","description":"Benchmark","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"benchmarks/EmptyEquityAndOptions400Benchmark.py"},{"id":"FCT-1E0D28D7","name":"EmptyMinute400EquityBenchmark","description":"Benchmark","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"benchmarks/EmptyMinute400EquityBenchmark.py"},{"id":"FCT-9BA28BE5","name":"EmptySingleSecuritySecondEquityBenchmark","description":"Benchmark","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"benchmarks/EmptySingleSecuritySecondEquityBenchmark.py"},{"id":"FCT-0C67D5F6","name":"HistoryRequestBenchmark","description":"Benchmark","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"benchmarks/HistoryRequestBenchmark.py"},{"id":"FCT-D5F0AB7B","name":"IndicatorRibbonBenchmark","description":"Benchmark","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"benchmarks/IndicatorRibbonBenchmark.py"},{"id":"FCT-5F7C7101","name":"ScheduledEventsBenchmark","description":"Benchmark","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"benchmarks/ScheduledEventsBenchmark.py"},{"id":"FCT-FA9F3E6A","name":"StatefulCoarseUniverseSelectionBenchmark","description":"Benchmark","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"benchmarks/StatefulCoarseUniverseSelectionBenchmark.py"},{"id":"FCT-D12D8ED1","name":"StatelessCoarseUniverseSelectionBenchmark","description":"Benchmark","timeframe":"1d","entry_conditions":[],"exit_conditions":[],"entry_logic":"AND","exit_logic":"AND","stop_loss":0,"take_profit":0,"trailing_stop":0,"script_path":"benchmarks/StatelessCoarseUniverseSelectionBenchmark.py"}]}
\ No newline at end of file
diff --git a/fincept-qt/scripts/strategies/test_strategies.py b/fincept-qt/scripts/strategies/test_strategies.py
deleted file mode 100644
index 4e03801eb..000000000
--- a/fincept-qt/scripts/strategies/test_strategies.py
+++ /dev/null
@@ -1,153 +0,0 @@
-#!/usr/bin/env python3
-"""
-Fincept Terminal - Strategy Test Suite
-Tests all strategies for import/instantiation/initialization errors.
-"""
-import os
-import sys
-import importlib
-import traceback
-
-# Set up path
-SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
-if SCRIPT_DIR not in sys.path:
- sys.path.insert(0, SCRIPT_DIR)
-
-# Import the framework first to ensure stubs are registered
-try:
- from AlgorithmImports import *
- print("OK: AlgorithmImports loaded successfully")
-except Exception as e:
- print(f"FATAL: AlgorithmImports failed to load: {e}")
- traceback.print_exc()
- sys.exit(1)
-
-# Strategy files to test (all .py files in the strategies directory, excluding infrastructure)
-EXCLUDE = {
- '__init__', '_registry', 'AlgorithmImports', 'main', 'test_strategies',
- 'live_runner'
-}
-
-def get_strategy_files():
- """Collect all strategy .py files."""
- strategies = []
- # Top-level strategies
- for f in sorted(os.listdir(SCRIPT_DIR)):
- if f.endswith('.py') and not f.startswith('_') and f[:-3] not in EXCLUDE:
- strategies.append(('', f[:-3]))
- # Subdirectory strategies (alphas, benchmarks, Execution, Portfolio, Risk, Selection)
- for subdir in ['alphas', 'benchmarks', 'Execution', 'Portfolio', 'Risk', 'Selection', 'Alphas']:
- subpath = os.path.join(SCRIPT_DIR, subdir)
- if os.path.isdir(subpath):
- for f in sorted(os.listdir(subpath)):
- if f.endswith('.py') and not f.startswith('_'):
- strategies.append((subdir, f[:-3]))
- return strategies
-
-def test_strategy_import(subdir, module_name):
- """Test that a strategy module can be imported and its class instantiated."""
- errors = []
-
- # Build the module path
- if subdir:
- full_module = f"{subdir}.{module_name}"
- file_path = os.path.join(SCRIPT_DIR, subdir, f"{module_name}.py")
- else:
- full_module = module_name
- file_path = os.path.join(SCRIPT_DIR, f"{module_name}.py")
-
- # Phase 1: Import the module
- try:
- if subdir:
- # For subdirectory modules, use importlib with spec
- spec = importlib.util.spec_from_file_location(full_module, file_path)
- mod = importlib.util.module_from_spec(spec)
- spec.loader.exec_module(mod)
- else:
- spec = importlib.util.spec_from_file_location(module_name, file_path)
- mod = importlib.util.module_from_spec(spec)
- spec.loader.exec_module(mod)
- except Exception as e:
- tb = traceback.format_exc()
- return [('IMPORT', str(e), tb)]
-
- # Phase 2: Find and instantiate the algorithm class
- algo_classes = []
- for name in dir(mod):
- obj = getattr(mod, name)
- if (isinstance(obj, type)
- and issubclass(obj, QCAlgorithm)
- and obj is not QCAlgorithm
- and obj.__module__ != 'fincept_engine.algorithm'):
- algo_classes.append((name, obj))
-
- if not algo_classes:
- # Not necessarily an error - some files are base classes or utilities
- return []
-
- for class_name, cls in algo_classes:
- try:
- instance = cls()
- except Exception as e:
- tb = traceback.format_exc()
- errors.append(('INSTANTIATE', f"{class_name}: {e}", tb))
- continue
-
- # Phase 3: Try calling initialize() if it exists
- if hasattr(instance, 'initialize'):
- try:
- instance.initialize()
- except Exception as e:
- tb = traceback.format_exc()
- errors.append(('INITIALIZE', f"{class_name}.initialize(): {e}", tb))
-
- return errors
-
-
-def main():
- strategies = get_strategy_files()
- print(f"\nTesting {len(strategies)} strategy files...\n")
- print("=" * 80)
-
- passed = 0
- failed = 0
- failures = []
-
- for subdir, module_name in strategies:
- display_name = f"{subdir}/{module_name}" if subdir else module_name
- errors = test_strategy_import(subdir, module_name)
-
- if errors:
- failed += 1
- for phase, msg, tb in errors:
- failures.append((display_name, phase, msg, tb))
- print(f"FAIL [{phase}]: {display_name}")
- print(f" Error: {msg}")
- # Print just the last few lines of traceback
- tb_lines = tb.strip().split('\n')
- for line in tb_lines[-4:]:
- print(f" {line}")
- print()
- else:
- passed += 1
- # Only print passes for verification
- # print(f"PASS: {display_name}")
-
- print("=" * 80)
- print(f"\nRESULTS: {passed} passed, {failed} failed out of {len(strategies)} total")
- print()
-
- if failures:
- print("=" * 80)
- print("FAILURE SUMMARY")
- print("=" * 80)
- for i, (name, phase, msg, tb) in enumerate(failures, 1):
- print(f"\n{i}. {name} [{phase}]")
- print(f" Error: {msg}")
- print()
-
- return failed
-
-
-if __name__ == '__main__':
- sys.exit(main())
diff --git a/fincept-qt/src/algo_engine/BacktestEngine.cpp b/fincept-qt/src/algo_engine/BacktestEngine.cpp
index 425ff9d7d..6519c8b6c 100644
--- a/fincept-qt/src/algo_engine/BacktestEngine.cpp
+++ b/fincept-qt/src/algo_engine/BacktestEngine.cpp
@@ -2,6 +2,9 @@
#include "algo_engine/BacktestEngine.h"
#include "algo_engine/ConditionEvaluator.h"
+#include "core/logging/Logger.h"
+
+#include <QDateTime>
#include <algorithm>
#include <cmath>
@@ -43,8 +46,10 @@ QJsonObject BacktestEngine::run(const QVector<OhlcvCandle>& candles,
const QJsonArray& entry_conditions, const QString& entry_logic,
const QJsonArray& exit_conditions, const QString& exit_logic,
double stop_loss_pct, double take_profit_pct, double trailing_stop_pct,
- double initial_capital, const QString& timeframe) {
+ double initial_capital, const QString& timeframe,
+ double position_size_pct) {
const int n = candles.size();
+ const double size_frac = std::clamp(position_size_pct, 1.0, 100.0) / 100.0;
if (n < kWarmupBars + 10) {
QJsonObject err;
err["success"] = false;
@@ -54,6 +59,20 @@ QJsonObject BacktestEngine::run(const QVector<OhlcvCandle>& candles,
return err;
}
+ LOG_INFO("Backtest", QString("run: candles=%1 tf=%2 entryConds=%3 exitConds=%4 sl=%5 tp=%6 sizePct=%7")
+ .arg(n)
+ .arg(timeframe)
+ .arg(entry_conditions.size())
+ .arg(exit_conditions.size())
+ .arg(stop_loss_pct)
+ .arg(take_profit_pct)
+ .arg(position_size_pct));
+
+ // ── Diagnostics ──────────────────────────────────────────────────────────
+ int entry_eval_count = 0, entry_true_count = 0, exit_true_count = 0, entry_err_count = 0;
+ QString last_entry_err;
+ bool entry_sampled = false;
+
double cash = initial_capital;
bool in_pos = false;
double entry_price = 0.0;
@@ -68,6 +87,10 @@ QJsonObject BacktestEngine::run(const QVector<OhlcvCandle>& candles,
QJsonArray trades;
QVector<double> equity_curve;
equity_curve.reserve(n - kWarmupBars);
+ // Buy-&-hold benchmark: invest all capital at the first evaluated bar's close.
+ QVector<double> benchmark_curve;
+ benchmark_curve.reserve(n - kWarmupBars);
+ const double bench_base = candles[kWarmupBars].close;
double peak_equity = initial_capital;
double max_dd = 0.0;
@@ -96,7 +119,7 @@ QJsonObject BacktestEngine::run(const QVector<OhlcvCandle>& candles,
// ── 1. Execute pending signal fills at THIS bar's open ──────────────
if (!in_pos && entry_signal) {
const double px = bar.open;
- const long long qty = px > 0 ? static_cast<long long>(std::floor(cash / px)) : 0;
+ const long long qty = px > 0 ? static_cast<long long>(std::floor(cash * size_frac / px)) : 0;
if (qty > 0) {
in_pos = true;
entry_price = px;
@@ -140,16 +163,43 @@ QJsonObject BacktestEngine::run(const QVector<OhlcvCandle>& candles,
const int start = std::max(0, i - kEvalWindow + 1);
const QVector<OhlcvCandle> window = candles.mid(start, i - start + 1);
if (!in_pos && !entry_signal && !entry_conditions.isEmpty()) {
- if (ConditionEvaluator::evaluate_group(entry_conditions, entry_logic, window).triggered)
+ const auto g = ConditionEvaluator::evaluate_group(entry_conditions, entry_logic, window);
+ ++entry_eval_count;
+ if (g.triggered) {
entry_signal = true;
+ ++entry_true_count;
+ }
+ for (const auto& d : g.details)
+ if (!d.error.isEmpty()) {
+ ++entry_err_count;
+ if (last_entry_err.isEmpty())
+ last_entry_err = d.error;
+ }
+ // Snapshot the first evaluation where the LHS operand is actually computed
+ // (past indicator warm-up) so we can see real operand values vs targets.
+ if (!entry_sampled && !g.details.isEmpty() && !std::isnan(g.details.first().computed_value)) {
+ entry_sampled = true;
+ for (const auto& d : g.details)
+ LOG_INFO("Backtest",
+ QString(" entry[bar %1] %2.%3 %4 lhs=%5 rhs=%6 met=%7 err=%8")
+ .arg(i)
+ .arg(d.indicator, d.field, d.op)
+ .arg(d.computed_value)
+ .arg(d.target_value)
+ .arg(d.met ? QStringLiteral("Y") : QStringLiteral("N"))
+ .arg(d.error));
+ }
} else if (in_pos && !exit_signal && !exit_conditions.isEmpty()) {
- if (ConditionEvaluator::evaluate_group(exit_conditions, exit_logic, window).triggered)
+ if (ConditionEvaluator::evaluate_group(exit_conditions, exit_logic, window).triggered) {
exit_signal = true;
+ ++exit_true_count;
+ }
}
// ── 4. Mark-to-market equity on close ───────────────────────────────
const double equity = cash + (in_pos ? static_cast<double>(shares) * bar.close : 0.0);
equity_curve.append(equity);
+ benchmark_curve.append(bench_base > 0 ? initial_capital * bar.close / bench_base : initial_capital);
if (equity > peak_equity)
peak_equity = equity;
const double dd = peak_equity > 0 ? (peak_equity - equity) / peak_equity * 100.0 : 0.0;
@@ -161,6 +211,15 @@ QJsonObject BacktestEngine::run(const QVector<OhlcvCandle>& candles,
if (in_pos)
close_trade(candles[n - 1].close, "end_of_data", n - 1);
+ LOG_INFO("Backtest",
+ QString("done: evalBars=%1 entryTrue=%2 exitTrue=%3 entryErr=%4 trades=%5 lastErr='%6'")
+ .arg(entry_eval_count)
+ .arg(entry_true_count)
+ .arg(exit_true_count)
+ .arg(entry_err_count)
+ .arg(trades.size())
+ .arg(last_entry_err));
+
// ── Metrics ─────────────────────────────────────────────────────────────
const int total_trades = trades.size();
const double final_value = cash;
@@ -184,7 +243,13 @@ QJsonObject BacktestEngine::run(const QVector<OhlcvCandle>& candles,
out["profit_factor"] = 0.0;
out["sharpe_ratio"] = 0.0;
out["sharpe"] = 0.0;
+ out["sortino"] = 0.0;
+ out["calmar"] = 0.0;
+ out["expectancy"] = 0.0;
out["equity_curve"] = QJsonArray();
+ out["benchmark_curve"] = QJsonArray();
+ out["benchmark_return"] = 0.0;
+ out["monthly_returns"] = QJsonArray();
out["trades"] = trades;
return out;
}
@@ -217,8 +282,10 @@ QJsonObject BacktestEngine::run(const QVector<OhlcvCandle>& candles,
if (profit_factor > 999.99)
profit_factor = 999.99;
- // Sharpe from equity-curve point-to-point returns, annualised by timeframe.
+ // Sharpe & Sortino from equity-curve point-to-point returns, annualised by
+ // timeframe. Calmar = annualised-ish return over max drawdown.
double sharpe = 0.0;
+ double sortino = 0.0;
if (equity_curve.size() > 1) {
QVector<double> rets;
rets.reserve(equity_curve.size() - 1);
@@ -231,30 +298,71 @@ QJsonObject BacktestEngine::run(const QVector<OhlcvCandle>& candles,
for (double r : rets)
mean += r;
mean /= rets.size();
- double var = 0.0;
- for (double r : rets)
+ double var = 0.0, dvar = 0.0;
+ for (double r : rets) {
var += (r - mean) * (r - mean);
+ if (r < 0.0)
+ dvar += r * r; // downside-only second moment
+ }
var /= rets.size();
+ dvar /= rets.size();
const double sd = std::sqrt(var);
+ const double dsd = std::sqrt(dvar);
+ const double ann = std::sqrt(bars_per_year(timeframe));
if (sd > 0.0)
- sharpe = (mean / sd) * std::sqrt(bars_per_year(timeframe));
+ sharpe = (mean / sd) * ann;
+ if (dsd > 0.0)
+ sortino = (mean / dsd) * ann;
}
}
+ const double calmar = (max_dd > 0.0) ? (total_return_pct / max_dd) : 0.0;
- // Downsample equity curve to <= 500 points (keep last point).
- QJsonArray equity_out;
- if (equity_curve.size() > 500) {
- const int step = equity_curve.size() / 500;
- for (int i = 0; i < equity_curve.size(); i += step)
+ // Downsample equity + buy-&-hold benchmark to <= 500 aligned points (keep last).
+ QJsonArray equity_out, benchmark_out;
+ {
+ const int sz = equity_curve.size();
+ const int step = sz > 500 ? sz / 500 : 1;
+ for (int i = 0; i < sz; i += step) {
equity_out.append(round_to(equity_curve[i], 2));
- if (equity_out.isEmpty() ||
- equity_out.last().toDouble() != round_to(equity_curve.last(), 2))
+ benchmark_out.append(round_to(benchmark_curve[i], 2));
+ }
+ if (sz > 0 && equity_out.last().toDouble() != round_to(equity_curve.last(), 2)) {
equity_out.append(round_to(equity_curve.last(), 2));
- } else {
- for (double e : equity_curve)
- equity_out.append(round_to(e, 2));
+ benchmark_out.append(round_to(benchmark_curve.last(), 2));
+ }
}
+ // Per-calendar-month returns of the strategy equity (for the heatmap).
+ QJsonArray monthly_returns;
+ {
+ QString cur_month;
+ bool have_month = false;
+ double month_end = initial_capital;
+ double prev_month_end = initial_capital;
+ auto flush = [&](const QString& label) {
+ const double ret = prev_month_end > 0 ? (month_end - prev_month_end) / prev_month_end * 100.0 : 0.0;
+ QJsonObject m;
+ m["month"] = label;
+ m["return"] = round_to(ret, 2);
+ monthly_returns.append(m);
+ prev_month_end = month_end;
+ };
+ for (int j = 0; j < equity_curve.size(); ++j) {
+ const QString ym =
+ QDateTime::fromMSecsSinceEpoch(candles[kWarmupBars + j].open_time, Qt::UTC).toString("yyyy-MM");
+ if (have_month && ym != cur_month)
+ flush(cur_month);
+ cur_month = ym;
+ have_month = true;
+ month_end = equity_curve[j];
+ }
+ if (have_month)
+ flush(cur_month);
+ }
+
+ const double bench_final = benchmark_curve.isEmpty() ? initial_capital : benchmark_curve.last();
+ const double bench_return_pct = initial_capital > 0 ? (bench_final - initial_capital) / initial_capital * 100.0 : 0.0;
+
out["total_trades"] = total_trades;
out["winning_trades"] = wins;
out["losing_trades"] = losses;
@@ -268,7 +376,13 @@ QJsonObject BacktestEngine::run(const QVector<OhlcvCandle>& candles,
out["profit_factor"] = round_to(profit_factor, 2);
out["sharpe_ratio"] = round_to(sharpe, 3); // panel reads sharpe_ratio
out["sharpe"] = round_to(sharpe, 3); // alias
+ out["sortino"] = round_to(sortino, 3);
+ out["calmar"] = round_to(calmar, 2);
+ out["expectancy"] = round_to(avg_pnl, 2); // avg P&L per trade
out["equity_curve"] = equity_out;
+ out["benchmark_curve"] = benchmark_out;
+ out["benchmark_return"] = round_to(bench_return_pct, 2);
+ out["monthly_returns"] = monthly_returns;
out["trades"] = trades;
return out;
}
diff --git a/fincept-qt/src/algo_engine/BacktestEngine.h b/fincept-qt/src/algo_engine/BacktestEngine.h
index 8d33886c6..2aa99a747 100644
--- a/fincept-qt/src/algo_engine/BacktestEngine.h
+++ b/fincept-qt/src/algo_engine/BacktestEngine.h
@@ -30,7 +30,8 @@ public:
const QJsonArray& entry_conditions, const QString& entry_logic,
const QJsonArray& exit_conditions, const QString& exit_logic,
double stop_loss_pct, double take_profit_pct, double trailing_stop_pct,
- double initial_capital, const QString& timeframe);
+ double initial_capital, const QString& timeframe,
+ double position_size_pct = 100.0);
};
} // namespace fincept::algo
diff --git a/fincept-qt/src/algo_engine/CandleDataFetcher.cpp b/fincept-qt/src/algo_engine/CandleDataFetcher.cpp
index 1cc875e69..9a0ddd8c0 100644
--- a/fincept-qt/src/algo_engine/CandleDataFetcher.cpp
+++ b/fincept-qt/src/algo_engine/CandleDataFetcher.cpp
@@ -438,10 +438,9 @@ void CandleDataFetcher::fetch_from_yahoo(const QStringList& symbols, const QStri
.arg(yi.interval);
QNetworkRequest req{QUrl(url)};
- // Yahoo blocks non-browser User-Agents — present a realistic one.
- req.setHeader(QNetworkRequest::UserAgentHeader,
- "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 "
- "(KHTML, like Gecko) Chrome/120.0 Safari/537.36");
+ // Yahoo's chart endpoint 429s detailed browser UA strings (and python-requests),
+ // but accepts a bare "Mozilla/5.0" — verified empirically.
+ req.setHeader(QNetworkRequest::UserAgentHeader, "Mozilla/5.0");
req.setRawHeader("Accept", "application/json");
QPointer<CandleDataFetcher> self = this;
diff --git a/fincept-qt/src/algo_engine/ConditionEvaluator.cpp b/fincept-qt/src/algo_engine/ConditionEvaluator.cpp
index afeed9182..e04a511be 100644
--- a/fincept-qt/src/algo_engine/ConditionEvaluator.cpp
+++ b/fincept-qt/src/algo_engine/ConditionEvaluator.cpp
@@ -3,10 +3,22 @@
#include <QJsonObject>
+#include <cmath>
+#include <limits>
+
namespace fincept::algo {
using services::algo::ConditionDef;
+namespace {
+constexpr double kNaN = std::numeric_limits<double>::quiet_NaN();
+
+bool op_needs_prev(const QString& op) {
+ return op == "crosses_above" || op == "crosses_below" ||
+ op == "rising" || op == "falling";
+}
+} // namespace
+
ConditionDef ConditionEvaluator::parse_condition(const QJsonObject& obj) {
ConditionDef c;
c.indicator = obj.value("indicator").toString();
@@ -14,14 +26,22 @@ ConditionDef ConditionEvaluator::parse_condition(const QJsonObject& obj) {
c.field = obj.value("field").toString("value");
c.op = obj.value("operator").toString(">");
c.value = obj.value("value").toDouble(0);
+ c.value2 = obj.value("value2").toDouble(0);
c.compare_mode = obj.value("compare_mode").toString("value");
c.compare_indicator = obj.value("compare_indicator").toString();
c.compare_params = obj.value("compare_params").toObject();
c.compare_field = obj.value("compare_field").toString("value");
+ c.offset = obj.value("offset").toInt(0);
+ c.compare_offset = obj.value("compare_offset").toInt(0);
return c;
}
+bool ConditionEvaluator::is_group_node(const QJsonObject& node) {
+ return node.contains("children") || node.value("type").toString() == "group";
+}
+
bool ConditionEvaluator::apply_comparison(double lhs, const QString& op, double rhs) {
+ if (std::isnan(lhs) || std::isnan(rhs)) return false;
if (op == ">") return lhs > rhs;
if (op == "<") return lhs < rhs;
if (op == ">=") return lhs >= rhs;
@@ -33,6 +53,9 @@ bool ConditionEvaluator::apply_comparison(double lhs, const QString& op, double
bool ConditionEvaluator::apply_crossing(double curr, double prev,
double target_curr, double target_prev,
const QString& op) {
+ if (std::isnan(curr) || std::isnan(prev) ||
+ std::isnan(target_curr) || std::isnan(target_prev))
+ return false;
if (op == "crosses_above")
return prev <= target_prev && curr > target_curr;
if (op == "crosses_below")
@@ -40,11 +63,24 @@ bool ConditionEvaluator::apply_crossing(double curr, double prev,
return false;
}
-bool ConditionEvaluator::apply_trend(const QVector<double>& /*values*/,
- int /*count*/, const QString& /*op*/) {
- // Simplified: compare last two values
- // A more sophisticated version would check N consecutive bars
- return false;
+double ConditionEvaluator::operand_value(const QString& indicator, const QJsonObject& params,
+ const QString& field, int offset,
+ const QVector<OhlcvCandle>& candles, QString* error) {
+ if (offset < 0) offset = 0;
+ QVector<OhlcvCandle> window = candles;
+ if (offset > 0) {
+ if (offset >= candles.size()) {
+ if (error) *error = QStringLiteral("insufficient data for offset %1").arg(offset);
+ return kNaN;
+ }
+ window = candles.mid(0, candles.size() - offset);
+ }
+ auto r = IndicatorEngine::compute(indicator, window, params, field);
+ if (!r.valid) {
+ if (error) *error = r.error;
+ return kNaN;
+ }
+ return r.current.value(field, kNaN);
}
ConditionResult ConditionEvaluator::evaluate_single(
@@ -56,88 +92,97 @@ ConditionResult ConditionEvaluator::evaluate_single(
result.field = condition.field;
result.op = condition.op;
- auto ind_result = IndicatorEngine::compute(
- condition.indicator, candles, condition.params, condition.field);
+ const bool needs_prev = op_needs_prev(condition.op);
- if (!ind_result.valid) {
- result.error = ind_result.error;
+ QString err;
+ double lhs_curr = operand_value(condition.indicator, condition.params, condition.field,
+ condition.offset, candles, &err);
+ if (!err.isEmpty()) {
+ result.error = err;
return result;
}
+ result.computed_value = lhs_curr;
- double curr_val = ind_result.current.value(condition.field, 0);
- double prev_val = ind_result.previous.value(condition.field, curr_val);
- result.computed_value = curr_val;
+ double lhs_prev = needs_prev
+ ? operand_value(condition.indicator, condition.params, condition.field,
+ condition.offset + 1, candles, nullptr)
+ : kNaN;
+ double rhs_curr, rhs_prev;
if (condition.compare_mode == "indicator") {
- auto cmp_result = IndicatorEngine::compute(
- condition.compare_indicator, candles,
- condition.compare_params, condition.compare_field);
-
- if (!cmp_result.valid) {
- result.error = cmp_result.error;
+ QString cerr;
+ rhs_curr = operand_value(condition.compare_indicator, condition.compare_params,
+ condition.compare_field, condition.compare_offset, candles, &cerr);
+ if (!cerr.isEmpty()) {
+ result.error = cerr;
return result;
}
-
- double target_curr = cmp_result.current.value(condition.compare_field, 0);
- double target_prev = cmp_result.previous.value(condition.compare_field, target_curr);
- result.target_value = target_curr;
-
- if (condition.op == "crosses_above" || condition.op == "crosses_below") {
- result.met = apply_crossing(curr_val, prev_val, target_curr, target_prev, condition.op);
- } else if (condition.op == "rising" || condition.op == "falling") {
- result.met = (condition.op == "rising") ? (curr_val > prev_val) : (curr_val < prev_val);
- } else {
- result.met = apply_comparison(curr_val, condition.op, target_curr);
- }
+ rhs_prev = needs_prev
+ ? operand_value(condition.compare_indicator, condition.compare_params,
+ condition.compare_field, condition.compare_offset + 1, candles, nullptr)
+ : kNaN;
} else {
- result.target_value = condition.value;
-
- if (condition.op == "crosses_above" || condition.op == "crosses_below") {
- result.met = apply_crossing(curr_val, prev_val,
- condition.value, condition.value, condition.op);
- } else if (condition.op == "rising" || condition.op == "falling") {
- result.met = (condition.op == "rising") ? (curr_val > prev_val) : (curr_val < prev_val);
- } else {
- result.met = apply_comparison(curr_val, condition.op, condition.value);
- }
+ rhs_curr = condition.value;
+ rhs_prev = condition.value;
+ }
+ result.target_value = rhs_curr;
+
+ if (condition.op == "crosses_above" || condition.op == "crosses_below") {
+ result.met = apply_crossing(lhs_curr, lhs_prev, rhs_curr, rhs_prev, condition.op);
+ } else if (condition.op == "rising") {
+ result.met = !std::isnan(lhs_curr) && !std::isnan(lhs_prev) && lhs_curr > lhs_prev;
+ } else if (condition.op == "falling") {
+ result.met = !std::isnan(lhs_curr) && !std::isnan(lhs_prev) && lhs_curr < lhs_prev;
+ } else if (condition.op == "between") {
+ result.met = !std::isnan(lhs_curr) && lhs_curr >= condition.value && lhs_curr <= condition.value2;
+ result.target_value = condition.value2;
+ } else {
+ result.met = apply_comparison(lhs_curr, condition.op, rhs_curr);
}
return result;
}
GroupEvalResult ConditionEvaluator::evaluate_group(
- const QJsonArray& conditions_json,
+ const QJsonArray& children,
const QString& logic,
const QVector<OhlcvCandle>& candles) {
GroupEvalResult group;
group.logic = logic;
- if (conditions_json.isEmpty()) {
+ if (children.isEmpty()) {
group.triggered = false;
return group;
}
- bool is_and = (logic.toUpper() == "AND");
+ const bool is_and = (logic.toUpper() != "OR"); // default AND
bool overall = is_and;
- for (const auto& val : conditions_json) {
- auto cond = parse_condition(val.toObject());
- auto result = evaluate_single(cond, candles);
- group.details.append(result);
-
- if (is_and) {
- overall = overall && result.met;
+ for (const auto& val : children) {
+ const QJsonObject node = val.toObject();
+
+ bool met;
+ if (is_group_node(node)) {
+ auto sub = evaluate_group(node.value("children").toArray(),
+ node.value("logic").toString(
+ node.value("op").toString("AND")),
+ candles);
+ met = node.value("negate").toBool(false) ? !sub.triggered : sub.triggered;
+ group.details.append(sub.details); // flatten nested detail for reporting
} else {
- overall = overall || result.met;
+ auto cond = parse_condition(node);
+ auto r = evaluate_single(cond, candles);
+ group.details.append(r);
+ met = r.met;
}
- }
- // Reset to false for OR if first iteration set it wrong
- if (!is_and && !conditions_json.isEmpty()) {
- overall = false;
- for (const auto& d : group.details) {
- if (d.met) { overall = true; break; }
+ if (is_and) {
+ overall = overall && met;
+ if (!overall) break; // short-circuit
+ } else {
+ overall = overall || met;
+ if (overall) break; // short-circuit
}
}
diff --git a/fincept-qt/src/algo_engine/ConditionEvaluator.h b/fincept-qt/src/algo_engine/ConditionEvaluator.h
index 76d9ec5b2..5c6c731dc 100644
--- a/fincept-qt/src/algo_engine/ConditionEvaluator.h
+++ b/fincept-qt/src/algo_engine/ConditionEvaluator.h
@@ -5,9 +5,27 @@
#include "services/algo_trading/AlgoTradingTypes.h"
#include <QJsonArray>
+#include <QJsonObject>
namespace fincept::algo {
+/// Evaluates a strategy's entry/exit logic against a window of candles whose
+/// LAST element is the current bar.
+///
+/// The condition format is a backward-compatible superset of the original flat
+/// schema: `evaluate_group` receives an array of nodes joined by `logic`
+/// (AND/OR). Each node is either
+/// • a comparison leaf — `{indicator, params, field, offset, operator,
+/// compare_mode, value | compare_indicator …}`, or
+/// • a nested group — `{"children": [...], "logic": "AND"|"OR",
+/// "negate": bool}`
+/// so `(A AND B) OR C` is expressible. Legacy strategies (all-leaf arrays) keep
+/// evaluating unchanged — no migration required.
+///
+/// Every operand carries an integer `offset` (bars ago, 0 = current); the value
+/// N bars back is obtained by recomputing the indicator on the window truncated
+/// by N bars. `crosses_*` / `rising` / `falling` read the operand one extra bar
+/// back.
class ConditionEvaluator {
public:
static ConditionResult evaluate_single(
@@ -15,17 +33,22 @@ public:
const QVector<OhlcvCandle>& candles);
static GroupEvalResult evaluate_group(
- const QJsonArray& conditions_json,
+ const QJsonArray& children,
const QString& logic,
const QVector<OhlcvCandle>& candles);
private:
static fincept::services::algo::ConditionDef parse_condition(const QJsonObject& obj);
+ static bool is_group_node(const QJsonObject& node);
static bool apply_comparison(double lhs, const QString& op, double rhs);
static bool apply_crossing(double curr, double prev,
double target_curr, double target_prev,
const QString& op);
- static bool apply_trend(const QVector<double>& values, int count, const QString& op);
+ /// Resolves an indicator operand `offset` bars back. Returns NaN and sets
+ /// `*error` (when non-null) on failure / insufficient data.
+ static double operand_value(const QString& indicator, const QJsonObject& params,
+ const QString& field, int offset,
+ const QVector<OhlcvCandle>& candles, QString* error);
};
} // namespace fincept::algo
diff --git a/fincept-qt/src/algo_engine/DeploymentRunner.cpp b/fincept-qt/src/algo_engine/DeploymentRunner.cpp
index 271d32072..974a390d7 100644
--- a/fincept-qt/src/algo_engine/DeploymentRunner.cpp
+++ b/fincept-qt/src/algo_engine/DeploymentRunner.cpp
@@ -1,5 +1,6 @@
// src/algo_engine/DeploymentRunner.cpp
#include "algo_engine/DeploymentRunner.h"
+#include "algo_engine/CandleDataFetcher.h"
#include "algo_engine/ConditionEvaluator.h"
#include "core/logging/Logger.h"
#include "datahub/DataHub.h"
@@ -10,6 +11,7 @@ using fincept::Database;
#include "trading/TradingTypes.h"
#include <QDateTime>
+#include <QPointer>
#include <QSqlQuery>
#include <QUuid>
#include <QVariant>
@@ -24,7 +26,8 @@ DeploymentRunner::DeploymentRunner(const services::algo::AlgoDeployment& deploym
, strategy_(strategy)
, timeframe_(timeframe_from_string(deployment.timeframe.isEmpty() ? strategy.timeframe : deployment.timeframe)) {
- aggregator_ = std::make_unique<CandleAggregator>(deployment.symbol, timeframe_, 200, this);
+ // Capacity 500 so long indicators (SMA200) + a crossover lookback fit.
+ aggregator_ = std::make_unique<CandleAggregator>(deployment.symbol, timeframe_, 500, this);
connect(aggregator_.get(), &CandleAggregator::candle_closed,
this, &DeploymentRunner::on_candle_closed);
@@ -50,7 +53,32 @@ void DeploymentRunner::start() {
paused_ = false;
last_heartbeat_ms_ = QDateTime::currentMSecsSinceEpoch();
- subscribe_tick_topic();
+ // Warm the aggregator with historical candles before going live, so indicators
+ // are valid immediately. Without this the buffer starts empty and the strategy
+ // can't trigger until hundreds of live bars accumulate. Live ticks are
+ // subscribed only after the backfill attempt (warm_from replaces the buffer).
+ const QString tf = timeframe_to_string(timeframe_);
+ const int lookback = services::algo::algo_default_lookback_days(tf);
+ const DataSource src = deployment_.broker_id.isEmpty() ? DataSource::YFinance : DataSource::Auto;
+ QPointer<DeploymentRunner> self = this;
+ CandleDataFetcher::instance().fetch(
+ deployment_.symbol, tf, lookback, src, deployment_.broker_id, deployment_.broker_account_id,
+ [self](bool ok, const QVector<OhlcvCandle>& candles, const QString& err) {
+ if (!self || !self->running_.load())
+ return;
+ if (ok && !candles.isEmpty()) {
+ self->aggregator_->warm_from(candles);
+ LOG_INFO("AlgoEngine", QString("Deployment %1 warmed with %2 historical candles")
+ .arg(self->deployment_.id)
+ .arg(candles.size()));
+ } else {
+ LOG_WARN("AlgoEngine",
+ QString("Deployment %1 backfill failed (%2) — warming from live ticks only")
+ .arg(self->deployment_.id, err));
+ }
+ self->subscribe_tick_topic();
+ });
+
heartbeat_timer_->start();
update_deployment_status(QStringLiteral("running"));
@@ -206,6 +234,12 @@ void DeploymentRunner::evaluate_exit(const QVector<OhlcvCandle>& candles) {
}
void DeploymentRunner::emit_order_signal(const AlgoOrderSignal& signal) {
+ // Only one order in flight at a time. Position/risk state updates only when a
+ // fill arrives, so without this guard a stop-loss re-fires on every tick (and
+ // entry/exit on every candle) until the fill lands — flooding duplicate orders.
+ if (!pending_orders_.isEmpty())
+ return;
+
PendingOrder pending;
pending.signal = signal;
pending.submitted_ms = QDateTime::currentMSecsSinceEpoch();
@@ -271,6 +305,18 @@ void DeploymentRunner::on_order_rejected(const QString& /*broker_order_id*/,
void DeploymentRunner::on_heartbeat() {
if (!running_.load()) return;
int64_t now = QDateTime::currentMSecsSinceEpoch();
+
+ // Purge orders that never reported a fill/rejection so a lost ack doesn't
+ // permanently block new signals (the in-flight guard in emit_order_signal).
+ for (int i = pending_orders_.size() - 1; i >= 0; --i) {
+ if (now - pending_orders_[i].submitted_ms > 60000) {
+ LOG_WARN("AlgoEngine",
+ QString("Deployment %1: pending order timed out (no fill/reject in 60s), clearing")
+ .arg(deployment_.id));
+ pending_orders_.removeAt(i);
+ }
+ }
+
if (now - last_heartbeat_ms_ > 30000) {
LOG_ERROR("AlgoEngine", QString("Deployment %1: no tick data for 30s, marking error")
.arg(deployment_.id));
diff --git a/fincept-qt/src/algo_engine/IndicatorEngine.cpp b/fincept-qt/src/algo_engine/IndicatorEngine.cpp
index 2f2ce4ac2..e4678c87d 100644
--- a/fincept-qt/src/algo_engine/IndicatorEngine.cpp
+++ b/fincept-qt/src/algo_engine/IndicatorEngine.cpp
@@ -179,11 +179,20 @@ IndicatorResult IndicatorEngine::compute_stock_attr(const QVector<OhlcvCandle>&
else if (attr == "LOW") { cv = curr.low; pv = prev.low; }
else if (attr == "VOLUME") { cv = curr.volume; pv = prev.volume; }
else if (attr == "VWAP") {
- auto vwap = [](const OhlcvCandle& c) {
- return c.volume > 0 ? (c.high + c.low + c.close) / 3.0 : c.close;
- };
- cv = vwap(curr);
- pv = vwap(prev);
+ // Cumulative VWAP over the provided window: Σ(typical·vol)/Σ(vol).
+ // (Per-bar (H+L+C)/3 was just typical price, not a VWAP.)
+ const int n = candles.size();
+ double num = 0.0, den = 0.0;
+ for (int i = 0; i < n; ++i) {
+ if (i == n - 1) // snapshot the previous-bar VWAP before adding the last bar
+ pv = den > 0.0 ? num / den : prev.close;
+ const auto& c = candles[i];
+ const double tp = (c.high + c.low + c.close) / 3.0;
+ const double v = c.volume > 0.0 ? c.volume : 0.0;
+ num += tp * v;
+ den += v;
+ }
+ cv = den > 0.0 ? num / den : curr.close;
}
r.current[QStringLiteral("value")] = cv;
r.previous[QStringLiteral("value")] = pv;
diff --git a/fincept-qt/src/app/DockScreenRouter.h b/fincept-qt/src/app/DockScreenRouter.h
index 8744b8640..de3113d60 100644
--- a/fincept-qt/src/app/DockScreenRouter.h
+++ b/fincept-qt/src/app/DockScreenRouter.h
@@ -229,6 +229,15 @@ class DockScreenRouter : public QObject {
ads::CDockWidget* create_dock_widget(const QString& id);
void materialize_screen(const QString& id);
+ /// Re-tile all open panels into the auto-grid the product wants when a new
+ /// panel is added: 1=full, 2=left|right, 3=top-row + full-width bottom,
+ /// 4=2x2 (3rd→bottom-left, 4th→bottom-right), 5+=tab into bottom-right.
+ /// Existing panels keep their reading order (top→bottom, left→right); if
+ /// `newest` is given it is placed into the last/next slot. Shared by the
+ /// `layout.tile_2x2` command (newest == nullptr) and navigate()'s
+ /// new-panel path.
+ void retile_grid(ads::CDockWidget* newest = nullptr);
+
// ── Symbol group linking ──────────────────────────────────────────────────
// If `screen` (or one of its descendants) implements IGroupLinked, wraps
// it in a thin container with a top-bar GroupBadge and wires the badge to
diff --git a/fincept-qt/src/app/DockScreenRouter_Navigation.cpp b/fincept-qt/src/app/DockScreenRouter_Navigation.cpp
index 0c19eb4b9..4e0607dd9 100644
--- a/fincept-qt/src/app/DockScreenRouter_Navigation.cpp
+++ b/fincept-qt/src/app/DockScreenRouter_Navigation.cpp
@@ -129,6 +129,10 @@ void DockScreenRouter::navigate(const QString& id, bool exclusive) {
// "right-of-TL → below-TL → right-of-BL" cycle was a v1
// simplification; this is the cleaner Fincept-grade behaviour
// (everything tabs into centre by default; user splits explicitly).
+ // Product behaviour: a newly-added panel auto-tiles into the next grid
+ // slot rather than stacking as a tab. Place it anywhere first so it's in
+ // a layout, then re-grid all open panels (newest lands in the next slot:
+ // 2→left|right, 3→full-width bottom, 4→2x2, 5+→tab into bottom-right).
const auto opened = manager_->openedDockAreas();
ads::CDockAreaWidget* target = nullptr;
if (auto* focused = manager_->focusedDockWidget()) {
@@ -141,6 +145,7 @@ void DockScreenRouter::navigate(const QString& id, bool exclusive) {
manager_->addDockWidget(ads::CenterDockWidgetArea, dw, target);
else
manager_->addDockWidget(ads::CenterDockWidgetArea, dw);
+ retile_grid(dw);
} else {
// Widget already has a dedicated area — just bring it to the front.
diff --git a/fincept-qt/src/app/DockScreenRouter_PanelOps.cpp b/fincept-qt/src/app/DockScreenRouter_PanelOps.cpp
index 52e662178..3f7eb82ec 100644
--- a/fincept-qt/src/app/DockScreenRouter_PanelOps.cpp
+++ b/fincept-qt/src/app/DockScreenRouter_PanelOps.cpp
@@ -35,8 +35,11 @@
#include <QLabel>
#include <QLineEdit>
#include <QMenu>
+#include <QPoint>
#include <QVBoxLayout>
+#include <algorithm>
+
#include <DockAreaWidget.h>
#include <DockManager.h>
#include <DockWidget.h>
@@ -357,20 +360,47 @@ void DockScreenRouter::show_tab_context_menu(const QString& id, const QPoint& gl
}
void DockScreenRouter::tile_2x2() {
- // Phase 6 final / decision 5.5. Detach every open dock widget then
- // re-add with explicit ADS area hints to force the 2x2 grid.
+ // Public `layout.tile_2x2` command: re-grid every open panel in its current
+ // reading order. Delegates to the shared auto-grid implementation.
+ retile_grid(nullptr);
+}
+
+void DockScreenRouter::retile_grid(ads::CDockWidget* newest) {
+ // Detach every open dock widget then re-add with explicit ADS area hints to
+ // force the product's auto-grid. Quadrant fill order:
+ // 1 panel → full
+ // 2 panels → left | right
+ // 3 panels → top row [left | right] + full-width bottom
+ // 4 panels → 2x2 (3rd → bottom-left, 4th → bottom-right)
+ // 5+ → tab into bottom-right
if (!manager_)
return;
+
+ // Collect open panels, excluding `newest` (appended last so it lands in the
+ // next/last slot). Existing panels are ordered by current on-screen position
+ // (top→bottom, then left→right) so a re-tile preserves their reading order
+ // instead of reshuffling them alphabetically by id.
QList<ads::CDockWidget*> open;
for (auto* dw : manager_->dockWidgetsMap()) {
- if (dw && !dw->isClosed())
+ if (dw && !dw->isClosed() && dw != newest)
open.append(dw);
}
+ std::sort(open.begin(), open.end(), [](ads::CDockWidget* a, ads::CDockWidget* b) {
+ const QPoint pa = a->dockAreaWidget() ? a->dockAreaWidget()->mapToGlobal(QPoint(0, 0)) : QPoint();
+ const QPoint pb = b->dockAreaWidget() ? b->dockAreaWidget()->mapToGlobal(QPoint(0, 0)) : QPoint();
+ if (pa.y() != pb.y())
+ return pa.y() < pb.y();
+ return pa.x() < pb.x();
+ });
+ if (newest && !newest->isClosed())
+ open.append(newest);
+
if (open.isEmpty()) {
- LOG_DEBUG("DockRouter", "tile_2x2: no open panels");
+ LOG_DEBUG("DockRouter", "retile_grid: no open panels");
return;
}
- LOG_INFO("DockRouter", QString("tile_2x2: rearranging %1 panel(s)").arg(open.size()));
+ const int n = open.size();
+ LOG_INFO("DockRouter", QString("retile_grid: arranging %1 panel(s)").arg(n));
for (auto* dw : open)
manager_->removeDockWidget(dw);
@@ -379,19 +409,23 @@ void DockScreenRouter::tile_2x2() {
ads::CDockAreaWidget* tr = nullptr;
ads::CDockAreaWidget* bl = nullptr;
ads::CDockAreaWidget* br = nullptr;
+ ads::CDockAreaWidget* bottom = nullptr;
- for (int i = 0; i < open.size(); ++i) {
+ for (int i = 0; i < n; ++i) {
ads::CDockWidget* dw = open.at(i);
if (i == 0) {
tl = manager_->addDockWidget(ads::CenterDockWidgetArea, dw);
} else if (i == 1) {
tr = manager_->addDockWidget(ads::RightDockWidgetArea, dw, tl);
} else if (i == 2) {
- bl = manager_->addDockWidget(ads::BottomDockWidgetArea, dw, tl);
+ if (n == 3)
+ bottom = manager_->addDockWidget(ads::BottomDockWidgetArea, dw); // full-width bottom
+ else
+ bl = manager_->addDockWidget(ads::BottomDockWidgetArea, dw, tl); // bottom-left
} else if (i == 3) {
- br = manager_->addDockWidget(ads::RightDockWidgetArea, dw, bl);
+ br = manager_->addDockWidget(ads::RightDockWidgetArea, dw, bl); // bottom-right
} else {
- ads::CDockAreaWidget* target = br ? br : (bl ? bl : (tr ? tr : tl));
+ ads::CDockAreaWidget* target = br ? br : (bottom ? bottom : (bl ? bl : (tr ? tr : tl)));
if (target)
manager_->addDockWidget(ads::CenterDockWidgetArea, dw, target);
else
@@ -399,7 +433,8 @@ void DockScreenRouter::tile_2x2() {
}
dw->toggleView(true);
}
- (void) tr; // suppress unused-variable warnings if compiler is strict
+ (void) tr;
+ (void) bottom;
}
// ── Phase 5: tear-off + cross-frame move ────────────────────────────────────
diff --git a/fincept-qt/src/app/WindowFrame_Auth.cpp b/fincept-qt/src/app/WindowFrame_Auth.cpp
index ff534ad63..0b6244d37 100644
--- a/fincept-qt/src/app/WindowFrame_Auth.cpp
+++ b/fincept-qt/src/app/WindowFrame_Auth.cpp
@@ -18,6 +18,7 @@
#include "services/updater/UpdateService.h"
#include "storage/repositories/SettingsRepository.h"
#include "trading/instruments/InstrumentService.h"
+#include "trading/instruments/SymbolResolver.h"
#include "ui/navigation/DockStatusBar.h"
#include "ui/navigation/DockToolBar.h"
#include "ui/theme/Theme.h"
@@ -155,11 +156,13 @@ void WindowFrame::on_auth_state_changed() {
});
// Warm instrument cache in background — only loaded if not already cached.
// Runs concurrently while the user reads the dashboard (3-5s head start).
- fincept::trading::InstrumentService::instance().load_from_db_async("zerodha");
- fincept::trading::InstrumentService::instance().load_from_db_async("angelone");
- fincept::trading::InstrumentService::instance().load_from_db_async("groww");
- fincept::trading::InstrumentService::instance().load_from_db_async("fyers");
- fincept::trading::InstrumentService::instance().load_from_db_async("dhan");
+ // Load every registered broker (all 17 Indian brokers) so unified
+ // cross-broker search includes any broker whose master was already
+ // downloaded, without needing the user to focus each one first.
+ // instance() also registers all broker sources, so registered_brokers() is populated.
+ auto& isvc = fincept::trading::InstrumentService::instance();
+ for (const QString& bid : fincept::trading::SymbolResolver::instance().registered_brokers())
+ isvc.load_from_db_async(bid);
} else {
// Free/no plan → show pricing gate
set_shell_visible(false);
diff --git a/fincept-qt/src/app/main.cpp b/fincept-qt/src/app/main.cpp
index ac4fe8705..ade266709 100644
--- a/fincept-qt/src/app/main.cpp
+++ b/fincept-qt/src/app/main.cpp
@@ -13,6 +13,7 @@
#include "core/config/ProfileManager.h"
#include "core/components/ComponentCatalog.h"
#include "core/crash/CrashHandler.h"
+#include "core/currency/CurrencyManager.h"
#include "core/i18n/LanguageManager.h"
#include "core/keys/KeyConfigManager.h"
#include "core/logging/Logger.h"
@@ -638,6 +639,7 @@ int main(int argc, char* argv[]) {
fincept::register_migration_v033();
fincept::register_migration_v034();
fincept::register_migration_v035();
+ fincept::register_migration_v036();
// Open main database
QString db_path = fincept::AppPaths::data() + "/fincept.db";
@@ -681,6 +683,10 @@ int main(int argc, char* argv[]) {
// any windows are shown — eliminates an English-flash on first paint
// when the user has previously chosen another language.
fincept::i18n::LanguageManager::instance().initialize();
+
+ // Load persisted display-currency preference so the symbol is correct
+ // on first paint of any calculator/analytics surface.
+ fincept::currency::CurrencyManager::instance().initialize();
}
// Open cache database (non-fatal if fails)
diff --git a/fincept-qt/src/core/currency/Currency.h b/fincept-qt/src/core/currency/Currency.h
new file mode 100644
index 000000000..ca6412592
--- /dev/null
+++ b/fincept-qt/src/core/currency/Currency.h
@@ -0,0 +1,80 @@
+#pragma once
+// cur:: — call-site helpers built on CurrencyManager.
+//
+// cur::symbol() -> current global symbol, e.g. "€"
+// cur::money(v) -> "€1,234.56" using the global currency
+// cur::money(v, true) -> "€1.2B" compact (K/M/B)
+// cur::money(v, true, "USD") -> pin to an intrinsic currency (market data)
+// cur::bindLabel(lbl, "Rev (%1)") -> set text now + on every currency_changed
+// cur::bindPrefix(spin) -> set spinbox prefix now + on change
+//
+// Binders use the bound widget as the Qt receiver/context, so the connection
+// auto-disconnects when the widget is destroyed — no manual cleanup needed.
+
+#include "core/currency/CurrencyManager.h"
+
+#include <QAbstractSpinBox>
+#include <QDoubleSpinBox>
+#include <QLabel>
+#include <QLocale>
+#include <QSpinBox>
+#include <QString>
+#include <cmath>
+
+namespace cur {
+
+inline QString symbol() { return fincept::currency::CurrencyManager::instance().symbol(); }
+
+/// Symbol for a specific currency code, independent of the global preference.
+/// Use for intrinsic-currency surfaces (e.g. a portfolio's own currency).
+inline QString symbol_for(const QString& code) {
+ return fincept::currency::CurrencyManager::symbol_for(code);
+}
+
+/// Format an amount. `compact` abbreviates to K/M/B. `intrinsic` (if non-empty)
+/// pins the symbol to that currency code instead of the global preference.
+inline QString money(double v, bool compact = false, const QString& intrinsic = QString()) {
+ const QString sym = intrinsic.isEmpty()
+ ? symbol()
+ : fincept::currency::CurrencyManager::symbol_for(intrinsic);
+ const QString sign = v < 0 ? QStringLiteral("-") : QString();
+ const double a = std::abs(v);
+ if (compact) {
+ if (a >= 1e9)
+ return sign + sym + QString::number(a / 1e9, 'f', 1) + "B";
+ if (a >= 1e6)
+ return sign + sym + QString::number(a / 1e6, 'f', 1) + "M";
+ if (a >= 1e3)
+ return sign + sym + QString::number(a / 1e3, 'f', 0) + "K";
+ }
+ return sign + sym + QLocale(QLocale::English).toString(a, 'f', 2);
+}
+
+/// `tmpl` must contain a single "%1" placeholder for the symbol.
+inline void bindLabel(QLabel* lbl, const QString& tmpl) {
+ if (!lbl)
+ return;
+ lbl->setText(tmpl.arg(symbol()));
+ QObject::connect(&fincept::currency::CurrencyManager::instance(),
+ &fincept::currency::CurrencyManager::currency_changed, lbl,
+ [lbl, tmpl](const QString&, const QString& s) { lbl->setText(tmpl.arg(s)); });
+}
+
+/// Sets the spin box prefix to the current symbol (plus a space) and keeps it
+/// in sync with currency changes.
+inline void bindPrefix(QAbstractSpinBox* spin) {
+ if (!spin)
+ return;
+ auto apply = [spin](const QString& s) {
+ if (auto* d = qobject_cast<QDoubleSpinBox*>(spin))
+ d->setPrefix(s + " ");
+ else if (auto* i = qobject_cast<QSpinBox*>(spin))
+ i->setPrefix(s + " ");
+ };
+ apply(symbol());
+ QObject::connect(&fincept::currency::CurrencyManager::instance(),
+ &fincept::currency::CurrencyManager::currency_changed, spin,
+ [apply](const QString&, const QString& s) { apply(s); });
+}
+
+} // namespace cur
diff --git a/fincept-qt/src/core/currency/CurrencyManager.cpp b/fincept-qt/src/core/currency/CurrencyManager.cpp
new file mode 100644
index 000000000..3a9be307a
--- /dev/null
+++ b/fincept-qt/src/core/currency/CurrencyManager.cpp
@@ -0,0 +1,49 @@
+#include "core/currency/CurrencyManager.h"
+
+#include "core/logging/Logger.h"
+#include "storage/repositories/SettingsRepository.h"
+
+namespace fincept::currency {
+
+CurrencyManager& CurrencyManager::instance() {
+ static CurrencyManager s;
+ return s;
+}
+
+QVector<CurrencyInfo> CurrencyManager::available() {
+ return {
+ {"USD", "$", "US Dollar"},
+ {"EUR", QString::fromUtf8("\xe2\x82\xac"), "Euro"}, // €
+ {"GBP", QString::fromUtf8("\xc2\xa3"), "British Pound"}, // £
+ {"JPY", QString::fromUtf8("\xc2\xa5"), "Japanese Yen"}, // ¥
+ {"INR", QString::fromUtf8("\xe2\x82\xb9"), "Indian Rupee"}, // ₹
+ {"CNY", QString::fromUtf8("\xc2\xa5"), "Chinese Yuan"}, // ¥
+ {"CHF", "Fr", "Swiss Franc"},
+ {"CAD", "$", "Canadian Dollar"},
+ {"AUD", "$", "Australian Dollar"},
+ };
+}
+
+QString CurrencyManager::symbol_for(const QString& code) {
+ for (const auto& c : available())
+ if (c.code == code)
+ return c.symbol;
+ return code; // unknown → show the code rather than a wrong glyph
+}
+
+void CurrencyManager::initialize() {
+ const auto r = SettingsRepository::instance().get("general.currency", "USD");
+ code_ = (r.is_ok() && !r.value().isEmpty()) ? r.value() : QStringLiteral("USD");
+ LOG_INFO("Currency", QString("Preferred currency: %1").arg(code_));
+}
+
+void CurrencyManager::set_currency(const QString& code) {
+ if (code == code_ || symbol_for(code) == code) // unchanged, or unknown code
+ return;
+ code_ = code;
+ SettingsRepository::instance().set("general.currency", code, "general");
+ LOG_INFO("Currency", QString("Currency \xe2\x86\x92 %1").arg(code)); // →
+ emit currency_changed(code_, symbol());
+}
+
+} // namespace fincept::currency
diff --git a/fincept-qt/src/core/currency/CurrencyManager.h b/fincept-qt/src/core/currency/CurrencyManager.h
new file mode 100644
index 000000000..548732f30
--- /dev/null
+++ b/fincept-qt/src/core/currency/CurrencyManager.h
@@ -0,0 +1,50 @@
+#pragma once
+// CurrencyManager — owns the user's preferred display currency.
+// Cloned from core/i18n/LanguageManager: singleton, persisted via
+// SettingsRepository ("general.currency"), broadcasts currency_changed.
+// Symbol-only: changing currency never converts values, it only changes
+// the symbol shown on denomination-agnostic surfaces (calculators).
+// Market-data surfaces pass an explicit intrinsic currency and are unaffected.
+
+#include <QObject>
+#include <QString>
+#include <QVector>
+
+namespace fincept::currency {
+
+struct CurrencyInfo {
+ QString code; // ISO 4217, e.g. "USD"
+ QString symbol; // display glyph, e.g. "$"
+ QString name; // human label for the settings combo
+};
+
+class CurrencyManager : public QObject {
+ Q_OBJECT
+ public:
+ static CurrencyManager& instance();
+
+ /// All selectable currencies (single source of truth for the combo).
+ static QVector<CurrencyInfo> available();
+
+ /// Symbol for a given code; falls back to the code itself if unknown.
+ static QString symbol_for(const QString& code);
+
+ /// Read the persisted choice from SettingsRepository (default "USD").
+ /// Call once on startup before windows are shown.
+ void initialize();
+
+ QString code() const { return code_; }
+ QString symbol() const { return symbol_for(code_); }
+
+ /// Switch currency: persist + emit. No-op if unchanged or unknown code.
+ void set_currency(const QString& code);
+
+ signals:
+ void currency_changed(const QString& code, const QString& symbol);
+
+ private:
+ CurrencyManager() = default;
+ QString code_ = "USD";
+};
+
+} // namespace fincept::currency
diff --git a/fincept-qt/src/network/websocket/WebSocketClient.cpp b/fincept-qt/src/network/websocket/WebSocketClient.cpp
index a82d76d05..289725c89 100644
--- a/fincept-qt/src/network/websocket/WebSocketClient.cpp
+++ b/fincept-qt/src/network/websocket/WebSocketClient.cpp
@@ -2,8 +2,10 @@
#include "core/logging/Logger.h"
+#include <QDateTime>
#include <QMetaObject>
#include <QPointer>
+#include <QRegularExpression>
#include <QThread>
#include <QTimer>
@@ -12,6 +14,15 @@ namespace fincept {
namespace {
constexpr const char* kTag = "WS";
+// Mask the `token=` query value so broker access tokens (JWTs) never reach the
+// log file. Applied to every URL we log — these tokens are bearer credentials.
+QString redact_url(const QString& url) {
+ QString out = url;
+ static const QRegularExpression re(QStringLiteral("token=[^&]*"));
+ out.replace(re, QStringLiteral("token=REDACTED"));
+ return out;
+}
+
QString thread_label() {
auto* t = QThread::currentThread();
if (!t)
@@ -70,6 +81,7 @@ void WebSocketClient::connect_to(const QString& url) {
return;
self->url_ = u;
self->reconnect_attempts_ = 0;
+ self->reconnect_enabled_ = true; // a fresh connect re-enables auto-reconnect
LOG_INFO(kTag, QString("[%1] Connecting to %2").arg(thread_label(), u));
self->socket_->open(QUrl(u));
});
@@ -80,12 +92,35 @@ void WebSocketClient::disconnect() {
run_on_owning_thread(this, [self]() {
if (!self)
return;
- LOG_INFO(kTag, QString("[%1] Disconnect requested for %2").arg(thread_label(), self->url_));
+ LOG_INFO(kTag, QString("[%1] Disconnect requested for %2").arg(thread_label(), redact_url(self->url_)));
self->reconnect_timer_.stop();
self->socket_->close();
});
}
+void WebSocketClient::stop_reconnect() {
+ QPointer<WebSocketClient> self(this);
+ run_on_owning_thread(this, [self]() {
+ if (!self)
+ return;
+ self->reconnect_stopped_ = true;
+ self->reconnect_timer_.stop();
+ LOG_INFO(kTag, QString("[%1] Auto-reconnect halted for %2 (fatal error or explicit stop)")
+ .arg(thread_label(), redact_url(self->url_)));
+ });
+}
+
+void WebSocketClient::stop_reconnect() {
+ QPointer<WebSocketClient> self(this);
+ run_on_owning_thread(this, [self]() {
+ if (!self)
+ return;
+ LOG_INFO(kTag, QString("[%1] Auto-reconnect halted for %2").arg(thread_label(), self->url_));
+ self->reconnect_enabled_ = false;
+ self->reconnect_timer_.stop();
+ });
+}
+
void WebSocketClient::send(const QString& message) {
QPointer<WebSocketClient> self(this);
const QString m = message;
@@ -122,7 +157,7 @@ void WebSocketClient::on_disconnected() {
.arg(thread_label(), url_)
.arg(static_cast<int>(socket_ ? socket_->state() : QAbstractSocket::UnconnectedState)));
emit disconnected();
- if (reconnect_attempts_ < MAX_RECONNECT_ATTEMPTS) {
+ if (reconnect_enabled_ && reconnect_attempts_ < MAX_RECONNECT_ATTEMPTS) {
const int delay = std::min(1000 * (1 << reconnect_attempts_), 30000);
LOG_INFO(kTag, QString("[%1] Scheduling reconnect attempt %2/%3 in %4ms")
.arg(thread_label())
@@ -149,18 +184,23 @@ void WebSocketClient::on_binary_received(const QByteArray& data) {
void WebSocketClient::on_error(QAbstractSocket::SocketError err) {
const QString es = socket_ ? socket_->errorString() : QStringLiteral("(no socket)");
LOG_ERROR(kTag, QString("[%1] Error on %2: %3 (code=%4)")
- .arg(thread_label(), url_, es)
+ .arg(thread_label(), redact_url(url_), es)
.arg(static_cast<int>(err)));
emit error_occurred(es);
}
void WebSocketClient::attempt_reconnect() {
+ if (reconnect_stopped_) {
+ LOG_INFO(kTag, QString("[%1] attempt_reconnect skipped for %2 (stop_reconnect)")
+ .arg(thread_label(), redact_url(url_)));
+ return;
+ }
reconnect_attempts_++;
LOG_INFO(kTag, QString("[%1] Reconnect attempt %2/%3 to %4")
.arg(thread_label())
.arg(reconnect_attempts_)
.arg(MAX_RECONNECT_ATTEMPTS)
- .arg(url_));
+ .arg(redact_url(url_)));
socket_->open(QUrl(url_));
}
@@ -171,6 +211,7 @@ void WebSocketClient::connect_to(const QString& /*url*/) {
LOG_WARN(kTag, "WebSocket not available — Qt6::WebSockets not installed");
}
void WebSocketClient::disconnect() {}
+void WebSocketClient::stop_reconnect() {}
void WebSocketClient::send(const QString& /*message*/) {}
void WebSocketClient::send_binary(const QByteArray& /*data*/) {}
bool WebSocketClient::is_connected() const {
diff --git a/fincept-qt/src/network/websocket/WebSocketClient.h b/fincept-qt/src/network/websocket/WebSocketClient.h
index 8ab7eb919..ac479094c 100644
--- a/fincept-qt/src/network/websocket/WebSocketClient.h
+++ b/fincept-qt/src/network/websocket/WebSocketClient.h
@@ -22,6 +22,11 @@ class WebSocketClient : public QObject {
void send_binary(const QByteArray& data);
bool is_connected() const;
+ // Halt auto-reconnect until the next connect_to(). Use on a fatal,
+ // non-retryable failure (e.g. expired/invalid token, Data API not
+ // subscribed) so we stop the reconnect storm immediately. Thread-safe.
+ void stop_reconnect();
+
signals:
void connected();
void disconnected();
@@ -51,6 +56,7 @@ class WebSocketClient : public QObject {
QTimer reconnect_timer_;
QString url_;
int reconnect_attempts_ = 0;
+ bool reconnect_stopped_ = false; // set by stop_reconnect() on fatal disconnects; cleared by connect_to()
static constexpr int MAX_RECONNECT_ATTEMPTS = 10;
};
diff --git a/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel.cpp b/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel.cpp
index 12c47eeb5..d36807039 100644
--- a/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel.cpp
+++ b/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel.cpp
@@ -9,6 +9,7 @@
#include "screens/ai_quant_lab/QuantModulePanel_GsHelpers.h"
#include "screens/ai_quant_lab/QuantModulePanel_Styles.h"
+#include "core/currency/Currency.h"
#include "core/logging/Logger.h"
#include "services/ai_quant_lab/AIQuantLabService.h"
#include "services/file_manager/FileManagerService.h"
@@ -81,8 +82,16 @@ QWidget* QuantModulePanel::build_input_row(const QString& label, QWidget* input,
auto* hl = new QHBoxLayout(row);
hl->setContentsMargins(0, 2, 0, 2);
hl->setSpacing(8);
- auto* lbl = new QLabel(label, row);
+ auto* lbl = new QLabel(row);
lbl->setFixedWidth(160);
+ // Bind "($)" unit hints to the preferred currency; others stay plain.
+ if (label.endsWith("($)")) {
+ QString base = label;
+ base.chop(3); // strip "($)"
+ cur::bindLabel(lbl, base + "(%1)");
+ } else {
+ lbl->setText(label);
+ }
lbl->setStyleSheet(QString("color:%1; background:transparent;").arg(ui::colors::TEXT_SECONDARY()));
hl->addWidget(lbl);
hl->addWidget(input, 1);
diff --git a/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_Backtesting.cpp b/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_Backtesting.cpp
index b946b388e..2a2bd4095 100644
--- a/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_Backtesting.cpp
+++ b/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_Backtesting.cpp
@@ -8,6 +8,7 @@
#include "screens/ai_quant_lab/QuantModulePanel_GsHelpers.h"
#include "screens/ai_quant_lab/QuantModulePanel_Styles.h"
+#include "core/currency/Currency.h"
#include "core/events/EventBus.h"
#include "core/logging/Logger.h"
#include "services/ai_quant_lab/AIQuantLabService.h"
@@ -262,10 +263,7 @@ void QuantModulePanel::display_backtest_result(const QJsonObject& payload) {
int t_days = metrics["trading_days"].toInt();
auto fmt_pct = [](double v) { return QString("%1%2%").arg(v >= 0 ? "+" : "").arg(v, 0, 'f', 2); };
- auto fmt_usd = [](double v) -> QString {
- if (v >= 1e6) return QString("$%1M").arg(v / 1e6, 0, 'f', 2);
- return QString("$%1K").arg(v / 1e3, 0, 'f', 0);
- };
+ auto fmt_usd = [](double v) -> QString { return cur::money(v, /*compact=*/true); };
QList<KpiCard> kpis = {
{tr("TOTAL RETURN"), fmt_pct(total_ret), tr("%1 final").arg(fmt_usd(final_val)), total_ret >= 0, false},
@@ -388,7 +386,7 @@ void QuantModulePanel::display_backtest_result(const QJsonObject& payload) {
auto* y_axis = new QValueAxis;
double padding = (max_val - min_val) * 0.05;
y_axis->setRange(min_val - padding, max_val + padding);
- y_axis->setLabelFormat("$%.0f");
+ y_axis->setLabelFormat(cur::symbol() + "%.0f");
y_axis->setLabelsColor(QColor(QString(text_t)));
y_axis->setGridLineColor(QColor(QString(border_dim)));
y_axis->setLinePen(QPen(QColor(QString(border_med))));
diff --git a/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_GsHelpers.h b/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_GsHelpers.h
index 8764380d0..ee114fb3a 100644
--- a/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_GsHelpers.h
+++ b/fincept-qt/src/screens/ai_quant_lab/QuantModulePanel_GsHelpers.h
@@ -8,6 +8,7 @@
// live in a shared inline-namespace header.
#pragma once
+#include "core/currency/Currency.h"
#include "ui/theme/Theme.h"
#include <QCoreApplication>
@@ -59,11 +60,8 @@ inline QString gs_fmt_pct(double v, int decimals = 2) {
}
inline QString gs_fmt_money(double v) {
- const double a = std::abs(v);
- if (a >= 1e9) return QString("$%1B").arg(v / 1e9, 0, 'f', 2);
- if (a >= 1e6) return QString("$%1M").arg(v / 1e6, 0, 'f', 2);
- if (a >= 1e3) return QString("$%1K").arg(v / 1e3, 0, 'f', 2);
- return QString("$%1").arg(v, 0, 'f', 2);
+ // Calculator output — follows the preferred currency.
+ return cur::money(v, /*compact=*/true);
}
inline QString gs_fmt_signed_money(double v) {
@@ -85,10 +83,8 @@ inline QString gs_pos_neg_color(double v) {
inline QString format_val(const QJsonValue& val) {
if (val.isDouble()) {
double v = val.toDouble();
- if (std::abs(v) >= 1e9)
- return QString("$%1B").arg(v / 1e9, 0, 'f', 1);
if (std::abs(v) >= 1e6)
- return QString("$%1M").arg(v / 1e6, 0, 'f', 1);
+ return cur::money(v, /*compact=*/true);
if (std::abs(v) < 1.0 && std::abs(v) > 0.0001)
return QString("%1%").arg(v * 100, 0, 'f', 2);
return QString::number(v, 'f', 4);
diff --git a/fincept-qt/src/screens/algo_trading/AlgoTradingScreen.cpp b/fincept-qt/src/screens/algo_trading/AlgoTradingScreen.cpp
index d3f1bee97..511b2ac3b 100644
--- a/fincept-qt/src/screens/algo_trading/AlgoTradingScreen.cpp
+++ b/fincept-qt/src/screens/algo_trading/AlgoTradingScreen.cpp
@@ -74,6 +74,20 @@ void AlgoTradingScreen::build_ui() {
content_stack_->addWidget(dashboard_);
root->addWidget(content_stack_, 1);
+ // "Edit" in My Strategies opens the Builder (tab 0) pre-filled with that strategy.
+ connect(strategies_, &StrategyListPanel::edit_requested, this,
+ [this](const AlgoStrategy& s) {
+ builder_->load_strategy(s);
+ on_tab_changed(0);
+ });
+
+ // "Backtest" opens the Builder (tab 0) pre-filled and runs the backtest immediately.
+ connect(strategies_, &StrategyListPanel::backtest_requested, this,
+ [this](const AlgoStrategy& s, const QString& symbol, const QString& start, const QString& end) {
+ on_tab_changed(0);
+ builder_->load_and_backtest(s, symbol, start, end);
+ });
+
root->addWidget(build_status_bar());
setStyleSheet(QString("background:%1;").arg(ui::colors::BG_BASE()));
}
diff --git a/fincept-qt/src/screens/algo_trading/StrategyBuilderPanel.cpp b/fincept-qt/src/screens/algo_trading/StrategyBuilderPanel.cpp
index d77291e6e..269baa4ce 100644
--- a/fincept-qt/src/screens/algo_trading/StrategyBuilderPanel.cpp
+++ b/fincept-qt/src/screens/algo_trading/StrategyBuilderPanel.cpp
@@ -2,12 +2,15 @@
#include "screens/algo_trading/StrategyBuilderPanel.h"
#include "algo_engine/AlgoEngine.h"
+#include "core/currency/Currency.h"
#include "core/events/EventBus.h"
#include "core/logging/Logger.h"
#include "screens/algo_trading/AlgoDeployDialog.h"
#include "services/algo_trading/AlgoTradingService.h"
#include "ui/theme/Theme.h"
+#include <QDate>
+#include <QDateEdit>
#include <QGridLayout>
#include <QHBoxLayout>
#include <QJsonDocument>
@@ -33,6 +36,15 @@ void StrategyBuilderPanel::build_ui() {
main_layout->addWidget(build_top_toolbar());
+ validation_banner_ = new QLabel(this);
+ validation_banner_->setObjectName(QStringLiteral("builderValidationBanner"));
+ validation_banner_->setWordWrap(true);
+ validation_banner_->setStyleSheet(QStringLiteral(
+ "background:#3A1A1A;color:#FCA5A5;border:1px solid #7F1D1D;"
+ "padding:5px 10px;font-size:11px;font-weight:600;"));
+ validation_banner_->setVisible(false);
+ main_layout->addWidget(validation_banner_);
+
auto* splitter = new QSplitter(Qt::Horizontal, this);
splitter->setObjectName(QStringLiteral("builderSplitter"));
splitter->addWidget(build_left_panel());
@@ -70,6 +82,12 @@ QWidget* StrategyBuilderPanel::build_top_toolbar() {
timeframe_combo_->addItem(tf);
timeframe_combo_->setCurrentText(QStringLiteral("5m"));
+ template_combo_ = new QComboBox(this);
+ template_combo_->setObjectName(QStringLiteral("builderTemplateCombo"));
+ template_combo_->addItem(tr("Templates…"));
+ for (const auto& t : services::algo::algo_strategy_templates())
+ template_combo_->addItem(t.name);
+
save_btn_ = new QPushButton(tr("Save"), this);
save_btn_->setObjectName(QStringLiteral("builderSaveBtn"));
backtest_btn_ = new QPushButton(tr("Backtest"), this);
@@ -81,6 +99,7 @@ QWidget* StrategyBuilderPanel::build_top_toolbar() {
layout->addWidget(desc_edit_);
layout->addWidget(symbol_combo_);
layout->addWidget(timeframe_combo_);
+ layout->addWidget(template_combo_);
layout->addStretch();
layout->addWidget(save_btn_);
layout->addWidget(backtest_btn_);
@@ -89,6 +108,8 @@ QWidget* StrategyBuilderPanel::build_top_toolbar() {
connect(save_btn_, &QPushButton::clicked, this, &StrategyBuilderPanel::on_save);
connect(backtest_btn_, &QPushButton::clicked, this, &StrategyBuilderPanel::on_backtest);
connect(deploy_btn_, &QPushButton::clicked, this, &StrategyBuilderPanel::on_deploy);
+ connect(template_combo_, QOverload<int>::of(&QComboBox::activated), this,
+ &StrategyBuilderPanel::load_template);
return toolbar;
}
@@ -125,17 +146,6 @@ QWidget* StrategyBuilderPanel::build_right_panel() {
layout->setContentsMargins(12, 8, 12, 8);
layout->setSpacing(8);
- // Chart placeholder
- auto* chart_placeholder = new QWidget(this);
- chart_placeholder->setObjectName(QStringLiteral("builderChartPlaceholder"));
- chart_placeholder->setMinimumHeight(200);
- auto* chart_layout = new QVBoxLayout(chart_placeholder);
- auto* chart_label = new QLabel(tr("Select a symbol and deploy to view live chart"), this);
- chart_label->setObjectName(QStringLiteral("builderChartLabel"));
- chart_label->setAlignment(Qt::AlignCenter);
- chart_layout->addWidget(chart_label);
- layout->addWidget(chart_placeholder, 1);
-
// Backtest params
auto* bt_section = new QLabel(tr("BACKTEST"), this);
bt_section->setObjectName(QStringLiteral("builderBtHeader"));
@@ -149,17 +159,24 @@ QWidget* StrategyBuilderPanel::build_right_panel() {
bt_capital_->setRange(1000, 100000000);
bt_capital_->setDecimals(0);
bt_capital_->setValue(100000);
- bt_capital_->setPrefix(QStringLiteral("$ "));
+ cur::bindPrefix(bt_capital_); // backtest capital is user-denominated
- bt_start_date_ = new QLineEdit(this);
+ const QDate today = QDate::currentDate();
+ bt_start_date_ = new QDateEdit(this);
bt_start_date_->setObjectName(QStringLiteral("builderBtStart"));
- bt_start_date_->setPlaceholderText(QStringLiteral("2024-01-01"));
- bt_start_date_->setText(QStringLiteral("2024-01-01"));
+ bt_start_date_->setCalendarPopup(true);
+ bt_start_date_->setDisplayFormat(QStringLiteral("yyyy-MM-dd"));
+ bt_start_date_->setMinimumDate(QDate(2000, 1, 1));
+ bt_start_date_->setMaximumDate(today);
+ bt_start_date_->setDate(today.addYears(-1));
- bt_end_date_ = new QLineEdit(this);
+ bt_end_date_ = new QDateEdit(this);
bt_end_date_->setObjectName(QStringLiteral("builderBtEnd"));
- bt_end_date_->setPlaceholderText(QStringLiteral("2024-12-31"));
- bt_end_date_->setText(QStringLiteral("2024-12-31"));
+ bt_end_date_->setCalendarPopup(true);
+ bt_end_date_->setDisplayFormat(QStringLiteral("yyyy-MM-dd"));
+ bt_end_date_->setMinimumDate(QDate(2000, 1, 1));
+ bt_end_date_->setMaximumDate(today);
+ bt_end_date_->setDate(today);
bt_grid->addWidget(new QLabel(tr("Capital"), this), 0, 0);
bt_grid->addWidget(bt_capital_, 0, 1);
@@ -173,50 +190,8 @@ QWidget* StrategyBuilderPanel::build_right_panel() {
status_label_->setObjectName(QStringLiteral("builderStatus"));
layout->addWidget(status_label_);
- // KPI grid (hidden until backtest runs)
- kpi_grid_widget_ = new QWidget(this);
- kpi_grid_widget_->setObjectName(QStringLiteral("builderKpiGrid"));
- kpi_grid_widget_->setVisible(false);
-
- auto* kpi_grid = new QGridLayout(kpi_grid_widget_);
- kpi_grid->setSpacing(8);
-
- auto make_kpi = [&](int row, int col, const QString& title) -> std::pair<QLabel*, QLabel*> {
- auto* card = new QWidget(kpi_grid_widget_);
- card->setObjectName(QStringLiteral("kpiCard"));
- auto* card_layout = new QVBoxLayout(card);
- card_layout->setContentsMargins(8, 6, 8, 6);
- card_layout->setSpacing(2);
-
- auto* title_lbl = new QLabel(title, card);
- title_lbl->setObjectName(QStringLiteral("kpiTitle"));
- auto* val_lbl = new QLabel(QStringLiteral("--"), card);
- val_lbl->setObjectName(QStringLiteral("kpiValue"));
- auto* sub_lbl = new QLabel(card);
- sub_lbl->setObjectName(QStringLiteral("kpiSub"));
-
- card_layout->addWidget(title_lbl);
- card_layout->addWidget(val_lbl);
- card_layout->addWidget(sub_lbl);
- kpi_grid->addWidget(card, row, col);
- return {val_lbl, sub_lbl};
- };
-
- auto [tr_v, tr_s] = make_kpi(0, 0, tr("TOTAL RETURN"));
- kpi_total_return_val_ = tr_v; kpi_total_return_sub_ = tr_s;
- auto [sh_v, sh_s] = make_kpi(0, 1, tr("SHARPE RATIO"));
- kpi_sharpe_val_ = sh_v; kpi_sharpe_sub_ = sh_s;
- auto [dd_v, dd_s] = make_kpi(0, 2, tr("MAX DRAWDOWN"));
- kpi_max_dd_val_ = dd_v; kpi_max_dd_sub_ = dd_s;
- auto [wr_v, wr_s] = make_kpi(1, 0, tr("WIN RATE"));
- kpi_win_rate_val_ = wr_v; kpi_win_rate_sub_ = wr_s;
- auto [tt_v, tt_s] = make_kpi(1, 1, tr("TOTAL TRADES"));
- kpi_trades_val_ = tt_v; kpi_trades_sub_ = tt_s;
- auto [pf_v, pf_s] = make_kpi(1, 2, tr("PROFIT FACTOR"));
- kpi_profit_factor_val_ = pf_v; kpi_profit_factor_sub_ = pf_s;
-
- layout->addWidget(kpi_grid_widget_);
- layout->addStretch();
+ report_panel_ = new ui::algo::BacktestReportPanel(this);
+ layout->addWidget(report_panel_, 1);
return right;
}
@@ -233,14 +208,12 @@ void StrategyBuilderPanel::connect_service() {
});
}
-void StrategyBuilderPanel::on_save() {
- if (name_edit_->text().trimmed().isEmpty()) {
- status_label_->setText(tr("Please enter a strategy name."));
- return;
- }
+services::algo::AlgoStrategy StrategyBuilderPanel::build_strategy() {
+ if (loaded_strategy_id_.isEmpty())
+ loaded_strategy_id_ = QUuid::createUuid().toString(QUuid::WithoutBraces);
services::algo::AlgoStrategy strat;
- strat.id = QUuid::createUuid().toString(QUuid::WithoutBraces);
+ strat.id = loaded_strategy_id_;
strat.name = name_edit_->text().trimmed();
strat.description = desc_edit_->text().trimmed();
strat.timeframe = timeframe_combo_->currentText();
@@ -251,8 +224,17 @@ void StrategyBuilderPanel::on_save() {
strat.stop_loss = risk_panel_->stop_loss();
strat.take_profit = risk_panel_->take_profit();
strat.trailing_stop = risk_panel_->trailing_stop();
+ strat.position_size_pct = risk_panel_->capital_pct();
+ return strat;
+}
+
+void StrategyBuilderPanel::on_save() {
+ if (name_edit_->text().trimmed().isEmpty()) {
+ status_label_->setText(tr("Please enter a strategy name."));
+ return;
+ }
- services::algo::AlgoTradingService::instance().save_strategy(strat);
+ services::algo::AlgoTradingService::instance().save_strategy(build_strategy());
status_label_->setText(tr("Saving strategy..."));
}
@@ -261,29 +243,28 @@ void StrategyBuilderPanel::on_backtest() {
status_label_->setText(tr("Save strategy first."));
return;
}
+ if (bt_start_date_->date() >= bt_end_date_->date()) {
+ status_label_->setText(tr("Start date must be before end date."));
+ return;
+ }
+ if (const QString err = validate(); !err.isEmpty()) {
+ validation_banner_->setText(err);
+ validation_banner_->setVisible(true);
+ return;
+ }
+ validation_banner_->setVisible(false);
- // Build the strategy from current UI state, persist it, then backtest it
- // directly (no DB round-trip — unsaved edits are tested as-shown).
- services::algo::AlgoStrategy strat;
- strat.id = QUuid::createUuid().toString(QUuid::WithoutBraces);
- strat.name = name_edit_->text().trimmed();
- strat.description = desc_edit_->text().trimmed();
- strat.timeframe = timeframe_combo_->currentText();
- strat.entry_conditions = entry_section_->conditions();
- strat.exit_conditions = exit_section_->conditions();
- strat.entry_logic = entry_section_->combined_logic();
- strat.exit_logic = exit_section_->combined_logic();
- strat.stop_loss = risk_panel_->stop_loss();
- strat.take_profit = risk_panel_->take_profit();
- strat.trailing_stop = risk_panel_->trailing_stop();
-
- services::algo::AlgoTradingService::instance().save_strategy(strat);
+ // Backtest the current UI state directly, without persisting — backtesting is
+ // non-mutating; the user saves explicitly via Save. (Avoids silently rewriting
+ // library rows / bumping updated_at on every run.)
+ auto strat = build_strategy();
QString symbol = symbol_combo_->currentText().trimmed();
if (symbol.isEmpty()) symbol = QStringLiteral("RELIANCE");
services::algo::AlgoTradingService::instance().run_backtest(
- strat, symbol, bt_start_date_->text(), bt_end_date_->text(), bt_capital_->value());
+ strat, symbol, bt_start_date_->date().toString(QStringLiteral("yyyy-MM-dd")),
+ bt_end_date_->date().toString(QStringLiteral("yyyy-MM-dd")), bt_capital_->value());
status_label_->setText(tr("Running backtest..."));
}
@@ -292,20 +273,15 @@ void StrategyBuilderPanel::on_deploy() {
status_label_->setText(tr("Save strategy first."));
return;
}
+ if (const QString err = validate(); !err.isEmpty()) {
+ validation_banner_->setText(err);
+ validation_banner_->setVisible(true);
+ return;
+ }
+ validation_banner_->setVisible(false);
// Build strategy from current UI state
- services::algo::AlgoStrategy strat;
- strat.id = QUuid::createUuid().toString(QUuid::WithoutBraces);
- strat.name = name_edit_->text().trimmed();
- strat.description = desc_edit_->text().trimmed();
- strat.timeframe = timeframe_combo_->currentText();
- strat.entry_conditions = entry_section_->conditions();
- strat.exit_conditions = exit_section_->conditions();
- strat.entry_logic = entry_section_->combined_logic();
- strat.exit_logic = exit_section_->combined_logic();
- strat.stop_loss = risk_panel_->stop_loss();
- strat.take_profit = risk_panel_->take_profit();
- strat.trailing_stop = risk_panel_->trailing_stop();
+ auto strat = build_strategy();
auto* dialog = new AlgoDeployDialog(strat, this);
if (dialog->exec() == QDialog::Accepted) {
@@ -325,6 +301,68 @@ void StrategyBuilderPanel::on_deploy() {
dialog->deleteLater();
}
+void StrategyBuilderPanel::load_template(int index) {
+ const auto tpls = services::algo::algo_strategy_templates();
+ const int i = index - 1; // index 0 is the "Templates…" placeholder
+ if (i < 0 || i >= tpls.size())
+ return;
+ const auto& t = tpls[i];
+
+ loaded_strategy_id_.clear(); // a template seeds a brand-new strategy
+ name_edit_->setText(t.name);
+ desc_edit_->setText(t.description);
+ timeframe_combo_->setCurrentText(t.timeframe);
+ entry_section_->set_conditions(t.entry, t.entry_logic);
+ exit_section_->set_conditions(t.exit, t.exit_logic);
+ risk_panel_->set_values(t.stop_loss, t.take_profit, 0.0, 1.0, 0.0);
+ report_panel_->clear();
+ status_label_->setText(tr("Loaded template: %1").arg(t.name));
+ template_combo_->setCurrentIndex(0); // reset to placeholder
+}
+
+void StrategyBuilderPanel::load_strategy(const services::algo::AlgoStrategy& s) {
+ loaded_strategy_id_ = s.id; // keep id → Save updates this strategy in place
+ name_edit_->setText(s.name);
+ desc_edit_->setText(s.description);
+ timeframe_combo_->setCurrentText(s.timeframe.isEmpty() ? QStringLiteral("5m") : s.timeframe);
+ entry_section_->set_conditions(s.entry_conditions, s.entry_logic.isEmpty() ? QStringLiteral("AND") : s.entry_logic);
+ exit_section_->set_conditions(s.exit_conditions, s.exit_logic.isEmpty() ? QStringLiteral("AND") : s.exit_logic);
+ risk_panel_->set_values(s.stop_loss, s.take_profit, s.trailing_stop, 1.0, 0.0,
+ s.position_size_pct > 0 ? s.position_size_pct : 100.0);
+ // Size the backtest range to the strategy's timeframe (daily needs years for
+ // long indicators; intraday must stay under Yahoo's history cap).
+ const QDate today = QDate::currentDate();
+ bt_start_date_->setDate(today.addDays(-services::algo::algo_default_lookback_days(s.timeframe)));
+ bt_end_date_->setDate(today);
+ report_panel_->clear();
+ validation_banner_->setVisible(false);
+ status_label_->setText(tr("Editing: %1").arg(s.name));
+}
+
+void StrategyBuilderPanel::load_and_backtest(const services::algo::AlgoStrategy& s,
+ const QString& symbol, const QString& start_date,
+ const QString& end_date) {
+ load_strategy(s);
+ if (!symbol.isEmpty())
+ symbol_combo_->setCurrentText(symbol);
+ const QDate sd = QDate::fromString(start_date, QStringLiteral("yyyy-MM-dd"));
+ const QDate ed = QDate::fromString(end_date, QStringLiteral("yyyy-MM-dd"));
+ if (sd.isValid())
+ bt_start_date_->setDate(sd);
+ if (ed.isValid())
+ bt_end_date_->setDate(ed);
+ on_backtest(); // reuses validation + service call; report renders in the right panel
+}
+
+QString StrategyBuilderPanel::validate() const {
+ if (entry_section_->conditions().isEmpty())
+ return tr("Add at least one entry condition.");
+ const bool no_exit = exit_section_->conditions().isEmpty();
+ if (no_exit && risk_panel_->stop_loss() <= 0.0 && risk_panel_->take_profit() <= 0.0)
+ return tr("Strategy never exits: add an exit condition or set a stop-loss / take-profit.");
+ return QString();
+}
+
void StrategyBuilderPanel::on_backtest_result(const QJsonObject& payload) {
status_label_->setText(tr("Backtest complete."));
display_backtest_result(payload);
@@ -336,43 +374,16 @@ void StrategyBuilderPanel::on_error(const QString& context, const QString& msg)
}
void StrategyBuilderPanel::display_backtest_result(const QJsonObject& payload) {
- kpi_grid_widget_->setVisible(true);
-
- double total_return = payload.value("total_return").toDouble();
- double sharpe = payload.value("sharpe_ratio").toDouble();
- double max_dd = payload.value("max_drawdown").toDouble();
- int total_trades = payload.value("total_trades").toInt();
- double win_rate = payload.value("win_rate").toDouble();
- double profit_factor = payload.value("profit_factor").toDouble();
- double final_val = payload.value("final_value").toDouble();
-
- kpi_total_return_val_->setText(
- QString("%1%2%").arg(total_return >= 0 ? "+" : "").arg(total_return, 0, 'f', 2));
- kpi_total_return_sub_->setText(QString("Final: $%1").arg(final_val, 0, 'f', 0));
-
- kpi_sharpe_val_->setText(QString::number(sharpe, 'f', 3));
- kpi_sharpe_sub_->setText(sharpe >= 1.0 ? "Excellent" : sharpe >= 0.5 ? "Good" : "Weak");
-
- kpi_max_dd_val_->setText(QString("-%1%").arg(qAbs(max_dd), 0, 'f', 2));
- kpi_max_dd_sub_->setText("Max Drawdown");
-
- kpi_win_rate_val_->setText(QString("%1%").arg(win_rate, 0, 'f', 1));
- kpi_win_rate_sub_->setText(win_rate >= 50.0 ? "Above average" : "Below average");
-
- kpi_trades_val_->setText(QString::number(total_trades));
- kpi_trades_sub_->setText("Total trades");
-
- kpi_profit_factor_val_->setText(QString::number(profit_factor, 'f', 2));
- kpi_profit_factor_sub_->setText(
- profit_factor >= 1.5 ? "Strong" : profit_factor >= 1.0 ? "Profitable" : "Losing");
+ report_panel_->set_result(payload);
}
void StrategyBuilderPanel::clear_results() {
- kpi_grid_widget_->setVisible(false);
+ report_panel_->clear();
}
QVariantMap StrategyBuilderPanel::save_draft() const {
QVariantMap draft;
+ draft["id"] = loaded_strategy_id_;
draft["name"] = name_edit_->text();
draft["description"] = desc_edit_->text();
draft["symbol"] = symbol_combo_->currentText();
@@ -386,10 +397,12 @@ QVariantMap StrategyBuilderPanel::save_draft() const {
draft["trailing_stop"] = risk_panel_->trailing_stop();
draft["quantity"] = risk_panel_->quantity();
draft["max_order_value"] = risk_panel_->max_order_value();
+ draft["capital_pct"] = risk_panel_->capital_pct();
return draft;
}
void StrategyBuilderPanel::restore_draft(const QVariantMap& draft) {
+ loaded_strategy_id_ = draft.value("id").toString();
name_edit_->setText(draft.value("name").toString());
desc_edit_->setText(draft.value("description").toString());
symbol_combo_->setCurrentText(draft.value("symbol").toString());
@@ -405,7 +418,8 @@ void StrategyBuilderPanel::restore_draft(const QVariantMap& draft) {
draft.value("take_profit", 5.0).toDouble(),
draft.value("trailing_stop", 0.0).toDouble(),
draft.value("quantity", 1.0).toDouble(),
- draft.value("max_order_value", 0.0).toDouble());
+ draft.value("max_order_value", 0.0).toDouble(),
+ draft.value("capital_pct", 100.0).toDouble());
}
} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/algo_trading/StrategyBuilderPanel.h b/fincept-qt/src/screens/algo_trading/StrategyBuilderPanel.h
index fb6f9a079..ef2172bb5 100644
--- a/fincept-qt/src/screens/algo_trading/StrategyBuilderPanel.h
+++ b/fincept-qt/src/screens/algo_trading/StrategyBuilderPanel.h
@@ -1,17 +1,20 @@
// src/screens/algo_trading/StrategyBuilderPanel.h
#pragma once
#include "services/algo_trading/AlgoTradingTypes.h"
+#include "ui/widgets/algo/BacktestReportPanel.h"
#include "ui/widgets/algo/ConditionSection.h"
#include "ui/widgets/algo/RiskManagementPanel.h"
#include "ui/widgets/algo/SymbolSearchCombo.h"
#include <QComboBox>
+#include <QDateEdit>
#include <QDoubleSpinBox>
#include <QJsonArray>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <QSplitter>
+#include <QString>
#include <QWidget>
namespace fincept::screens {
@@ -23,6 +26,11 @@ public:
QVariantMap save_draft() const;
void restore_draft(const QVariantMap& draft);
+ // Loads an existing strategy for editing (keeps its id so Save updates in place).
+ void load_strategy(const services::algo::AlgoStrategy& strategy);
+ // Loads a strategy, sets symbol/date range, and runs a backtest immediately.
+ void load_and_backtest(const services::algo::AlgoStrategy& strategy, const QString& symbol,
+ const QString& start_date, const QString& end_date);
private slots:
void on_save();
@@ -39,12 +47,20 @@ private:
QWidget* build_right_panel();
void display_backtest_result(const QJsonObject& data);
void clear_results();
+ // Builds an AlgoStrategy from the current UI state, reusing the same id for
+ // the lifetime of this editor so repeated Save/Backtest/Deploy update one
+ // strategy instead of spawning duplicates.
+ services::algo::AlgoStrategy build_strategy();
+ void load_template(int index);
+ // Returns a human-readable error if the strategy is unrunnable, else empty.
+ QString validate() const;
// Top toolbar
QLineEdit* name_edit_ = nullptr;
QLineEdit* desc_edit_ = nullptr;
ui::algo::SymbolSearchCombo* symbol_combo_ = nullptr;
QComboBox* timeframe_combo_ = nullptr;
+ QComboBox* template_combo_ = nullptr;
QPushButton* save_btn_ = nullptr;
QPushButton* backtest_btn_ = nullptr;
QPushButton* deploy_btn_ = nullptr;
@@ -56,24 +72,18 @@ private:
// Right panel — backtest
QDoubleSpinBox* bt_capital_ = nullptr;
- QLineEdit* bt_start_date_ = nullptr;
- QLineEdit* bt_end_date_ = nullptr;
+ QDateEdit* bt_start_date_ = nullptr;
+ QDateEdit* bt_end_date_ = nullptr;
QLabel* status_label_ = nullptr;
- // KPI card labels
- QLabel* kpi_total_return_val_ = nullptr;
- QLabel* kpi_total_return_sub_ = nullptr;
- QLabel* kpi_sharpe_val_ = nullptr;
- QLabel* kpi_sharpe_sub_ = nullptr;
- QLabel* kpi_max_dd_val_ = nullptr;
- QLabel* kpi_max_dd_sub_ = nullptr;
- QLabel* kpi_win_rate_val_ = nullptr;
- QLabel* kpi_win_rate_sub_ = nullptr;
- QLabel* kpi_trades_val_ = nullptr;
- QLabel* kpi_trades_sub_ = nullptr;
- QLabel* kpi_profit_factor_val_ = nullptr;
- QLabel* kpi_profit_factor_sub_ = nullptr;
- QWidget* kpi_grid_widget_ = nullptr;
+ // Identity of the strategy currently being edited (empty => not yet minted).
+ QString loaded_strategy_id_;
+
+ // Right panel — backtest performance report (KPIs, equity, drawdown, trades)
+ ui::algo::BacktestReportPanel* report_panel_ = nullptr;
+
+ // Inline validation banner shown above the builder when a guard fails.
+ QLabel* validation_banner_ = nullptr;
};
} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/algo_trading/StrategyListPanel.cpp b/fincept-qt/src/screens/algo_trading/StrategyListPanel.cpp
index 07a5c88db..e2ced2c68 100644
--- a/fincept-qt/src/screens/algo_trading/StrategyListPanel.cpp
+++ b/fincept-qt/src/screens/algo_trading/StrategyListPanel.cpp
@@ -9,8 +9,14 @@
#include <algorithm>
+#include <QDate>
+#include <QDateEdit>
+#include <QDialog>
+#include <QDialogButtonBox>
+#include <QFormLayout>
#include <QHeaderView>
#include <QHBoxLayout>
+#include <QLineEdit>
#include <QMessageBox>
#include <QPushButton>
#include <QScrollArea>
@@ -113,8 +119,8 @@ void StrategyListPanel::build_ui() {
// ── Table ────────────────────────────────────────────────────────────────
table_ = new QTableWidget(this);
- table_->setColumnCount(6); // #, NAME, CATEGORY, ID, DEPLOY, DELETE
- table_->setHorizontalHeaderLabels({"#", "STRATEGY NAME", "CATEGORY", "ID", "", ""});
+ table_->setColumnCount(8); // #, NAME, CATEGORY, ID, EDIT, BACKTEST, DEPLOY, DELETE
+ table_->setHorizontalHeaderLabels({"#", "STRATEGY NAME", "CATEGORY", "ID", "", "", "", ""});
table_->verticalHeader()->setVisible(false);
table_->setSelectionBehavior(QAbstractItemView::SelectRows);
table_->setSelectionMode(QAbstractItemView::SingleSelection);
@@ -130,10 +136,12 @@ void StrategyListPanel::build_ui() {
table_->horizontalHeader()->setSectionResizeMode(4, QHeaderView::Fixed);
table_->horizontalHeader()->setSectionResizeMode(5, QHeaderView::Fixed);
table_->setColumnWidth(0, 40);
- table_->setColumnWidth(2, 180);
- table_->setColumnWidth(3, 120);
- table_->setColumnWidth(4, 80);
- table_->setColumnWidth(5, 70);
+ table_->setColumnWidth(2, 150);
+ table_->setColumnWidth(3, 100);
+ table_->setColumnWidth(4, 56);
+ table_->setColumnWidth(5, 76);
+ table_->setColumnWidth(6, 72);
+ table_->setColumnWidth(7, 66);
table_->verticalHeader()->setDefaultSectionSize(30);
table_->setStyleSheet(
QString("QTableWidget { background:%1; alternate-background-color:%2;"
@@ -242,36 +250,28 @@ void StrategyListPanel::render_page() {
id_item->setForeground(QColor(colors::TEXT_TERTIARY()));
table_->setItem(row, 3, id_item);
- // Col 4: DEPLOY button
- auto* deploy_btn = new QPushButton("DEPLOY", table_);
- deploy_btn->setCursor(Qt::PointingHandCursor);
- deploy_btn->setFixedHeight(22);
- deploy_btn->setStyleSheet(
- QString("QPushButton { background: transparent; color: %1; border: 1px solid %1;"
- " font-size: %2px; font-weight: 700; font-family: %3; padding: 1px 8px; }"
- "QPushButton:hover { background: rgba(217,119,6,0.1); }")
- .arg(colors::AMBER())
- .arg(fonts::TINY)
- .arg(fonts::DATA_FAMILY()));
- connect(deploy_btn, &QPushButton::clicked, this, [this, row]() { on_deploy_clicked(row); });
- table_->setCellWidget(row, 4, deploy_btn);
-
- // Col 5: DELETE button (only for DSL strategies — QC strategies come from file registry)
- const bool is_dsl = !s.id.startsWith("FCT-");
- if (is_dsl) {
- auto* delete_btn = new QPushButton("DELETE", table_);
- delete_btn->setCursor(Qt::PointingHandCursor);
- delete_btn->setFixedHeight(22);
- delete_btn->setStyleSheet(
+ auto make_btn = [&](const QString& text, const QString& color, const QString& hover,
+ int col, auto handler) {
+ auto* btn = new QPushButton(text, table_);
+ btn->setCursor(Qt::PointingHandCursor);
+ btn->setFixedHeight(22);
+ btn->setStyleSheet(
QString("QPushButton { background: transparent; color: %1; border: 1px solid %1;"
" font-size: %2px; font-weight: 700; font-family: %3; padding: 1px 8px; }"
- "QPushButton:hover { background: rgba(220,38,38,0.1); }")
- .arg(colors::NEGATIVE())
+ "QPushButton:hover { background: %4; }")
+ .arg(color)
.arg(fonts::TINY)
- .arg(fonts::DATA_FAMILY()));
- connect(delete_btn, &QPushButton::clicked, this, [this, row]() { on_delete_clicked(row); });
- table_->setCellWidget(row, 5, delete_btn);
- }
+ .arg(fonts::DATA_FAMILY())
+ .arg(hover));
+ connect(btn, &QPushButton::clicked, this, handler);
+ table_->setCellWidget(row, col, btn);
+ };
+
+ // Col 4: EDIT (Builder). 5: BACKTEST. 6: DEPLOY. 7: DELETE.
+ make_btn("EDIT", colors::CYAN(), "rgba(34,211,238,0.1)", 4, [this, row]() { on_edit_clicked(row); });
+ make_btn("BACKTEST", colors::POSITIVE(), "rgba(22,163,74,0.1)", 5, [this, row]() { on_backtest_clicked(row); });
+ make_btn("DEPLOY", colors::AMBER(), "rgba(217,119,6,0.1)", 6, [this, row]() { on_deploy_clicked(row); });
+ make_btn("DELETE", colors::NEGATIVE(), "rgba(220,38,38,0.1)", 7, [this, row]() { on_delete_clicked(row); });
}
update_pagination_controls();
@@ -373,6 +373,58 @@ void StrategyListPanel::on_error(const QString& context, const QString& msg) {
LOG_ERROR("AlgoTrading", QString("StrategyList error [%1]: %2").arg(context, msg));
}
+void StrategyListPanel::on_edit_clicked(int row) {
+ const int abs_index = current_page_ * kPageSize + row;
+ if (abs_index < 0 || abs_index >= filtered_.size())
+ return;
+ emit edit_requested(filtered_[abs_index]); // AlgoTradingScreen routes to the Builder
+}
+
+void StrategyListPanel::on_backtest_clicked(int row) {
+ const int abs_index = current_page_ * kPageSize + row;
+ if (abs_index < 0 || abs_index >= filtered_.size())
+ return;
+ const auto& strategy = filtered_[abs_index];
+
+ // Prompt for symbol + date range before running.
+ QDialog dlg(this);
+ dlg.setWindowTitle(tr("Backtest: %1").arg(strategy.name));
+ auto* form = new QFormLayout(&dlg);
+
+ auto* symbol = new QLineEdit(QStringLiteral("RELIANCE"), &dlg);
+ symbol->setPlaceholderText(tr("e.g. RELIANCE, AAPL"));
+ const QDate today = QDate::currentDate();
+ // Default range sized to the strategy's timeframe (daily needs years for
+ // SMA200; intraday must stay under Yahoo's history cap).
+ const int lookback = services::algo::algo_default_lookback_days(strategy.timeframe);
+ auto* start = new QDateEdit(today.addDays(-lookback), &dlg);
+ auto* end = new QDateEdit(today, &dlg);
+ for (QDateEdit* d : {start, end}) {
+ d->setCalendarPopup(true);
+ d->setDisplayFormat(QStringLiteral("yyyy-MM-dd"));
+ d->setMinimumDate(QDate(2000, 1, 1));
+ d->setMaximumDate(today);
+ }
+ form->addRow(tr("Symbol"), symbol);
+ form->addRow(tr("Start"), start);
+ form->addRow(tr("End"), end);
+
+ auto* buttons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, &dlg);
+ buttons->button(QDialogButtonBox::Ok)->setText(tr("Run Backtest"));
+ form->addRow(buttons);
+ connect(buttons, &QDialogButtonBox::accepted, &dlg, &QDialog::accept);
+ connect(buttons, &QDialogButtonBox::rejected, &dlg, &QDialog::reject);
+
+ if (dlg.exec() != QDialog::Accepted)
+ return;
+ if (symbol->text().trimmed().isEmpty() || start->date() >= end->date())
+ return;
+
+ emit backtest_requested(strategy, symbol->text().trimmed(),
+ start->date().toString(QStringLiteral("yyyy-MM-dd")),
+ end->date().toString(QStringLiteral("yyyy-MM-dd")));
+}
+
void StrategyListPanel::on_deploy_clicked(int row) {
const int abs_index = current_page_ * kPageSize + row;
if (abs_index < 0 || abs_index >= filtered_.size())
diff --git a/fincept-qt/src/screens/algo_trading/StrategyListPanel.h b/fincept-qt/src/screens/algo_trading/StrategyListPanel.h
index 28f233c7b..faefadde0 100644
--- a/fincept-qt/src/screens/algo_trading/StrategyListPanel.h
+++ b/fincept-qt/src/screens/algo_trading/StrategyListPanel.h
@@ -12,17 +12,26 @@
namespace fincept::screens {
-/// Strategy list — compact table with pagination, loads from registry_index.json in <50ms.
+/// Strategy list — compact paginated table of DSL strategies loaded from the
+/// algo_strategies DB table (curated library + user-created). Per-row EDIT opens
+/// the Builder pre-filled; DEPLOY and DELETE act on the strategy.
class StrategyListPanel : public QWidget {
Q_OBJECT
public:
explicit StrategyListPanel(QWidget* parent = nullptr);
+ signals:
+ void edit_requested(fincept::services::algo::AlgoStrategy strategy);
+ void backtest_requested(fincept::services::algo::AlgoStrategy strategy, QString symbol,
+ QString start_date, QString end_date);
+
private slots:
void on_strategies_loaded(QVector<fincept::services::algo::AlgoStrategy> strategies);
void on_sort_changed(int index);
void on_error(const QString& context, const QString& msg);
void on_filter_changed(const QString& text);
+ void on_edit_clicked(int row);
+ void on_backtest_clicked(int row);
void on_deploy_clicked(int row);
void on_delete_clicked(int row);
void go_to_page(int page);
diff --git a/fincept-qt/src/screens/alt_investments/AltInvestmentsScreen.cpp b/fincept-qt/src/screens/alt_investments/AltInvestmentsScreen.cpp
index 98e5dd090..cd4a5fa09 100644
--- a/fincept-qt/src/screens/alt_investments/AltInvestmentsScreen.cpp
+++ b/fincept-qt/src/screens/alt_investments/AltInvestmentsScreen.cpp
@@ -32,73 +32,73 @@ static const QString kStyle =
QStringLiteral("#altScreen { background: %1; }"
"#altHeader { background: %2; border-bottom: 2px solid %3; padding: 0 16px; }"
- "#altHeaderTitle { color: %4; font-size: 13px; font-weight: 700; background: transparent; }"
- "#altHeaderSub { color: %5; font-size: 9px; letter-spacing: 0.8px; background: transparent; }"
- "#altHeaderBadge { color: %6; font-size: 8px; font-weight: 700; letter-spacing: 0.5px;"
+ "#altHeaderTitle { color: %4; font-size: 15px; font-weight: 700; background: transparent; }"
+ "#altHeaderSub { color: %5; font-size: 11px; letter-spacing: 0.8px; background: transparent; }"
+ "#altHeaderBadge { color: %6; font-size: 10px; font-weight: 700; letter-spacing: 0.5px;"
" background: rgba(22,163,74,0.18); border: 1px solid rgba(22,163,74,0.4); padding: 2px 8px; }"
"#altLeftPanel { background: %7; border-right: 1px solid %8; }"
- "#altLeftTitle { color: %5; font-size: 9px; font-weight: 700; letter-spacing: 0.8px;"
+ "#altLeftTitle { color: %5; font-size: 11px; font-weight: 700; letter-spacing: 0.8px;"
" background: %2; padding: 8px 12px; border-bottom: 1px solid %8; }"
"#altCatBtn { background: transparent; color: %5; border: none; border-bottom: 1px solid %8;"
- " text-align: left; font-size: 11px; padding: 9px 14px; }"
+ " text-align: left; font-size: 13px; padding: 9px 14px; }"
"#altCatBtn:hover { color: %4; background: %12; }"
"#altCatBtn[active=\"true\"] { color: %3; font-weight: 700;"
" background: rgba(217,119,6,0.08); border-left: 3px solid %3; padding-left: 11px; }"
"#altCenterPanel { background: %1; }"
"#altCenterTitleBar { background: %2; border-bottom: 1px solid %8; }"
- "#altCenterTitle { color: %4; font-size: 12px; font-weight: 700; background: transparent; }"
- "#altCenterDesc { color: %5; font-size: 10px; background: transparent; }"
- "#altComboLabel { color: %5; font-size: 9px; font-weight: 700;"
+ "#altCenterTitle { color: %4; font-size: 14px; font-weight: 700; background: transparent; }"
+ "#altCenterDesc { color: %5; font-size: 12px; background: transparent; }"
+ "#altComboLabel { color: %5; font-size: 11px; font-weight: 700;"
" letter-spacing: 0.5px; background: transparent; }"
"#altFormPanel { background: %7; border: 1px solid %8; }"
"#altFormHeader { background: %2; border-bottom: 1px solid %8; padding: 0 12px; }"
- "#altFormTitle { color: %4; font-size: 10px; font-weight: 700; background: transparent; }"
- "#altFieldLabel { color: %5; font-size: 9px; font-weight: 700;"
+ "#altFormTitle { color: %4; font-size: 12px; font-weight: 700; background: transparent; }"
+ "#altFieldLabel { color: %5; font-size: 11px; font-weight: 700;"
" letter-spacing: 0.5px; background: transparent; }"
"QLineEdit { background: %1; color: %4; border: 1px solid %8;"
- " padding: 5px 8px; font-size: 11px; }"
+ " padding: 5px 8px; font-size: 13px; }"
"QLineEdit:focus { border-color: %9; }"
"QDoubleSpinBox { background: %1; color: %4; border: 1px solid %8;"
- " padding: 5px 8px; font-size: 11px; }"
+ " padding: 5px 8px; font-size: 13px; }"
"QDoubleSpinBox:focus { border-color: %9; }"
"QDoubleSpinBox::up-button, QDoubleSpinBox::down-button { width: 0; }"
"QComboBox { background: %1; color: %4; border: 1px solid %8;"
- " padding: 5px 8px; font-size: 11px; }"
+ " padding: 5px 8px; font-size: 13px; }"
"QComboBox::drop-down { border: none; width: 18px; }"
"QComboBox QAbstractItemView { background: %2; color: %4; border: 1px solid %8;"
" selection-background-color: %3; selection-color: %1; outline: none; }"
"#altAnalyzeBtn { background: %3; color: %1; border: none; padding: 7px 20px;"
- " font-size: 10px; font-weight: 700; letter-spacing: 0.5px; }"
+ " font-size: 12px; font-weight: 700; letter-spacing: 0.5px; }"
"#altAnalyzeBtn:hover { background: #FF8800; }"
"#altAnalyzeBtn:disabled { background: %10; color: %11; }"
"#altRightPanel { background: %7; border-left: 1px solid %8; }"
- "#altRightTitle { color: %5; font-size: 9px; font-weight: 700; letter-spacing: 0.8px;"
+ "#altRightTitle { color: %5; font-size: 11px; font-weight: 700; letter-spacing: 0.8px;"
" background: %2; padding: 8px 12px; border-bottom: 1px solid %8; }"
- "#altVerdictBadge { font-size: 11px; font-weight: 700; padding: 4px 14px;"
+ "#altVerdictBadge { font-size: 13px; font-weight: 700; padding: 4px 14px;"
" letter-spacing: 0.5px; }"
- "#altVerdictRating { color: %13; font-size: 14px; font-weight: 700; background: transparent; }"
- "#altVerdictRec { color: %4; font-size: 10px; background: transparent; }"
+ "#altVerdictRating { color: %13; font-size: 16px; font-weight: 700; background: transparent; }"
+ "#altVerdictRec { color: %4; font-size: 12px; background: transparent; }"
"#altMetricRow { background: transparent; border-bottom: 1px solid %8; }"
- "#altMetricKey { color: %5; font-size: 10px; background: transparent; }"
- "#altMetricVal { color: %13; font-size: 10px; font-weight: 700; background: transparent; }"
- "#altMetricSection { color: %3; font-size: 9px; font-weight: 700; letter-spacing: 0.8px;"
+ "#altMetricKey { color: %5; font-size: 12px; background: transparent; }"
+ "#altMetricVal { color: %13; font-size: 12px; font-weight: 700; background: transparent; }"
+ "#altMetricSection { color: %3; font-size: 11px; font-weight: 700; letter-spacing: 0.8px;"
" background: %2; padding: 4px 10px; border-top: 1px solid %8; }"
- "#altMetricBullet { color: %5; font-size: 10px; background: transparent; }"
- "#altMetricBulletVal { color: %4; font-size: 10px; background: transparent; }"
- "#altMetricWarn { color: #FFD700; font-size: 10px; background: transparent; }"
- "#altMetricGood { color: %6; font-size: 10px; background: transparent; }"
- "#altMetricBad { color: %14; font-size: 10px; background: transparent; }"
+ "#altMetricBullet { color: %5; font-size: 12px; background: transparent; }"
+ "#altMetricBulletVal { color: %4; font-size: 12px; background: transparent; }"
+ "#altMetricWarn { color: #FFD700; font-size: 12px; background: transparent; }"
+ "#altMetricGood { color: %6; font-size: 12px; background: transparent; }"
+ "#altMetricBad { color: %14; font-size: 12px; background: transparent; }"
"#altStatusBar { background: %2; border-top: 1px solid %8; }"
- "#altStatusText { color: %5; font-size: 9px; background: transparent; }"
- "#altStatusHigh { color: %13; font-size: 9px; background: transparent; }"
+ "#altStatusText { color: %5; font-size: 11px; background: transparent; }"
+ "#altStatusHigh { color: %13; font-size: 11px; background: transparent; }"
"QSplitter::handle { background: %8; }"
"QScrollBar:vertical { background: %1; width: 5px; border: none; }"
@@ -503,7 +503,7 @@ QString AltInvestmentsScreen::format_value(const QJsonValue& v) const {
void AltInvestmentsScreen::display_error(const QString& error) {
verdict_badge_->setText("ERROR");
verdict_badge_->setStyleSheet(QString("color:%1; background:rgba(220,38,38,0.15);"
- " font-size:11px; font-weight:700; padding:4px 14px;")
+ " font-size:13px; font-weight:700; padding:4px 14px;")
.arg(colors::NEGATIVE()));
verdict_rating_->clear();
verdict_rec_->setText(error);
diff --git a/fincept-qt/src/screens/alt_investments/AltInvestmentsScreen_Analysis.cpp b/fincept-qt/src/screens/alt_investments/AltInvestmentsScreen_Analysis.cpp
index 4aab5c3e1..fbf9ffc5a 100644
--- a/fincept-qt/src/screens/alt_investments/AltInvestmentsScreen_Analysis.cpp
+++ b/fincept-qt/src/screens/alt_investments/AltInvestmentsScreen_Analysis.cpp
@@ -7,6 +7,7 @@
#include "screens/alt_investments/AltInvestmentsScreen.h"
+#include "core/currency/Currency.h"
#include "core/logging/Logger.h"
#include "core/session/ScreenStateManager.h"
#include "services/python_cli/PythonCliService.h"
@@ -34,6 +35,25 @@ namespace fincept::screens {
using namespace fincept::ui;
+// Currency-aware field helpers: labels ending in "($)" and spin prefixes of "$"
+// track the user's preferred currency live; everything else is left untouched.
+static void set_alt_field_label(QLabel* lbl, const QString& label) {
+ if (label.endsWith("($)")) {
+ QString base = label;
+ base.chop(3); // strip "($)"
+ cur::bindLabel(lbl, base + "(%1)");
+ } else {
+ lbl->setText(label);
+ }
+}
+
+static void apply_alt_field_prefix(QDoubleSpinBox* sp, const QString& prefix) {
+ if (prefix == QLatin1String("$"))
+ cur::bindPrefix(sp);
+ else if (!prefix.isEmpty())
+ sp->setPrefix(prefix);
+}
+
static AltField text_field(const QString& key, const QString& label, const QString& def = "") {
AltField f;
f.key = key;
@@ -392,7 +412,8 @@ void AltInvestmentsScreen::rebuild_form(int cat, int ana) {
auto* cl = new QVBoxLayout(col);
cl->setContentsMargins(0, 0, 0, 0);
cl->setSpacing(3);
- auto* lbl = new QLabel(field.label);
+ auto* lbl = new QLabel;
+ set_alt_field_label(lbl, field.label);
lbl->setObjectName("altFieldLabel");
cl->addWidget(lbl);
auto* sp = new QDoubleSpinBox;
@@ -400,8 +421,7 @@ void AltInvestmentsScreen::rebuild_form(int cat, int ana) {
sp->setValue(field.default_val);
sp->setDecimals(field.decimals);
sp->setButtonSymbols(QAbstractSpinBox::NoButtons);
- if (!field.prefix.isEmpty())
- sp->setPrefix(field.prefix);
+ apply_alt_field_prefix(sp, field.prefix);
if (!field.suffix.isEmpty())
sp->setSuffix(field.suffix);
cl->addWidget(sp);
@@ -418,7 +438,8 @@ void AltInvestmentsScreen::rebuild_form(int cat, int ana) {
auto* cl = new QVBoxLayout(col);
cl->setContentsMargins(0, 0, 0, 0);
cl->setSpacing(3);
- auto* lbl = new QLabel(f.label);
+ auto* lbl = new QLabel;
+ set_alt_field_label(lbl, f.label);
lbl->setObjectName("altFieldLabel");
cl->addWidget(lbl);
@@ -438,8 +459,7 @@ void AltInvestmentsScreen::rebuild_form(int cat, int ana) {
sp->setValue(f.default_val);
sp->setDecimals(f.decimals);
sp->setButtonSymbols(QAbstractSpinBox::NoButtons);
- if (!f.prefix.isEmpty())
- sp->setPrefix(f.prefix);
+ apply_alt_field_prefix(sp, f.prefix);
if (!f.suffix.isEmpty())
sp->setSuffix(f.suffix);
cl->addWidget(sp);
@@ -547,7 +567,7 @@ void AltInvestmentsScreen::run_analysis(const QString& command, const QJsonObjec
set_loading(true);
verdict_badge_->setText("ANALYZING...");
verdict_badge_->setStyleSheet(QString("color:%1; background:rgba(217,119,6,0.15);"
- " font-size:11px; font-weight:700; padding:4px 14px;")
+ " font-size:13px; font-weight:700; padding:4px 14px;")
.arg(colors::AMBER()));
verdict_rating_->clear();
verdict_rec_->clear();
@@ -625,7 +645,7 @@ void AltInvestmentsScreen::display_verdict(const QJsonObject& result, const QStr
}
verdict_badge_->setText(category.toUpper());
- verdict_badge_->setStyleSheet(QString("color:%1; background:%2; font-size:11px; font-weight:700;"
+ verdict_badge_->setStyleSheet(QString("color:%1; background:%2; font-size:13px; font-weight:700;"
" padding:4px 14px; letter-spacing:0.5px;")
.arg(badge_color, badge_bg));
diff --git a/fincept-qt/src/screens/alt_investments/AltInvestmentsScreen_Layout.cpp b/fincept-qt/src/screens/alt_investments/AltInvestmentsScreen_Layout.cpp
index b0c972876..93bf0c652 100644
--- a/fincept-qt/src/screens/alt_investments/AltInvestmentsScreen_Layout.cpp
+++ b/fincept-qt/src/screens/alt_investments/AltInvestmentsScreen_Layout.cpp
@@ -220,7 +220,7 @@ QWidget* AltInvestmentsScreen::create_right_panel() {
verdict_badge_ = new QLabel("AWAITING ANALYSIS");
verdict_badge_->setObjectName("altVerdictBadge");
verdict_badge_->setAlignment(Qt::AlignCenter);
- verdict_badge_->setStyleSheet(QString("color:%1; background:%2; font-size:11px; font-weight:700;"
+ verdict_badge_->setStyleSheet(QString("color:%1; background:%2; font-size:13px; font-weight:700;"
" padding:4px 14px; letter-spacing:0.5px;")
.arg(colors::TEXT_DIM(), colors::BG_RAISED()));
val->addWidget(verdict_badge_);
diff --git a/fincept-qt/src/screens/auth/PricingScreen.cpp b/fincept-qt/src/screens/auth/PricingScreen.cpp
index 62e93cfab..933275959 100644
--- a/fincept-qt/src/screens/auth/PricingScreen.cpp
+++ b/fincept-qt/src/screens/auth/PricingScreen.cpp
@@ -2,6 +2,7 @@
#include "auth/AuthApi.h"
#include "auth/AuthManager.h"
+#include "core/currency/Currency.h"
#include "ui/theme/Theme.h"
#include <QApplication>
@@ -370,7 +371,9 @@ QWidget* PricingScreen::create_plan_card(const auth::SubscriptionPlan& plan, int
.arg(MF));
vl->addWidget(price);
} else {
- auto* price = new QLabel(QString("$%1").arg(plan.price_usd, 0, 'f', 0));
+ // Symbol-only (values are stored USD; not FX-converted). Preserve the
+ // whole-number format used for plan prices.
+ auto* price = new QLabel(cur::symbol() + QString::number(plan.price_usd, 'f', 0));
price->setAlignment(Qt::AlignCenter);
price->setStyleSheet(QString("color: %1; font-size: 28px; font-weight: 700; "
"background: transparent; %2")
diff --git a/fincept-qt/src/screens/backtesting/BacktestingScreen_Layout.cpp b/fincept-qt/src/screens/backtesting/BacktestingScreen_Layout.cpp
index 61ef44acf..b8705d6f8 100644
--- a/fincept-qt/src/screens/backtesting/BacktestingScreen_Layout.cpp
+++ b/fincept-qt/src/screens/backtesting/BacktestingScreen_Layout.cpp
@@ -493,7 +493,8 @@ QWidget* BacktestingScreen::build_right_panel() {
exec_title->setStyleSheet(section_style);
exec_layout->addWidget(exec_title);
- auto* cap_lbl = new QLabel("INITIAL CAPITAL ($)", execution_section_);
+ auto* cap_lbl = new QLabel(execution_section_);
+ cur::bindLabel(cap_lbl, "INITIAL CAPITAL (%1)");
cap_lbl->setStyleSheet(label_style);
exec_layout->addWidget(cap_lbl);
capital_spin_ = new QDoubleSpinBox(execution_section_);
@@ -610,7 +611,7 @@ QWidget* BacktestingScreen::build_right_panel() {
pos_sizing_value_spin_->setRange(1, 100);
pos_sizing_value_spin_->setValue(100);
} else if (text == "fixed") {
- pos_sizing_value_label_->setText("SIZE ($)");
+ pos_sizing_value_label_->setText(QString("SIZE (%1)").arg(cur::symbol()));
pos_sizing_value_spin_->setSuffix("");
pos_sizing_value_spin_->setRange(1, 1e9);
pos_sizing_value_spin_->setValue(10000);
diff --git a/fincept-qt/src/screens/backtesting/BacktestingScreen_Results.cpp b/fincept-qt/src/screens/backtesting/BacktestingScreen_Results.cpp
index 8f4aa282b..237801318 100644
--- a/fincept-qt/src/screens/backtesting/BacktestingScreen_Results.cpp
+++ b/fincept-qt/src/screens/backtesting/BacktestingScreen_Results.cpp
@@ -542,7 +542,7 @@ void BacktestingScreen::display_result(const QString& command, const QJsonObject
auto* y_axis = new QValueAxis;
double margin = (y_max - y_min) * 0.05;
y_axis->setRange(y_min - margin, y_max + margin);
- y_axis->setLabelFormat("$%.0f");
+ y_axis->setLabelFormat(cur::symbol() + "%.0f");
y_axis->setLabelsColor(QColor(ui::colors::TEXT_TERTIARY()));
y_axis->setGridLineColor(QColor(ui::colors::BORDER_DIM()));
chart->addAxis(y_axis, Qt::AlignLeft);
diff --git a/fincept-qt/src/screens/backtesting/BacktestingScreen_internal.h b/fincept-qt/src/screens/backtesting/BacktestingScreen_internal.h
index 87a119e28..ed13ab2f3 100644
--- a/fincept-qt/src/screens/backtesting/BacktestingScreen_internal.h
+++ b/fincept-qt/src/screens/backtesting/BacktestingScreen_internal.h
@@ -10,6 +10,7 @@
#pragma once
+#include "core/currency/Currency.h"
#include "services/backtesting/BacktestingTypes.h"
#include <QComboBox>
@@ -127,13 +128,10 @@ inline QString fmt_metric(const QString& key, const QJsonValue& val) {
if (ratio_metric_keys().contains(key))
return QString::number(v, 'f', std::abs(v) >= 10.0 ? 2 : 4);
- // Currency-like large values
- if (std::abs(v) >= 1e9)
- return QString("$%1B").arg(v / 1e9, 0, 'f', 1);
- if (std::abs(v) >= 1e6)
- return QString("$%1M").arg(v / 1e6, 0, 'f', 1);
+ // Currency-like large values — follow the preferred currency (backtest
+ // capital/equity is user-denominated, not market data).
if (std::abs(v) >= 1e3)
- return QString("$%1K").arg(v / 1e3, 0, 'f', 0);
+ return cur::money(v, /*compact=*/true);
return QString::number(v, 'f', 4);
}
diff --git a/fincept-qt/src/screens/dashboard/widgets/PortfolioSummaryWidget.cpp b/fincept-qt/src/screens/dashboard/widgets/PortfolioSummaryWidget.cpp
index 8a463729d..2482ff58a 100644
--- a/fincept-qt/src/screens/dashboard/widgets/PortfolioSummaryWidget.cpp
+++ b/fincept-qt/src/screens/dashboard/widgets/PortfolioSummaryWidget.cpp
@@ -1,5 +1,6 @@
#include "screens/dashboard/widgets/PortfolioSummaryWidget.h"
+#include "core/currency/Currency.h"
#include "datahub/DataHub.h"
#include "datahub/DataHubMetaTypes.h"
#include "services/portfolio/PortfolioService.h"
@@ -228,6 +229,9 @@ void PortfolioSummaryWidget::load_holdings() {
emit config_changed(config());
}
selected_portfolio_name_ = picked->name;
+ // This tile shows the portfolio's OWN currency (intrinsic) — not the global
+ // preferred currency. Values are not converted; we only use the right symbol.
+ selected_portfolio_currency_ = picked->currency.isEmpty() ? QStringLiteral("USD") : picked->currency;
portfolio_name_lbl_->setText(picked->name.toUpper());
portfolio_name_lbl_->setVisible(true);
@@ -276,9 +280,10 @@ void PortfolioSummaryWidget::render_empty(const QString& message) {
.arg(ui::colors::TEXT_TERTIARY()));
list_layout_->addWidget(empty);
list_layout_->addStretch();
- total_value_lbl_->setText(QStringLiteral("$0"));
- day_pnl_lbl_->setText(QStringLiteral("$0"));
- total_pnl_lbl_->setText(QStringLiteral("$0"));
+ const QString sym = cur::symbol_for(selected_portfolio_currency_);
+ total_value_lbl_->setText(sym + QStringLiteral("0"));
+ day_pnl_lbl_->setText(sym + QStringLiteral("0"));
+ total_pnl_lbl_->setText(sym + QStringLiteral("0"));
num_holdings_lbl_->setText(QStringLiteral("0"));
// Reset the colour overrides applied during a populated render so the
@@ -339,6 +344,10 @@ void PortfolioSummaryWidget::render(const QVector<Holding>& holdings,
last_holdings_ = holdings;
last_quotes_ = quotes;
+ // Portfolio's own currency symbol (intrinsic — not the global preference,
+ // and values are not converted: symbol-only).
+ const QString sym = cur::symbol_for(selected_portfolio_currency_);
+
QMap<QString, const services::QuoteData*> qmap;
for (const auto& q : last_quotes_)
qmap[q.symbol] = &q;
@@ -383,10 +392,13 @@ void PortfolioSummaryWidget::render(const QVector<Holding>& holdings,
cell(h.symbol, 1, Qt::AlignLeft, ui::colors::TEXT_PRIMARY);
cell(QString::number(h.shares, 'f', h.shares == (int)h.shares ? 0 : 2), 1, Qt::AlignRight,
ui::colors::TEXT_SECONDARY);
- cell(price > 0 ? QString("$%1").arg(price, 0, 'f', 2) : "--", 1, Qt::AlignRight, ui::colors::TEXT_PRIMARY);
- cell(value > 0 ? QString("$%1").arg(value, 0, 'f', 0) : "--", 1, Qt::AlignRight, ui::colors::TEXT_PRIMARY);
+ cell(price > 0 ? sym + QString::number(price, 'f', 2) : QStringLiteral("--"), 1, Qt::AlignRight,
+ ui::colors::TEXT_PRIMARY);
+ cell(value > 0 ? sym + QString::number(value, 'f', 0) : QStringLiteral("--"), 1, Qt::AlignRight,
+ ui::colors::TEXT_PRIMARY);
- QString pnl_str = pnl >= 0 ? QString("+$%1").arg(pnl, 0, 'f', 0) : QString("-$%1").arg(-pnl, 0, 'f', 0);
+ QString pnl_str = pnl >= 0 ? QStringLiteral("+") + sym + QString::number(pnl, 'f', 0)
+ : QStringLiteral("-") + sym + QString::number(-pnl, 'f', 0);
cell(pnl_str, 1, Qt::AlignRight, pnl >= 0 ? ui::colors::POSITIVE : ui::colors::NEGATIVE);
list_layout_->addWidget(row);
@@ -394,13 +406,14 @@ void PortfolioSummaryWidget::render(const QVector<Holding>& holdings,
}
list_layout_->addStretch();
- total_value_lbl_->setText(QString("$%1").arg(total_value, 0, 'f', 0));
+ total_value_lbl_->setText(sym + QString::number(total_value, 'f', 0));
num_holdings_lbl_->setText(QString::number(holdings.size()));
double total_pnl = total_value - total_cost;
- QString day_str = day_pnl >= 0 ? QString("+$%1").arg(day_pnl, 0, 'f', 0) : QString("-$%1").arg(-day_pnl, 0, 'f', 0);
- QString tot_str =
- total_pnl >= 0 ? QString("+$%1").arg(total_pnl, 0, 'f', 0) : QString("-$%1").arg(-total_pnl, 0, 'f', 0);
+ QString day_str = day_pnl >= 0 ? QStringLiteral("+") + sym + QString::number(day_pnl, 'f', 0)
+ : QStringLiteral("-") + sym + QString::number(-day_pnl, 'f', 0);
+ QString tot_str = total_pnl >= 0 ? QStringLiteral("+") + sym + QString::number(total_pnl, 'f', 0)
+ : QStringLiteral("-") + sym + QString::number(-total_pnl, 'f', 0);
day_pnl_lbl_->setText(day_str);
day_pnl_lbl_->setStyleSheet(QString("color: %1; font-size: 13px; font-weight: bold; background: transparent;")
diff --git a/fincept-qt/src/screens/dashboard/widgets/PortfolioSummaryWidget.h b/fincept-qt/src/screens/dashboard/widgets/PortfolioSummaryWidget.h
index ca40780f4..745d407c5 100644
--- a/fincept-qt/src/screens/dashboard/widgets/PortfolioSummaryWidget.h
+++ b/fincept-qt/src/screens/dashboard/widgets/PortfolioSummaryWidget.h
@@ -70,6 +70,7 @@ class PortfolioSummaryWidget : public BaseWidget {
// ── Selected portfolio ─────────────────────────────────────────────────
QString selected_portfolio_id_;
QString selected_portfolio_name_;
+ QString selected_portfolio_currency_ = QStringLiteral("USD"); // the picked portfolio's own currency
QVector<portfolio::Portfolio> portfolio_cache_;
// ── Summary labels ──────────────────────────────────────────────────────
diff --git a/fincept-qt/src/screens/derivatives/DerivativesScreen.cpp b/fincept-qt/src/screens/derivatives/DerivativesScreen.cpp
index 7e50abda0..57a7cd01b 100644
--- a/fincept-qt/src/screens/derivatives/DerivativesScreen.cpp
+++ b/fincept-qt/src/screens/derivatives/DerivativesScreen.cpp
@@ -1,5 +1,6 @@
#include "screens/derivatives/DerivativesScreen.h"
+#include "core/currency/Currency.h"
#include "core/logging/Logger.h"
#include "core/session/ScreenStateManager.h"
#include "services/python_cli/PythonCliService.h"
@@ -230,7 +231,8 @@ QWidget* DerivativesScreen::create_bonds_panel() {
ph->setFixedHeight(34);
auto* phl = new QHBoxLayout(ph);
phl->setContentsMargins(12, 0, 12, 0);
- auto* phi = new QLabel("$");
+ auto* phi = new QLabel;
+ cur::bindLabel(phi, "%1"); // panel icon reflects the preferred currency, live
phi->setObjectName("derivPanelIcon");
auto* pht = new QLabel("BOND PRICE CALCULATOR");
pht->setObjectName("derivPanelTitle");
diff --git a/fincept-qt/src/screens/equity_trading/EquityTradingScreen.cpp b/fincept-qt/src/screens/equity_trading/EquityTradingScreen.cpp
index dc2fe6741..4ca9267b3 100644
--- a/fincept-qt/src/screens/equity_trading/EquityTradingScreen.cpp
+++ b/fincept-qt/src/screens/equity_trading/EquityTradingScreen.cpp
@@ -32,6 +32,7 @@
#include "trading/OrderMatcher.h"
#include "trading/PaperTrading.h"
#include "trading/UnifiedTrading.h"
+#include "trading/instruments/InstrumentService.h"
#include "ui/theme/StyleSheets.h"
#include "ui/theme/Theme.h"
@@ -78,6 +79,23 @@ EquityTradingScreen::EquityTradingScreen(QWidget* parent) : QWidget(parent) {
setup_timers();
connect_data_stream_signals();
+ // When InstrumentService finishes loading/downloading a broker's instrument
+ // master, reload market data for the active account if its broker matches.
+ // Account data works without this, but quotes/charts/depth need the numeric
+ // securityId map that only exists once instruments are loaded.
+ {
+ QPointer<EquityTradingScreen> self = this;
+ connect(&trading::InstrumentService::instance(), &trading::InstrumentService::refresh_done,
+ this, [self](const QString& broker_id, int /*count*/) {
+ if (self)
+ self->on_instruments_ready(broker_id);
+ });
+ connect(&trading::InstrumentService::instance(), &trading::InstrumentService::refresh_failed,
+ this, [](const QString& broker_id, const QString& error) {
+ LOG_WARN(TAG, QString("Instrument load failed for %1: %2").arg(broker_id, error));
+ });
+ }
+
// Accept symbol drops anywhere on the screen — route through the
// existing selection path so sub-panels resync and the linked group is
// published to.
@@ -362,6 +380,67 @@ void EquityTradingScreen::update_clock() {
// DataStreamManager signal connections
// ============================================================================
+void EquityTradingScreen::ensure_instruments_loaded(const QString& account_id) {
+ if (account_id.isEmpty())
+ return;
+ const auto creds = AccountManager::instance().load_credentials(account_id);
+ const QString broker_id = creds.broker_id;
+ if (broker_id.isEmpty())
+ return;
+
+ auto& svc = trading::InstrumentService::instance();
+ if (svc.is_loaded(broker_id)) {
+ // Already in memory — make sure market data reflects it.
+ on_instruments_ready(broker_id);
+ return;
+ }
+
+ QPointer<EquityTradingScreen> self = this;
+ svc.load_from_db_async(broker_id, [self, broker_id, creds](int count) {
+ if (!self)
+ return;
+ if (count > 0) {
+ // Cache hit: instruments now in memory → reload market data.
+ self->on_instruments_ready(broker_id);
+ return;
+ }
+ // No cache on disk — download from the broker. refresh() emits
+ // refresh_done on completion, which routes to on_instruments_ready().
+ LOG_INFO(TAG, QString("Downloading %1 instruments from broker...").arg(broker_id));
+ trading::InstrumentService::instance().refresh(broker_id, creds);
+ });
+}
+
+void EquityTradingScreen::on_instruments_ready(const QString& broker_id) {
+ // Only act if the currently-focused account uses this broker.
+ if (focused_account_id_.isEmpty())
+ return;
+ const QString focused_broker =
+ AccountManager::instance().load_credentials(focused_account_id_).broker_id;
+ if (focused_broker != broker_id)
+ return;
+
+ LOG_INFO(TAG, QString("Instruments ready for %1 — reloading market data").arg(broker_id));
+
+ // Rebuild the watchlist so its completer/validation pick up the new cache,
+ // then re-issue the data fetches for the active symbol + watchlist via the
+ // stream (the same path on_account_changed uses on connect).
+ watchlist_->set_symbols(watchlist_symbols_);
+
+ auto* stream = DataStreamManager::instance().stream_for(focused_account_id_);
+ if (stream) {
+ stream->set_selected_symbol(selected_symbol_, selected_exchange_);
+ stream->subscribe_symbols(watchlist_symbols_);
+ stream->fetch_candles(selected_symbol_, chart_->current_timeframe());
+ stream->fetch_orderbook(selected_symbol_);
+ stream->fetch_time_sales(selected_symbol_);
+ }
+
+ // Re-subscribe hub topics so streaming quotes flow for the resolved symbols.
+ if (isVisible())
+ hub_subscribe_streaming();
+}
+
void EquityTradingScreen::connect_data_stream_signals() {
auto& dsm = DataStreamManager::instance();
// Streaming data (quotes, positions, holdings, orders, funds) now comes
@@ -408,6 +487,12 @@ void EquityTradingScreen::init_focused_account() {
watchlist_->set_broker_id(account.broker_id);
}
+ // Load the broker instrument master (numeric securityId map) for the
+ // restored/active account so quotes, charts and depth resolve on app
+ // restart / account switch. Loads from the SQLite cache when present,
+ // else downloads; on_instruments_ready() reloads market data when done.
+ ensure_instruments_loaded(focused_account_id_);
+
// Register fill callback for paper trading
if (fill_cb_id_ < 0) {
QPointer<EquityTradingScreen> self = this;
diff --git a/fincept-qt/src/screens/equity_trading/EquityTradingScreen.h b/fincept-qt/src/screens/equity_trading/EquityTradingScreen.h
index f43e0abde..fa1c28563 100644
--- a/fincept-qt/src/screens/equity_trading/EquityTradingScreen.h
+++ b/fincept-qt/src/screens/equity_trading/EquityTradingScreen.h
@@ -66,6 +66,10 @@ class EquityTradingScreen : public QWidget, public IGroupLinked, public IStatefu
void on_ob_price_clicked(double price);
void on_import_holdings_requested(const QVector<trading::BrokerHolding>& holdings);
+ // Instruments ready — reloads watchlist/market data for the active account
+ // when InstrumentService finishes a load/download for the matching broker.
+ void on_instruments_ready(const QString& broker_id);
+
void refresh_candles();
void update_clock();
@@ -98,6 +102,12 @@ class EquityTradingScreen : public QWidget, public IGroupLinked, public IStatefu
void hub_subscribe_quotes();
QString broker_id_for_focused() const;
+ // Ensure the broker instrument master for `account_id` is loaded into
+ // InstrumentService (from SQLite cache or a fresh download). Market data
+ // (quotes/charts/depth) needs the numeric securityId map, which only exists
+ // once instruments are loaded. Mirrors the ChainSubTab load pattern.
+ void ensure_instruments_loaded(const QString& account_id);
+
// ── Command bar widgets ──
QPushButton* account_btn_ = nullptr; // shows focused account name
QMenu* account_menu_ = nullptr; // lists all active accounts
diff --git a/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Handlers.cpp b/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Handlers.cpp
index 48e0ba4c0..4ace83d71 100644
--- a/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Handlers.cpp
+++ b/fincept-qt/src/screens/equity_trading/EquityTradingScreen_Handlers.cpp
@@ -127,6 +127,10 @@ void EquityTradingScreen::on_account_changed(const QString& account_id) {
const bool has_creds = !AccountManager::instance().load_credentials(account_id).api_key.isEmpty();
auto& dsm = DataStreamManager::instance();
if (has_creds) {
+ // Load the broker instrument master (numeric securityId map) so quotes,
+ // charts and depth resolve. Loads from the SQLite cache when present,
+ // else downloads. on_instruments_ready() reloads market data when done.
+ ensure_instruments_loaded(account_id);
dsm.start_stream(account_id);
auto* stream = dsm.stream_for(account_id);
if (stream) {
@@ -285,6 +289,10 @@ void EquityTradingScreen::on_accounts_clicked() {
connect(dlg, &AccountManagementDialog::credentials_saved, this, [this](const QString& account_id) {
token_expired_shown_.store(false);
+ // Broker just connected — load its instrument master so market data
+ // (watchlist quotes, charts, depth) can resolve numeric securityIds.
+ // Covers every broker: all connect paths emit credentials_saved.
+ ensure_instruments_loaded(account_id);
// First account ever connected: focus it now (account_added intentionally
// does not auto-focus — see comment there). on_account_changed() does its
// own start_stream() + symbol/watchlist setup, so we're done after that.
diff --git a/fincept-qt/src/screens/equity_trading/EquityWatchlist.cpp b/fincept-qt/src/screens/equity_trading/EquityWatchlist.cpp
index 1a8ee14c5..bbbc6588e 100644
--- a/fincept-qt/src/screens/equity_trading/EquityWatchlist.cpp
+++ b/fincept-qt/src/screens/equity_trading/EquityWatchlist.cpp
@@ -2,6 +2,8 @@
#include "screens/equity_trading/EquityWatchlist.h"
#include "screens/equity_trading/EquityTypes.h"
+#include "trading/AccountManager.h"
+#include "trading/BrokerRegistry.h"
#include "trading/instruments/InstrumentService.h"
#include "ui/theme/Theme.h"
@@ -13,6 +15,38 @@
namespace fincept::screens::equity {
+namespace {
+
+// Distinct broker ids for every connected (active) account, with the focused
+// broker first so its matches sort to the top of unified search. Falls back to
+// just the focused broker when no accounts are enumerated.
+QStringList connected_broker_ids(const QString& active) {
+ QStringList ids;
+ if (!active.isEmpty())
+ ids << active;
+ for (const auto& a : trading::AccountManager::instance().active_accounts()) {
+ if (!a.broker_id.isEmpty() && !ids.contains(a.broker_id))
+ ids << a.broker_id;
+ }
+ return ids;
+}
+
+// Human-readable broker name for the suggestion tag.
+QString broker_display(const QString& broker_id) {
+ auto* b = trading::BrokerRegistry::instance().get(broker_id);
+ return b ? b->profile().display_name : broker_id;
+}
+
+// True if at least one of the connected brokers has its instrument catalog loaded.
+bool any_loaded(const QStringList& ids) {
+ for (const QString& id : ids)
+ if (trading::InstrumentService::instance().is_loaded(id))
+ return true;
+ return false;
+}
+
+} // namespace
+
EquityWatchlist::EquityWatchlist(QWidget* parent) : QWidget(parent) {
setObjectName("eqWatchlist");
@@ -240,13 +274,17 @@ void EquityWatchlist::on_add_symbol_entered() {
if (raw.isEmpty())
return;
- // If broker instruments are loaded, validate the symbol exists
- // Extract just the symbol part (ignore "EXCHANGE:SYMBOL" format from completer)
- QString sym = raw.contains(':') ? raw.section(':', 1) : raw;
-
- if (!broker_id_.isEmpty() && trading::InstrumentService::instance().is_loaded(broker_id_)) {
- // Accept if any exchange has it
- auto results = trading::InstrumentService::instance().search(sym, "", broker_id_, 1);
+ // The completer suggestion is "SYMBOL · EXCH · Broker" — keep only the
+ // leading symbol token. Also tolerate the legacy "EXCHANGE:SYMBOL" form.
+ QString sym = raw.section(QStringLiteral(" · "), 0, 0).trimmed();
+ if (sym.contains(':'))
+ sym = sym.section(':', 1);
+
+ // Validate against every connected broker (not just the focused one) so a
+ // symbol that only one connected broker carries is still accepted.
+ const QStringList ids = connected_broker_ids(broker_id_);
+ if (any_loaded(ids)) {
+ auto results = trading::InstrumentService::instance().search_all(sym, "", ids, 1);
if (results.isEmpty()) {
// Not found — flash the edit red briefly to signal invalid
add_edit_->setStyleSheet(QString("border: 1px solid %1;").arg(fincept::ui::colors::NEGATIVE()));
@@ -261,18 +299,32 @@ void EquityWatchlist::on_add_symbol_entered() {
}
void EquityWatchlist::on_add_text_changed(const QString& text) {
- if (broker_id_.isEmpty() || text.trimmed().length() < 2)
+ if (text.trimmed().length() < 2)
return;
- if (!trading::InstrumentService::instance().is_loaded(broker_id_))
+ const QStringList ids = connected_broker_ids(broker_id_);
+ if (ids.isEmpty())
return;
+ // Unified search across all connected brokers — one row per (broker,
+ // instrument). search_all hits the SQLite catalog directly, so we do NOT
+ // gate on the in-memory cache (is_loaded) here: as soon as a broker's
+ // master is in the DB the symbols are searchable, even if the in-memory
+ // cache rebuild hasn't landed yet. The symbol stays the leading token (so
+ // prefix completion on the typed text still works); exchange + broker follow.
const QString query = text.trimmed().toUpper();
- auto results = trading::InstrumentService::instance().search(query, "", broker_id_, 12);
+ auto results = trading::InstrumentService::instance().search_all(query, "", ids, 24);
QStringList suggestions;
suggestions.reserve(results.size());
- for (const auto& inst : results)
- suggestions.append(inst.symbol);
+ for (const auto& inst : results) {
+ suggestions.append(
+ QString("%1 · %2 · %3").arg(inst.symbol, inst.exchange, broker_display(inst.broker_id)));
+ }
completer_model_->setStringList(suggestions);
+ // Force the popup to refresh against the just-updated model (otherwise the
+ // completer can filter against the previous, stale/empty model for this
+ // keystroke and show nothing).
+ if (!suggestions.isEmpty())
+ completer_->complete();
}
} // namespace fincept::screens::equity
diff --git a/fincept-qt/src/screens/ma_analytics/MAModulePanel.cpp b/fincept-qt/src/screens/ma_analytics/MAModulePanel.cpp
index 0932eff34..264a9fb8f 100644
--- a/fincept-qt/src/screens/ma_analytics/MAModulePanel.cpp
+++ b/fincept-qt/src/screens/ma_analytics/MAModulePanel.cpp
@@ -1,6 +1,7 @@
// src/screens/ma_analytics/MAModulePanel.cpp
#include "screens/ma_analytics/MAModulePanel.h"
+#include "core/currency/Currency.h"
#include "core/logging/Logger.h"
#include "services/ma_analytics/MAAnalyticsService.h"
#include "ui/theme/Theme.h"
@@ -77,8 +78,17 @@ QWidget* MAModulePanel::build_input_row(const QString& label, QWidget* input, QW
auto* hl = new QHBoxLayout(row);
hl->setContentsMargins(0, 2, 0, 2);
hl->setSpacing(8);
- auto* lbl = new QLabel(label, row);
+ auto* lbl = new QLabel(row);
lbl->setFixedWidth(160);
+ // Labels ending in "($)" are a currency-unit hint — bind them so the symbol
+ // tracks the preferred currency live; others are plain text.
+ if (label.endsWith("($)")) {
+ QString base = label;
+ base.chop(3); // strip "($)"
+ cur::bindLabel(lbl, base + "(%1)");
+ } else {
+ lbl->setText(label);
+ }
lbl->setStyleSheet(QString("color:%1; font-size:%2px; font-family:%3;")
.arg(ui::colors::TEXT_SECONDARY())
.arg(ui::fonts::SMALL)
@@ -224,15 +234,13 @@ void MAModulePanel::display_error(const QString& msg) {
status_label_->setText("Error");
}
-static QString format_value(const QJsonValue& val) {
+// `intrinsic` pins the symbol to a fixed currency (e.g. "USD" for SEC/EDGAR
+// data); empty means follow the user's preferred currency.
+static QString format_value(const QJsonValue& val, const QString& intrinsic = QString()) {
if (val.isDouble()) {
double v = val.toDouble();
- if (std::abs(v) >= 1e9)
- return QString("$%1B").arg(v / 1e9, 0, 'f', 1);
- if (std::abs(v) >= 1e6)
- return QString("$%1M").arg(v / 1e6, 0, 'f', 1);
if (std::abs(v) >= 1e3)
- return QString("$%1K").arg(v / 1e3, 0, 'f', 0);
+ return cur::money(v, /*compact=*/true, intrinsic);
if (std::abs(v) < 1.0 && std::abs(v) > 0.0001)
return QString("%1%").arg(v * 100, 0, 'f', 1);
return QString::number(v, 'f', 2);
@@ -244,7 +252,8 @@ static QString format_value(const QJsonValue& val) {
return QString::fromUtf8("—");
}
-static QTableWidget* build_json_table(const QJsonArray& arr, const QString& accent, QWidget* parent) {
+static QTableWidget* build_json_table(const QJsonArray& arr, const QString& accent, QWidget* parent,
+ const QString& intrinsic = QString()) {
if (arr.isEmpty())
return nullptr;
// Collect all column keys from first object
@@ -282,7 +291,7 @@ static QTableWidget* build_json_table(const QJsonArray& arr, const QString& acce
for (int r = 0; r < arr.size(); ++r) {
auto obj = arr[r].toObject();
for (int c = 0; c < cols.size(); ++c) {
- auto* item = new QTableWidgetItem(format_value(obj[cols[c]]));
+ auto* item = new QTableWidgetItem(format_value(obj[cols[c]], intrinsic));
item->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
table->setItem(r, c, item);
}
@@ -291,7 +300,8 @@ static QTableWidget* build_json_table(const QJsonArray& arr, const QString& acce
return table;
}
-static QTableWidget* build_kv_table(const QJsonObject& obj, const QString& accent, QWidget* parent) {
+static QTableWidget* build_kv_table(const QJsonObject& obj, const QString& accent, QWidget* parent,
+ const QString& intrinsic = QString()) {
// Collect only scalar key-value pairs
QStringList keys;
for (auto it = obj.begin(); it != obj.end(); ++it)
@@ -329,7 +339,7 @@ static QTableWidget* build_kv_table(const QJsonObject& obj, const QString& accen
auto* key_item = new QTableWidgetItem(label.toUpper());
key_item->setTextAlignment(Qt::AlignLeft | Qt::AlignVCenter);
table->setItem(r, 0, key_item);
- auto* val_item = new QTableWidgetItem(format_value(obj[keys[r]]));
+ auto* val_item = new QTableWidgetItem(format_value(obj[keys[r]], intrinsic));
val_item->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
table->setItem(r, 1, val_item);
}
@@ -342,6 +352,13 @@ void MAModulePanel::display_result(const QJsonObject& payload) {
QString accent = QString("%1,%2,%3").arg(module_.color.red()).arg(module_.color.green()).arg(module_.color.blue());
+ // The Deals module shows SEC/EDGAR filing values, which are USD — pin them
+ // so they don't get repainted with the user's preferred currency symbol.
+ // Every other M&A module is a calculator the user denominates themselves.
+ const QString intrinsic = (module_.id == fincept::services::ma::ModuleId::Deals)
+ ? QStringLiteral("USD")
+ : QString();
+
// Section header
auto* header = new QLabel("RESULTS");
header->setStyleSheet(QString("color:%1; font-size:9px; font-weight:700; font-family:%2; letter-spacing:1px;"
@@ -364,7 +381,7 @@ void MAModulePanel::display_result(const QJsonObject& payload) {
has_scalars = true;
QString label = it.key();
label.replace('_', ' ');
- auto* card = build_metric_card(label.toUpper(), format_value(it.value()), module_.color.name(), grid);
+ auto* card = build_metric_card(label.toUpper(), format_value(it.value(), intrinsic), module_.color.name(), grid);
gl->addWidget(card, row, col);
col++;
if (col >= 3) {
@@ -394,14 +411,14 @@ void MAModulePanel::display_result(const QJsonObject& payload) {
results_layout_->addWidget(sec);
if (arr[0].isObject()) {
- auto* table = build_json_table(arr, accent, this);
+ auto* table = build_json_table(arr, accent, this, intrinsic);
if (table)
results_layout_->addWidget(table);
} else {
// Simple array — display as comma-separated
QStringList items;
for (const auto& v : arr)
- items.append(format_value(v));
+ items.append(format_value(v, intrinsic));
auto* lbl = new QLabel(items.join(", "));
lbl->setWordWrap(true);
lbl->setStyleSheet(QString("color:%1; font-size:%2px; font-family:%3;"
@@ -427,7 +444,7 @@ void MAModulePanel::display_result(const QJsonObject& payload) {
.arg(ui::fonts::DATA_FAMILY));
results_layout_->addWidget(sec);
- auto* table = build_kv_table(obj, accent, this);
+ auto* table = build_kv_table(obj, accent, this, intrinsic);
if (table)
results_layout_->addWidget(table);
}
@@ -509,6 +526,9 @@ void MAModulePanel::on_error(const QString& context, const QString& message) {
void MAModulePanel::apply_tab_stylesheet() {
if (!sub_tabs_)
return;
+ // Never truncate tab labels to "Accreti…"; show full text and scroll on overflow.
+ sub_tabs_->setElideMode(Qt::ElideNone);
+ sub_tabs_->setUsesScrollButtons(true);
sub_tabs_->setStyleSheet(QString("QTabWidget::pane { border:1px solid %1; background:%2; }"
"QTabBar::tab { background:%3; color:%4; padding:6px 16px;"
"font-family:%5; font-size:%6px; border:1px solid %1; border-bottom:none; }"
diff --git a/fincept-qt/src/screens/profile/ProfileScreen.cpp b/fincept-qt/src/screens/profile/ProfileScreen.cpp
index fbfe0502a..c0a342ab6 100644
--- a/fincept-qt/src/screens/profile/ProfileScreen.cpp
+++ b/fincept-qt/src/screens/profile/ProfileScreen.cpp
@@ -2,6 +2,7 @@
#include "auth/AuthManager.h"
#include "auth/UserApi.h"
+#include "core/currency/Currency.h"
#include "core/logging/Logger.h"
#include "ui/theme/Theme.h"
@@ -704,7 +705,7 @@ void ProfileScreen::fetch_billing_data() {
self->bill_history_->setItem(row, 0, new QTableWidgetItem(e["created_at"].toString().left(10)));
self->bill_history_->setItem(row, 1, new QTableWidgetItem(e["plan_name"].toString()));
self->bill_history_->setItem(
- row, 2, new QTableWidgetItem(QString("$%1").arg(e["amount_usd"].toDouble(), 0, 'f', 2)));
+ row, 2, new QTableWidgetItem(cur::money(e["amount_usd"].toDouble())));
self->bill_history_->setItem(row, 3, new QTableWidgetItem(QString::number(e["credits_purchased"].toInt())));
self->bill_history_->setItem(row, 4, new QTableWidgetItem(e["status"].toString().toUpper()));
}
diff --git a/fincept-qt/src/screens/settings/GeneralSection.cpp b/fincept-qt/src/screens/settings/GeneralSection.cpp
index c6cbfb102..17be1c9fa 100644
--- a/fincept-qt/src/screens/settings/GeneralSection.cpp
+++ b/fincept-qt/src/screens/settings/GeneralSection.cpp
@@ -2,6 +2,7 @@
#include "screens/settings/GeneralSection.h"
+#include "core/currency/CurrencyManager.h"
#include "core/i18n/LanguageManager.h"
#include "core/logging/Logger.h"
#include "screens/settings/SettingsRowHelpers.h"
@@ -114,6 +115,34 @@ void GeneralSection::build_ui() {
i18n::LanguageManager::instance().set_language(code);
});
+ vl->addSpacing(20);
+
+ // ── CURRENCY ────────────────────────────────────────────────────────────
+ auto* cur_title = new QLabel(tr("CURRENCY"));
+ cur_title->setStyleSheet(section_title_ss());
+ vl->addWidget(cur_title);
+ vl->addWidget(make_sep());
+ vl->addSpacing(8);
+
+ currency_combo_ = new QComboBox;
+ for (const auto& c : currency::CurrencyManager::available())
+ currency_combo_->addItem(QString("%1 %2 (%3)").arg(c.symbol, c.name, c.code), c.code);
+ currency_combo_->setStyleSheet(combo_ss());
+ vl->addWidget(make_row(
+ tr("Display currency"),
+ currency_combo_,
+ tr("Changes the currency symbol on calculators and analytics. Live market "
+ "data keeps its own currency — values are not converted.")));
+
+ connect(currency_combo_, qOverload<int>(&QComboBox::currentIndexChanged), this,
+ [this](int idx) {
+ const QString code = currency_combo_->itemData(idx).toString();
+ if (code.isEmpty())
+ return;
+ LOG_INFO("Settings", QString("currency → %1").arg(code));
+ currency::CurrencyManager::instance().set_currency(code);
+ });
+
vl->addStretch();
scroll->setWidget(page);
@@ -138,6 +167,12 @@ void GeneralSection::reload() {
QSignalBlocker block(language_combo_);
language_combo_->setCurrentIndex(idx >= 0 ? idx : 0);
}
+ if (currency_combo_) {
+ const QString cur = currency::CurrencyManager::instance().code();
+ const int idx = currency_combo_->findData(cur);
+ QSignalBlocker block(currency_combo_);
+ currency_combo_->setCurrentIndex(idx >= 0 ? idx : 0);
+ }
}
} // namespace fincept::screens
diff --git a/fincept-qt/src/screens/settings/GeneralSection.h b/fincept-qt/src/screens/settings/GeneralSection.h
index bb48f73ff..4dce15c5a 100644
--- a/fincept-qt/src/screens/settings/GeneralSection.h
+++ b/fincept-qt/src/screens/settings/GeneralSection.h
@@ -25,6 +25,7 @@ class GeneralSection : public QWidget {
QComboBox* on_close_combo_ = nullptr;
QComboBox* language_combo_ = nullptr;
+ QComboBox* currency_combo_ = nullptr;
};
} // namespace fincept::screens
diff --git a/fincept-qt/src/services/algo_trading/AlgoStrategyLibrary.h b/fincept-qt/src/services/algo_trading/AlgoStrategyLibrary.h
new file mode 100644
index 000000000..15aef3837
--- /dev/null
+++ b/fincept-qt/src/services/algo_trading/AlgoStrategyLibrary.h
@@ -0,0 +1,171 @@
+// src/services/algo_trading/AlgoStrategyLibrary.h
+#pragma once
+#include "services/algo_trading/AlgoTradingTypes.h"
+
+#include <QJsonArray>
+#include <QJsonObject>
+#include <QVector>
+
+namespace fincept::services::algo {
+
+// Curated, fully-editable C++ DSL strategy library seeded into the algo_strategies
+// table (fixed LIB-* ids). Replaces the old Python/LEAN QC registry. Each entry is
+// expressed in the same condition schema the Builder and ConditionEvaluator use.
+inline QVector<AlgoStrategy> algo_library_strategies() {
+ // value-comparison leaf: <indicator>.<field> <op> <constant>
+ auto cv = [](const QString& ind, const QJsonObject& p, const QString& field,
+ const QString& op, double value) {
+ QJsonObject c;
+ c["indicator"] = ind;
+ c["params"] = p;
+ c["field"] = field;
+ c["operator"] = op;
+ c["compare_mode"] = "value";
+ c["value"] = value;
+ return c;
+ };
+ // indicator-vs-indicator leaf
+ auto ci = [](const QString& ind, const QJsonObject& p, const QString& field, const QString& op,
+ const QString& cmpInd, const QJsonObject& cmpP, const QString& cmpField) {
+ QJsonObject c;
+ c["indicator"] = ind;
+ c["params"] = p;
+ c["field"] = field;
+ c["operator"] = op;
+ c["compare_mode"] = "indicator";
+ c["compare_indicator"] = cmpInd;
+ c["compare_params"] = cmpP;
+ c["compare_field"] = cmpField;
+ return c;
+ };
+ // indicator-vs-indicator leaf comparing against the RHS band N bars back
+ // (needed for true channel breakouts: close vs the *prior* bar's extreme).
+ auto cio = [&ci](const QString& ind, const QJsonObject& p, const QString& field, const QString& op,
+ const QString& cmpInd, const QJsonObject& cmpP, const QString& cmpField, int cmpOffset) {
+ QJsonObject c = ci(ind, p, field, op, cmpInd, cmpP, cmpField);
+ c["compare_offset"] = cmpOffset;
+ return c;
+ };
+ auto mk = [](const QString& id, const QString& name, const QString& category, const QString& tf,
+ const QString& entry_logic, const QString& exit_logic, double sl, double tp,
+ const QJsonArray& entry, const QJsonArray& exit) {
+ AlgoStrategy s;
+ s.id = id;
+ s.name = name;
+ s.description = category; // shown in the CATEGORY column / used for filtering
+ s.timeframe = tf;
+ s.entry_logic = entry_logic;
+ s.exit_logic = exit_logic;
+ s.stop_loss = sl;
+ s.take_profit = tp;
+ s.entry_conditions = entry;
+ s.exit_conditions = exit;
+ return s;
+ };
+
+ QVector<AlgoStrategy> v;
+
+ // ── Trend Following ──────────────────────────────────────────────────────
+ v << mk("LIB-GOLDEN-CROSS", "Golden Cross", "Trend Following", "1d", "AND", "AND", 5, 15,
+ {ci("SMA", {{"period", 50}}, "value", "crosses_above", "SMA", {{"period", 200}}, "value")},
+ {ci("SMA", {{"period", 50}}, "value", "crosses_below", "SMA", {{"period", 200}}, "value")});
+ v << mk("LIB-EMA-CROSS", "EMA 9/21 Cross", "Trend Following", "15m", "AND", "AND", 2, 5,
+ {ci("EMA", {{"period", 9}}, "value", "crosses_above", "EMA", {{"period", 21}}, "value")},
+ {ci("EMA", {{"period", 9}}, "value", "crosses_below", "EMA", {{"period", 21}}, "value")});
+ v << mk("LIB-TRIPLE-EMA", "Triple EMA Stack", "Trend Following", "15m", "AND", "AND", 2, 6,
+ {ci("EMA", {{"period", 9}}, "value", ">", "EMA", {{"period", 21}}, "value"),
+ ci("EMA", {{"period", 21}}, "value", ">", "EMA", {{"period", 50}}, "value")},
+ {ci("EMA", {{"period", 9}}, "value", "crosses_below", "EMA", {{"period", 21}}, "value")});
+ v << mk("LIB-SUPERTREND", "SuperTrend Follow", "Trend Following", "15m", "AND", "AND", 3, 9,
+ {ci("CLOSE", {}, "value", "crosses_above", "SUPERTREND", {{"period", 10}, {"multiplier", 3}}, "value")},
+ {ci("CLOSE", {}, "value", "crosses_below", "SUPERTREND", {{"period", 10}, {"multiplier", 3}}, "value")});
+ v << mk("LIB-ADX-TREND", "ADX Trend Filter", "Trend Following", "1h", "AND", "OR", 3, 9,
+ {cv("ADX", {{"period", 14}}, "value", ">", 25),
+ ci("EMA", {{"period", 9}}, "value", ">", "EMA", {{"period", 21}}, "value")},
+ {cv("ADX", {{"period", 14}}, "value", "<", 20),
+ ci("EMA", {{"period", 9}}, "value", "crosses_below", "EMA", {{"period", 21}}, "value")});
+ v << mk("LIB-ICHIMOKU", "Ichimoku Cloud Break", "Trend Following", "1d", "AND", "AND", 4, 12,
+ {ci("CLOSE", {}, "value", "crosses_above", "ICHIMOKU",
+ {{"tenkan", 9}, {"kijun", 26}, {"senkou", 52}}, "senkou_a")},
+ {ci("CLOSE", {}, "value", "crosses_below", "ICHIMOKU",
+ {{"tenkan", 9}, {"kijun", 26}, {"senkou", 52}}, "kijun_sen")});
+ // Breakout vs the PRIOR bar's 20-bar channel (compare_offset=1); comparing
+ // against the current bar's band is impossible since close is inside it.
+ v << mk("LIB-DONCHIAN-BREAK", "Donchian Breakout", "Trend Following", "1h", "AND", "AND", 3, 9,
+ {cio("CLOSE", {}, "value", "crosses_above", "DONCHIAN", {{"period", 20}}, "upper", 1)},
+ {cio("CLOSE", {}, "value", "crosses_below", "DONCHIAN", {{"period", 20}}, "lower", 1)});
+
+ // ── Momentum ─────────────────────────────────────────────────────────────
+ v << mk("LIB-RSI-REVERSAL", "RSI Reversal", "Momentum", "1h", "AND", "AND", 3, 8,
+ {cv("RSI", {{"period", 14}}, "value", "<", 30)},
+ {cv("RSI", {{"period", 14}}, "value", ">", 60)});
+ v << mk("LIB-RSI-BREAKOUT", "RSI Momentum Breakout", "Momentum", "15m", "AND", "AND", 2, 6,
+ {cv("RSI", {{"period", 14}}, "value", "crosses_above", 60)},
+ {cv("RSI", {{"period", 14}}, "value", "crosses_below", 40)});
+ v << mk("LIB-MACD-CROSS", "MACD Signal Cross", "Momentum", "15m", "AND", "AND", 2, 6,
+ {ci("MACD", {{"fast", 12}, {"slow", 26}, {"signal", 9}}, "line", "crosses_above", "MACD",
+ {{"fast", 12}, {"slow", 26}, {"signal", 9}}, "signal_line")},
+ {ci("MACD", {{"fast", 12}, {"slow", 26}, {"signal", 9}}, "line", "crosses_below", "MACD",
+ {{"fast", 12}, {"slow", 26}, {"signal", 9}}, "signal_line")});
+ v << mk("LIB-STOCH-CROSS", "Stochastic Cross", "Momentum", "15m", "AND", "AND", 2, 6,
+ {ci("STOCHASTIC", {{"k_period", 14}, {"d_period", 3}}, "k", "crosses_above", "STOCHASTIC",
+ {{"k_period", 14}, {"d_period", 3}}, "d")},
+ {ci("STOCHASTIC", {{"k_period", 14}, {"d_period", 3}}, "k", "crosses_below", "STOCHASTIC",
+ {{"k_period", 14}, {"d_period", 3}}, "d")});
+ v << mk("LIB-CCI", "CCI Zero-Line", "Momentum", "1h", "AND", "AND", 3, 8,
+ {cv("CCI", {{"period", 20}}, "value", "crosses_above", -100)},
+ {cv("CCI", {{"period", 20}}, "value", "crosses_below", 100)});
+ v << mk("LIB-WILLIAMS-R", "Williams %R Reversal", "Momentum", "1h", "AND", "AND", 3, 8,
+ {cv("WILLIAMS_R", {{"period", 14}}, "value", "crosses_above", -80)},
+ {cv("WILLIAMS_R", {{"period", 14}}, "value", "crosses_below", -20)});
+ v << mk("LIB-ROC-MOMENTUM", "Rate-of-Change Momentum", "Momentum", "1d", "AND", "AND", 4, 12,
+ {cv("ROC", {{"period", 12}}, "value", ">", 0), cv("ROC", {{"period", 12}}, "value", "rising", 0)},
+ {cv("ROC", {{"period", 12}}, "value", "<", 0)});
+
+ // ── Mean Reversion / Volatility ──────────────────────────────────────────
+ v << mk("LIB-BB-BREAKOUT", "Bollinger Breakout", "Volatility", "1h", "AND", "AND", 3, 9,
+ {ci("CLOSE", {}, "value", "crosses_above", "BOLLINGER", {{"period", 20}, {"std_dev", 2}}, "upper")},
+ {ci("CLOSE", {}, "value", "crosses_below", "BOLLINGER", {{"period", 20}, {"std_dev", 2}}, "middle")});
+ v << mk("LIB-BB-BOUNCE", "Bollinger Bounce", "Mean Reversion", "1h", "AND", "AND", 3, 6,
+ {ci("CLOSE", {}, "value", "<", "BOLLINGER", {{"period", 20}, {"std_dev", 2}}, "lower")},
+ {ci("CLOSE", {}, "value", ">", "BOLLINGER", {{"period", 20}, {"std_dev", 2}}, "middle")});
+ v << mk("LIB-KELTNER-BREAK", "Keltner Breakout", "Volatility", "1h", "AND", "AND", 3, 9,
+ {ci("CLOSE", {}, "value", "crosses_above", "KELTNER", {{"period", 20}, {"multiplier", 2}}, "upper")},
+ {ci("CLOSE", {}, "value", "crosses_below", "KELTNER", {{"period", 20}, {"multiplier", 2}}, "middle")});
+
+ // ── Volume ───────────────────────────────────────────────────────────────
+ v << mk("LIB-OBV-TREND", "OBV Trend Confirm", "Volume", "1d", "AND", "OR", 4, 12,
+ {cv("OBV", {}, "value", "rising", 0),
+ ci("CLOSE", {}, "value", ">", "EMA", {{"period", 21}}, "value")},
+ {cv("OBV", {}, "value", "falling", 0)});
+ v << mk("LIB-CMF", "Chaikin Money Flow", "Volume", "1d", "AND", "AND", 4, 10,
+ {cv("CMF", {{"period", 20}}, "value", "crosses_above", 0)},
+ {cv("CMF", {{"period", 20}}, "value", "crosses_below", 0)});
+ v << mk("LIB-MFI", "Money Flow Index", "Volume", "1h", "AND", "AND", 3, 8,
+ {cv("MFI", {{"period", 14}}, "value", "<", 20)},
+ {cv("MFI", {{"period", 14}}, "value", ">", 80)});
+
+ // ── Multi-Indicator combos ───────────────────────────────────────────────
+ v << mk("LIB-RSI-MACD", "RSI + MACD Confluence", "Multi-Indicator", "15m", "AND", "OR", 3, 9,
+ {cv("RSI", {{"period", 14}}, "value", "<", 45),
+ ci("MACD", {{"fast", 12}, {"slow", 26}, {"signal", 9}}, "line", "crosses_above", "MACD",
+ {{"fast", 12}, {"slow", 26}, {"signal", 9}}, "signal_line")},
+ {cv("RSI", {{"period", 14}}, "value", ">", 70),
+ ci("MACD", {{"fast", 12}, {"slow", 26}, {"signal", 9}}, "line", "crosses_below", "MACD",
+ {{"fast", 12}, {"slow", 26}, {"signal", 9}}, "signal_line")});
+ v << mk("LIB-TREND-PULLBACK", "Trend Pullback", "Multi-Indicator", "1h", "AND", "AND", 3, 9,
+ {ci("EMA", {{"period", 50}}, "value", ">", "EMA", {{"period", 200}}, "value"),
+ cv("RSI", {{"period", 14}}, "value", "<", 40)},
+ {cv("RSI", {{"period", 14}}, "value", ">", 65)});
+ v << mk("LIB-BB-RSI", "Bollinger + RSI Oversold", "Multi-Indicator", "1h", "AND", "AND", 3, 7,
+ {ci("CLOSE", {}, "value", "<", "BOLLINGER", {{"period", 20}, {"std_dev", 2}}, "lower"),
+ cv("RSI", {{"period", 14}}, "value", "<", 30)},
+ {ci("CLOSE", {}, "value", ">", "BOLLINGER", {{"period", 20}, {"std_dev", 2}}, "middle")});
+ v << mk("LIB-VWAP-RECLAIM", "VWAP Reclaim", "Multi-Indicator", "5m", "AND", "AND", 1, 3,
+ {ci("CLOSE", {}, "value", "crosses_above", "VWAP", {}, "value")},
+ {ci("CLOSE", {}, "value", "crosses_below", "VWAP", {}, "value")});
+
+ return v;
+}
+
+} // namespace fincept::services::algo
diff --git a/fincept-qt/src/services/algo_trading/AlgoTradingService.cpp b/fincept-qt/src/services/algo_trading/AlgoTradingService.cpp
index 03cf2039f..48548e73d 100644
--- a/fincept-qt/src/services/algo_trading/AlgoTradingService.cpp
+++ b/fincept-qt/src/services/algo_trading/AlgoTradingService.cpp
@@ -4,12 +4,11 @@
#include "algo_engine/BacktestEngine.h"
#include "algo_engine/CandleDataFetcher.h"
#include "core/logging/Logger.h"
-#include "python/PythonRunner.h"
+#include "services/algo_trading/AlgoStrategyLibrary.h"
#include "storage/sqlite/Database.h"
#include "trading/AccountManager.h"
#include <QDate>
-#include <QFile>
#include <QJsonArray>
#include <QJsonDocument>
#include <QUuid>
@@ -67,31 +66,6 @@ void AlgoTradingService::save_strategy(const AlgoStrategy& strategy) {
emit strategy_saved(resolved_id);
}
-static QVector<AlgoStrategy> parse_strategies(const QJsonArray& arr) {
- QVector<AlgoStrategy> strategies;
- strategies.reserve(arr.size());
- for (const auto& v : arr) {
- auto o = v.toObject();
- AlgoStrategy s;
- s.id = o["id"].toString();
- s.name = o["name"].toString();
- s.description = o["description"].toString();
- s.timeframe = o["timeframe"].toString();
- s.entry_conditions = o["entry_conditions"].toArray();
- s.exit_conditions = o["exit_conditions"].toArray();
- s.entry_logic = o["entry_logic"].toString("AND");
- s.exit_logic = o["exit_logic"].toString("AND");
- s.stop_loss = o["stop_loss"].toDouble();
- s.take_profit = o["take_profit"].toDouble();
- s.trailing_stop = o["trailing_stop"].toDouble();
- s.created_at = o["created_at"].toString();
- s.updated_at = o["updated_at"].toString();
- s.script_path = o["script_path"].toString(); // empty for DSL, file path for QC
- strategies.append(s);
- }
- return strategies;
-}
-
static QVector<AlgoStrategy> load_dsl_strategies_from_db() {
QVector<AlgoStrategy> result;
auto q = fincept::Database::instance().execute(
@@ -122,28 +96,70 @@ static QVector<AlgoStrategy> load_dsl_strategies_from_db() {
return result;
}
-void AlgoTradingService::list_strategies() {
- QVector<AlgoStrategy> all;
-
- // 1. Load QC strategies from pre-generated registry_index.json
- const QString json_path =
- python::PythonRunner::instance().scripts_dir() + "/strategies/registry_index.json";
- QFile f(json_path);
- if (f.open(QIODevice::ReadOnly)) {
- auto doc = QJsonDocument::fromJson(f.readAll());
- f.close();
- if (!doc.isNull())
- all = parse_strategies(doc.object()["strategies"].toArray());
+// Bump when the curated library's *definitions* change (e.g. a fixed strategy).
+// On a bump, existing LIB-* rows are refreshed to the latest definition (without
+// reviving rows the user deleted); otherwise only missing ids are inserted, so
+// user-created strategies and edits are preserved.
+static constexpr int kLibraryVersion = 2;
+
+void AlgoTradingService::seed_library() {
+ int stored = 0;
+ {
+ auto q = fincept::Database::instance().execute(
+ "SELECT value FROM key_value_storage WHERE key='algo_library_version'", {});
+ if (q.is_ok() && q.value().next())
+ stored = q.value().value(0).toInt();
+ }
+ const bool force = stored < kLibraryVersion;
+
+ for (const auto& s : algo_library_strategies()) {
+ const QString entry_json =
+ QString::fromUtf8(QJsonDocument(s.entry_conditions).toJson(QJsonDocument::Compact));
+ const QString exit_json =
+ QString::fromUtf8(QJsonDocument(s.exit_conditions).toJson(QJsonDocument::Compact));
+ const QVariantList args = {s.id, s.name, s.description, s.timeframe,
+ entry_json, exit_json, s.entry_logic, s.exit_logic,
+ s.stop_loss, s.take_profit, s.trailing_stop};
+ if (force) {
+ // Refresh definition in place; do NOT touch is_active (keeps deletions).
+ fincept::Database::instance().execute(
+ "INSERT INTO algo_strategies "
+ "(id, name, description, timeframe, entry_conditions, exit_conditions, "
+ " entry_logic, exit_logic, stop_loss, take_profit, trailing_stop, is_active, "
+ " created_at, updated_at) "
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP) "
+ "ON CONFLICT(id) DO UPDATE SET name=excluded.name, description=excluded.description, "
+ " timeframe=excluded.timeframe, entry_conditions=excluded.entry_conditions, "
+ " exit_conditions=excluded.exit_conditions, entry_logic=excluded.entry_logic, "
+ " exit_logic=excluded.exit_logic, stop_loss=excluded.stop_loss, "
+ " take_profit=excluded.take_profit, trailing_stop=excluded.trailing_stop, "
+ " updated_at=CURRENT_TIMESTAMP",
+ args);
+ } else {
+ fincept::Database::instance().execute(
+ "INSERT OR IGNORE INTO algo_strategies "
+ "(id, name, description, timeframe, entry_conditions, exit_conditions, "
+ " entry_logic, exit_logic, stop_loss, take_profit, trailing_stop, is_active, "
+ " created_at, updated_at) "
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)",
+ args);
+ }
}
- // 2. Load user-saved DSL strategies from the database
- auto dsl = load_dsl_strategies_from_db();
- if (!dsl.isEmpty()) {
- all.append(dsl);
- LOG_INFO("AlgoTrading", QString("Loaded %1 DSL strategies from DB").arg(dsl.size()));
+ if (force) {
+ fincept::Database::instance().execute(
+ "INSERT INTO key_value_storage(key, value, updated_at) "
+ "VALUES('algo_library_version', ?, CAST(strftime('%s','now') AS INTEGER)) "
+ "ON CONFLICT(key) DO UPDATE SET value=excluded.value, updated_at=excluded.updated_at",
+ {QString::number(kLibraryVersion)});
+ LOG_INFO("AlgoTrading", QString("Curated library refreshed to v%1").arg(kLibraryVersion));
}
+}
- LOG_INFO("AlgoTrading", QString("Total strategies: %1 (QC + DSL)").arg(all.size()));
+void AlgoTradingService::list_strategies() {
+ seed_library(); // idempotent — ensures the curated library exists
+ QVector<AlgoStrategy> all = load_dsl_strategies_from_db();
+ LOG_INFO("AlgoTrading", QString("Loaded %1 strategies from DB").arg(all.size()));
emit strategies_loaded(all);
}
@@ -198,6 +214,7 @@ void AlgoTradingService::run_backtest(const AlgoStrategy& strategy, const QStrin
const double sl = strategy.stop_loss;
const double tp = strategy.take_profit;
const double trail = strategy.trailing_stop;
+ const double size_pct = strategy.position_size_pct > 0 ? strategy.position_size_pct : 100.0;
const QString timeframe = strategy.timeframe.isEmpty() ? QStringLiteral("1d") : strategy.timeframe;
LOG_INFO("AlgoTrading",
@@ -208,14 +225,14 @@ void AlgoTradingService::run_backtest(const AlgoStrategy& strategy, const QStrin
// Singleton — `this` outlives any async work, so capture directly.
fincept::algo::CandleDataFetcher::instance().fetch(
symbol, timeframe, lookback_days, source, broker_id, account_id,
- [this, entry, exit, entry_logic, exit_logic, sl, tp, trail, capital, timeframe, symbol](
+ [this, entry, exit, entry_logic, exit_logic, sl, tp, trail, size_pct, capital, timeframe, symbol](
bool ok, const QVector<fincept::algo::OhlcvCandle>& candles, const QString& err) {
if (!ok || candles.isEmpty()) {
emit error_occurred("backtest", err.isEmpty() ? QStringLiteral("No data") : err);
return;
}
const QJsonObject result = fincept::algo::BacktestEngine::run(
- candles, entry, entry_logic, exit, exit_logic, sl, tp, trail, capital, timeframe);
+ candles, entry, entry_logic, exit, exit_logic, sl, tp, trail, capital, timeframe, size_pct);
if (!result.value("success").toBool(false)) {
emit error_occurred("backtest", result.value("error").toString(QStringLiteral("Backtest failed")));
return;
diff --git a/fincept-qt/src/services/algo_trading/AlgoTradingService.h b/fincept-qt/src/services/algo_trading/AlgoTradingService.h
index 103f504f0..d9e9eec4f 100644
--- a/fincept-qt/src/services/algo_trading/AlgoTradingService.h
+++ b/fincept-qt/src/services/algo_trading/AlgoTradingService.h
@@ -38,6 +38,7 @@ class AlgoTradingService : public QObject {
private:
explicit AlgoTradingService(QObject* parent = nullptr);
+ void seed_library(); // idempotently seeds the curated C++ DSL library
Q_DISABLE_COPY(AlgoTradingService)
};
diff --git a/fincept-qt/src/services/algo_trading/AlgoTradingTypes.h b/fincept-qt/src/services/algo_trading/AlgoTradingTypes.h
index 1a866a6e8..2f9f94996 100644
--- a/fincept-qt/src/services/algo_trading/AlgoTradingTypes.h
+++ b/fincept-qt/src/services/algo_trading/AlgoTradingTypes.h
@@ -11,9 +11,10 @@ namespace fincept::services::algo {
// ── Kind & backend enums ────────────────────────────────────────────────────
-/// Strategy kind. Derived from the ID prefix — never persisted as a column.
-/// FCT-XXXXXXXX → Qc (code-based, lives under scripts/strategies/<file>.py)
-/// anything else → Dsl (indicator-rule-based, persisted in algo_strategies table)
+/// Strategy kind. All strategies are now Dsl (indicator-rule based, persisted in
+/// the algo_strategies table and evaluated by the C++ ConditionEvaluator). The Qc
+/// value is retained only so historical deployment records still classify; the
+/// Python/LEAN QC library was removed.
enum class StrategyKind { Dsl, Qc };
inline StrategyKind kind_from_id(const QString& id) {
@@ -64,15 +65,12 @@ struct AlgoStrategy {
double stop_loss = 0;
double take_profit = 0;
double trailing_stop = 0;
+ double position_size_pct = 100.0; // in-memory only — % of capital allocated per backtest entry
bool is_active = true;
QString created_at;
QString updated_at;
QJsonObject last_backtest; // in-memory only — populated when backtest runs, not persisted
- // For QC strategies, this is the .py file path relative to scripts/strategies/.
- // Empty for DSL strategies (their definition lives in entry_conditions/exit_conditions).
- QString script_path;
-
StrategyKind kind() const { return kind_from_id(id); }
};
@@ -136,27 +134,41 @@ struct ConditionDef {
QString indicator;
QJsonObject params;
QString field;
- QString op; // >, <, >=, <=, ==, crosses_above, crosses_below
+ QString op; // >, <, >=, <=, ==, crosses_above, crosses_below, rising, falling, between
double value = 0;
+ double value2 = 0; // upper bound for the `between` operator (value = lower)
QString compare_mode = "value"; // value, indicator
QString compare_indicator;
QJsonObject compare_params;
QString compare_field;
+ int offset = 0; // bars-ago for the LHS operand (0 = current bar)
+ int compare_offset = 0; // bars-ago for the RHS operand (indicator mode)
};
// ── Indicator categories ────────────────────────────────────────────────────
+// A single tunable indicator parameter with a UI-ready range. Aggregate-init as
+// {name, min, max, default, step, decimals}.
+struct ParamSpec {
+ QString name;
+ double min = 1;
+ double max = 500;
+ double def = 14;
+ double step = 1;
+ int decimals = 0;
+};
+
struct IndicatorDef {
QString id;
QString label;
QString category; // stock, ma, momentum, trend, volatility, volume
- QStringList params;
- QStringList fields;
+ QVector<ParamSpec> params;
+ QStringList fields; // named outputs; first is the default
};
inline QVector<IndicatorDef> algo_indicators() {
return {
- // Stock attributes
+ // Stock attributes (no params)
{"CLOSE", "Close Price", "stock", {}, {"value"}},
{"OPEN", "Open Price", "stock", {}, {"value"}},
{"HIGH", "High Price", "stock", {}, {"value"}},
@@ -164,51 +176,156 @@ inline QVector<IndicatorDef> algo_indicators() {
{"VOLUME", "Volume", "stock", {}, {"value"}},
{"VWAP", "VWAP", "stock", {}, {"value"}},
// Moving averages
- {"SMA", "SMA", "ma", {"period"}, {"value"}},
- {"EMA", "EMA", "ma", {"period"}, {"value"}},
- {"WMA", "WMA", "ma", {"period"}, {"value"}},
- {"DEMA", "DEMA", "ma", {"period"}, {"value"}},
- {"TEMA", "TEMA", "ma", {"period"}, {"value"}},
+ {"SMA", "SMA", "ma", {{"period", 1, 500, 20, 1, 0}}, {"value"}},
+ {"EMA", "EMA", "ma", {{"period", 1, 500, 20, 1, 0}}, {"value"}},
+ {"WMA", "WMA", "ma", {{"period", 1, 500, 20, 1, 0}}, {"value"}},
+ {"DEMA", "DEMA", "ma", {{"period", 1, 500, 20, 1, 0}}, {"value"}},
+ {"TEMA", "TEMA", "ma", {{"period", 1, 500, 20, 1, 0}}, {"value"}},
// Momentum
- {"RSI", "RSI", "momentum", {"period"}, {"value"}},
- {"MACD", "MACD", "momentum", {"fast", "slow", "signal"}, {"line", "signal_line", "histogram"}},
- {"STOCHASTIC", "Stochastic", "momentum", {"k_period", "d_period"}, {"k", "d"}},
- {"CCI", "CCI", "momentum", {"period"}, {"value"}},
- {"WILLIAMS_R", "Williams %R", "momentum", {"period"}, {"value"}},
- {"MFI", "MFI", "momentum", {"period"}, {"value"}},
- {"ROC", "Rate of Change", "momentum", {"period"}, {"value"}},
+ {"RSI", "RSI", "momentum", {{"period", 2, 100, 14, 1, 0}}, {"value"}},
+ {"MACD", "MACD", "momentum",
+ {{"fast", 1, 100, 12, 1, 0}, {"slow", 1, 200, 26, 1, 0}, {"signal", 1, 100, 9, 1, 0}},
+ {"line", "signal_line", "histogram"}},
+ {"STOCHASTIC", "Stochastic", "momentum",
+ {{"k_period", 1, 100, 14, 1, 0}, {"d_period", 1, 100, 3, 1, 0}}, {"k", "d"}},
+ {"CCI", "CCI", "momentum", {{"period", 1, 100, 20, 1, 0}}, {"value"}},
+ {"WILLIAMS_R", "Williams %R", "momentum", {{"period", 1, 100, 14, 1, 0}}, {"value"}},
+ {"MFI", "MFI", "momentum", {{"period", 1, 100, 14, 1, 0}}, {"value"}},
+ {"ROC", "Rate of Change", "momentum", {{"period", 1, 100, 12, 1, 0}}, {"value"}},
// Trend
- {"ADX", "ADX", "trend", {"period"}, {"value", "plus_di", "minus_di"}},
- {"SUPERTREND", "SuperTrend", "trend", {"period", "multiplier"}, {"value", "direction"}},
- {"AROON", "Aroon", "trend", {"period"}, {"up", "down"}},
- {"ICHIMOKU",
- "Ichimoku",
- "trend",
- {"tenkan", "kijun", "senkou"},
+ {"ADX", "ADX", "trend", {{"period", 1, 100, 14, 1, 0}}, {"value", "plus_di", "minus_di"}},
+ {"SUPERTREND", "SuperTrend", "trend",
+ {{"period", 1, 100, 10, 1, 0}, {"multiplier", 0.5, 10, 3, 0.5, 1}}, {"value", "direction"}},
+ {"AROON", "Aroon", "trend", {{"period", 1, 100, 14, 1, 0}}, {"up", "down"}},
+ {"ICHIMOKU", "Ichimoku", "trend",
+ {{"tenkan", 1, 100, 9, 1, 0}, {"kijun", 1, 100, 26, 1, 0}, {"senkou", 1, 200, 52, 1, 0}},
{"tenkan_sen", "kijun_sen", "senkou_a", "senkou_b"}},
// Volatility
- {"ATR", "ATR", "volatility", {"period"}, {"value"}},
- {"BOLLINGER",
- "Bollinger Bands",
- "volatility",
- {"period", "std_dev"},
+ {"ATR", "ATR", "volatility", {{"period", 1, 100, 14, 1, 0}}, {"value"}},
+ {"BOLLINGER", "Bollinger Bands", "volatility",
+ {{"period", 1, 100, 20, 1, 0}, {"std_dev", 0.5, 5, 2, 0.5, 1}},
{"upper", "middle", "lower", "width", "pct_b"}},
- {"KELTNER", "Keltner Channel", "volatility", {"period", "multiplier"}, {"upper", "middle", "lower"}},
- {"DONCHIAN", "Donchian Channel", "volatility", {"period"}, {"upper", "lower"}},
+ {"KELTNER", "Keltner Channel", "volatility",
+ {{"period", 1, 100, 20, 1, 0}, {"multiplier", 0.5, 10, 2, 0.5, 1}}, {"upper", "middle", "lower"}},
+ {"DONCHIAN", "Donchian Channel", "volatility", {{"period", 1, 100, 20, 1, 0}}, {"upper", "lower"}},
// Volume
{"OBV", "On Balance Volume", "volume", {}, {"value"}},
- {"CMF", "Chaikin Money Flow", "volume", {"period"}, {"value"}},
+ {"CMF", "Chaikin Money Flow", "volume", {{"period", 1, 100, 20, 1, 0}}, {"value"}},
};
}
inline QStringList algo_operators() {
- return {">", "<", ">=", "<=", "==", "crosses_above", "crosses_below", "rising", "falling"};
+ return {">", "<", ">=", "<=", "==", "crosses_above",
+ "crosses_below", "rising", "falling", "between"};
}
inline QStringList algo_timeframes() {
return {"live", "1m", "3m", "5m", "10m", "15m", "30m", "1h", "4h", "1d"};
}
+// Sensible default backtest lookback per timeframe. Daily needs years so long
+// indicators (SMA200, EMA200) have valid history; intraday must stay under
+// Yahoo's history caps (≈60 days for 5–30m, 7 for 1m).
+inline int algo_default_lookback_days(const QString& tf) {
+ if (tf == "1d") return 365 * 3;
+ if (tf == "4h" || tf == "1h") return 365;
+ if (tf == "1m") return 7;
+ if (tf == "live") return 365;
+ return 55; // 3m / 5m / 10m / 15m / 30m — just under Yahoo's ~60-day cap
+}
+
+// ── Strategy templates ────────────────────────────────────────────────────
+// Ready-made, editable starting points (long-only, matching the backtest engine).
+
+struct StrategyTemplate {
+ QString name;
+ QString description;
+ QString timeframe;
+ QString entry_logic = "AND";
+ QString exit_logic = "AND";
+ double stop_loss = 2.0;
+ double take_profit = 5.0;
+ QJsonArray entry;
+ QJsonArray exit;
+};
+
+inline QVector<StrategyTemplate> algo_strategy_templates() {
+ // value-comparison leaf
+ auto cv = [](const QString& ind, const QJsonObject& p, const QString& field,
+ const QString& op, double value) {
+ QJsonObject c;
+ c["indicator"] = ind;
+ c["params"] = p;
+ c["field"] = field;
+ c["operator"] = op;
+ c["compare_mode"] = "value";
+ c["value"] = value;
+ return c;
+ };
+ // indicator-vs-indicator leaf
+ auto ci = [](const QString& ind, const QJsonObject& p, const QString& field, const QString& op,
+ const QString& cmpInd, const QJsonObject& cmpP, const QString& cmpField) {
+ QJsonObject c;
+ c["indicator"] = ind;
+ c["params"] = p;
+ c["field"] = field;
+ c["operator"] = op;
+ c["compare_mode"] = "indicator";
+ c["compare_indicator"] = cmpInd;
+ c["compare_params"] = cmpP;
+ c["compare_field"] = cmpField;
+ return c;
+ };
+
+ QVector<StrategyTemplate> t;
+
+ StrategyTemplate golden;
+ golden.name = "Golden Cross";
+ golden.description = "SMA(50) crosses above SMA(200)";
+ golden.timeframe = "1d";
+ golden.stop_loss = 5;
+ golden.take_profit = 15;
+ golden.entry = {ci("SMA", {{"period", 50}}, "value", "crosses_above", "SMA", {{"period", 200}}, "value")};
+ golden.exit = {ci("SMA", {{"period", 50}}, "value", "crosses_below", "SMA", {{"period", 200}}, "value")};
+ t.append(golden);
+
+ StrategyTemplate rsi;
+ rsi.name = "RSI Reversal";
+ rsi.description = "Buy oversold RSI < 30, exit RSI > 60";
+ rsi.timeframe = "1h";
+ rsi.entry = {cv("RSI", {{"period", 14}}, "value", "<", 30)};
+ rsi.exit = {cv("RSI", {{"period", 14}}, "value", ">", 60)};
+ t.append(rsi);
+
+ StrategyTemplate macd;
+ macd.name = "MACD Cross";
+ macd.description = "MACD line crosses above signal";
+ macd.timeframe = "15m";
+ macd.entry = {ci("MACD", {{"fast", 12}, {"slow", 26}, {"signal", 9}}, "line", "crosses_above",
+ "MACD", {{"fast", 12}, {"slow", 26}, {"signal", 9}}, "signal_line")};
+ macd.exit = {ci("MACD", {{"fast", 12}, {"slow", 26}, {"signal", 9}}, "line", "crosses_below",
+ "MACD", {{"fast", 12}, {"slow", 26}, {"signal", 9}}, "signal_line")};
+ t.append(macd);
+
+ StrategyTemplate boll;
+ boll.name = "Bollinger Breakout";
+ boll.description = "Close breaks upper band, exit at middle band";
+ boll.timeframe = "1h";
+ boll.entry = {ci("CLOSE", {}, "value", "crosses_above", "BOLLINGER", {{"period", 20}, {"std_dev", 2}}, "upper")};
+ boll.exit = {ci("CLOSE", {}, "value", "crosses_below", "BOLLINGER", {{"period", 20}, {"std_dev", 2}}, "middle")};
+ t.append(boll);
+
+ StrategyTemplate st;
+ st.name = "SuperTrend Follow";
+ st.description = "Close crosses SuperTrend(10, 3)";
+ st.timeframe = "15m";
+ st.entry = {ci("CLOSE", {}, "value", "crosses_above", "SUPERTREND", {{"period", 10}, {"multiplier", 3}}, "value")};
+ st.exit = {ci("CLOSE", {}, "value", "crosses_below", "SUPERTREND", {{"period", 10}, {"multiplier", 3}}, "value")};
+ t.append(st);
+
+ return t;
+}
+
// ── Scanner preset conditions ───────────────────────────────────────────────
struct ScannerPreset {
diff --git a/fincept-qt/src/storage/sqlite/migrations/MigrationRunner.h b/fincept-qt/src/storage/sqlite/migrations/MigrationRunner.h
index f0cc769d6..89e218fb0 100644
--- a/fincept-qt/src/storage/sqlite/migrations/MigrationRunner.h
+++ b/fincept-qt/src/storage/sqlite/migrations/MigrationRunner.h
@@ -82,5 +82,6 @@ void register_migration_v032();
void register_migration_v033();
void register_migration_v034();
void register_migration_v035();
+void register_migration_v036();
} // namespace fincept
diff --git a/fincept-qt/src/storage/sqlite/migrations/v023_algo_trading_deploy.cpp b/fincept-qt/src/storage/sqlite/migrations/v023_algo_trading_deploy.cpp
index dbad09faa..400fbb85c 100644
--- a/fincept-qt/src/storage/sqlite/migrations/v023_algo_trading_deploy.cpp
+++ b/fincept-qt/src/storage/sqlite/migrations/v023_algo_trading_deploy.cpp
@@ -50,8 +50,9 @@ static Result<void> v023_add_column_if_missing(QSqlDatabase& db, const QString&
Result<void> apply_v023(QSqlDatabase& db) {
// ── Strategy registry (DSL strategies) ──────────────────────────────────
- // QC strategies live in scripts/strategies/_registry.py — not in SQL.
- // This table only holds DSL strategies built in StrategyBuilderPanel.
+ // Holds all strategies: the seeded curated library (LIB-*) plus user
+ // strategies built in StrategyBuilderPanel. (The old Python/LEAN QC library
+ // was removed.)
{
auto r = v023_sql(db, R"sql(
CREATE TABLE IF NOT EXISTS algo_strategies (
diff --git a/fincept-qt/src/storage/sqlite/migrations/v036_instrument_broker_token.cpp b/fincept-qt/src/storage/sqlite/migrations/v036_instrument_broker_token.cpp
new file mode 100644
index 000000000..d930d72f7
--- /dev/null
+++ b/fincept-qt/src/storage/sqlite/migrations/v036_instrument_broker_token.cpp
@@ -0,0 +1,35 @@
+// v036_instrument_broker_token — add a TEXT column carrying each broker's native
+// non-numeric instrument key (Upstox "NSE_EQ|INE…", Samco "758960_NSE"). Numeric-
+// token brokers leave it empty and keep using instrument_token. Needed so the
+// catalog can route market-data/orders for string-token brokers, and so those
+// rows get a distinct numeric instrument_token (via norm::stable_token) instead
+// of all colliding on 0 under UNIQUE(instrument_token, broker_id).
+
+#include "storage/sqlite/migrations/MigrationRunner.h"
+
+#include <QSqlError>
+#include <QSqlQuery>
+
+namespace fincept {
+namespace {
+
+Result<void> apply_v036(QSqlDatabase& db) {
+ QSqlQuery q(db);
+ // MigrationRunner guarantees a migration applies at most once, so a plain
+ // ADD COLUMN (which errors if the column already exists) is safe here.
+ if (!q.exec("ALTER TABLE instruments ADD COLUMN broker_token TEXT NOT NULL DEFAULT ''"))
+ return Result<void>::err(q.lastError().text().toStdString());
+ return Result<void>::ok();
+}
+
+} // namespace
+
+void register_migration_v036() {
+ static bool done = false;
+ if (done)
+ return;
+ done = true;
+ MigrationRunner::register_migration({36, "instrument_broker_token", apply_v036});
+}
+
+} // namespace fincept
diff --git a/fincept-qt/src/trading/AccountDataStream.cpp b/fincept-qt/src/trading/AccountDataStream.cpp
index 6c08c4a09..b1df645de 100644
--- a/fincept-qt/src/trading/AccountDataStream.cpp
+++ b/fincept-qt/src/trading/AccountDataStream.cpp
@@ -13,6 +13,7 @@
#include "trading/websocket/FivePaisaWebSocket.h"
#include "trading/websocket/FyersWebSocket.h"
#include "trading/websocket/IIFLWebSocket.h"
+#include "trading/websocket/IciciDirectWebSocket.h"
#include "trading/websocket/KotakWebSocket.h"
#include "trading/websocket/MotilalPoller.h"
#include "trading/websocket/ShoonyaWebSocket.h"
@@ -991,6 +992,25 @@ void AccountDataStream::ws_init() {
return;
}
+ if (broker_id_ == "icicidirect") {
+ auto creds = AccountManager::instance().load_credentials(account_id_);
+ // access_token = base64("user_id:session_key") from the Breeze session flow.
+ if (creds.access_token.isEmpty()) {
+ LOG_WARN(ADS_TAG, QString("ICICI WS: missing session token for %1").arg(account_id_));
+ return;
+ }
+ auto* iws = new IciciDirectWebSocket(creds.access_token, creds.user_id, this);
+ ws_ = iws;
+ wire_base_ws(iws);
+ connect(iws, &IciciDirectWebSocket::connected, this, [this, current_symbols, resolve_tokens]() {
+ LOG_INFO(ADS_TAG, QString("ICICI WS connected for %1").arg(account_id_));
+ if (auto* w = qobject_cast<IciciDirectWebSocket*>(ws_))
+ w->subscribe(resolve_tokens(current_symbols()));
+ });
+ iws->open();
+ return;
+ }
+
if (broker_id_ != "angelone")
return;
diff --git a/fincept-qt/src/trading/BrokerRegistry.cpp b/fincept-qt/src/trading/BrokerRegistry.cpp
index 8f7592439..7cf932769 100644
--- a/fincept-qt/src/trading/BrokerRegistry.cpp
+++ b/fincept-qt/src/trading/BrokerRegistry.cpp
@@ -13,6 +13,7 @@
#include "trading/brokers/fyers/FyersBroker.h"
#include "trading/brokers/groww/GrowwBroker.h"
#include "trading/brokers/ibkr/IBKRBroker.h"
+#include "trading/brokers/icicidirect/IciciDirectBroker.h"
#include "trading/brokers/metaapi/MetaApiBroker.h"
#include "trading/brokers/iifl/IIFLBroker.h"
#include "trading/brokers/kotak/KotakBroker.h"
@@ -130,6 +131,7 @@ void BrokerRegistry::register_all() {
brokers_["flattrade"] = std::make_unique<FlattradeBroker>();
brokers_["paytm"] = std::make_unique<PaytmBroker>();
brokers_["tradejini"] = std::make_unique<TradejiniBroker>();
+ brokers_["icicidirect"] = std::make_unique<IciciDirectBroker>();
// US brokers
brokers_["alpaca"] = std::make_unique<AlpacaBroker>();
diff --git a/fincept-qt/src/trading/TradingTypes.h b/fincept-qt/src/trading/TradingTypes.h
index 117d217c8..a22c872c6 100644
--- a/fincept-qt/src/trading/TradingTypes.h
+++ b/fincept-qt/src/trading/TradingTypes.h
@@ -439,6 +439,7 @@ enum class BrokerId {
Flattrade,
Paytm,
Tradejini,
+ IciciDirect,
Alpaca,
IBKR,
Tradier,
@@ -480,6 +481,8 @@ inline const char* broker_id_str(BrokerId id) {
return "paytm";
case BrokerId::Tradejini:
return "tradejini";
+ case BrokerId::IciciDirect:
+ return "icicidirect";
case BrokerId::Alpaca:
return "alpaca";
case BrokerId::IBKR:
@@ -527,6 +530,8 @@ inline std::optional<BrokerId> parse_broker_id(const QString& s) {
return BrokerId::Paytm;
if (s == "tradejini")
return BrokerId::Tradejini;
+ if (s == "icicidirect")
+ return BrokerId::IciciDirect;
if (s == "alpaca")
return BrokerId::Alpaca;
if (s == "ibkr")
diff --git a/fincept-qt/src/trading/brokers/BrokerHttp.cpp b/fincept-qt/src/trading/brokers/BrokerHttp.cpp
index 6edeeea7d..5ab7298a2 100644
--- a/fincept-qt/src/trading/brokers/BrokerHttp.cpp
+++ b/fincept-qt/src/trading/brokers/BrokerHttp.cpp
@@ -99,6 +99,11 @@ BrokerHttpResponse BrokerHttp::put_raw(const QString& url, const QByteArray& bod
return execute("PUT", url, body, ct, h);
}
+BrokerHttpResponse BrokerHttp::send(const QString& method, const QString& url, const QByteArray& body,
+ const QString& content_type, const QMap<QString, QString>& headers) {
+ return execute(method, url, body, content_type, headers);
+}
+
BrokerHttpResponse BrokerHttp::execute(const QString& method, const QString& url, const QByteArray& body,
const QString& content_type, const QMap<QString, QString>& headers) {
// One QNetworkAccessManager per worker thread so TLS/TCP connections are
@@ -131,7 +136,13 @@ BrokerHttpResponse BrokerHttp::execute(const QString& method, const QString& url
// Send request
QNetworkReply* reply = nullptr;
if (method == "GET") {
- reply = nam.get(req);
+ // Some broker REST APIs (e.g. ICICI Breeze) send a JSON body on GET.
+ // QNetworkAccessManager::get() can't carry a body, so fall back to a
+ // custom request when one is present. Empty-body GET keeps the fast path.
+ if (body.isEmpty())
+ reply = nam.get(req);
+ else
+ reply = nam.sendCustomRequest(req, "GET", body);
} else if (method == "POST") {
reply = nam.post(req, body);
} else if (method == "PUT") {
diff --git a/fincept-qt/src/trading/brokers/BrokerHttp.h b/fincept-qt/src/trading/brokers/BrokerHttp.h
index 2d2f9c9dc..7a75177f0 100644
--- a/fincept-qt/src/trading/brokers/BrokerHttp.h
+++ b/fincept-qt/src/trading/brokers/BrokerHttp.h
@@ -55,6 +55,13 @@ class BrokerHttp {
// Raw body PUT — caller provides pre-encoded body + headers (Tradier modify_order)
BrokerHttpResponse put_raw(const QString& url, const QByteArray& body, const QMap<QString, QString>& headers = {});
+ // Generic request — exposes the internal dispatcher for brokers that need a
+ // verb/body combination the typed helpers don't cover. ICICI Breeze, for
+ // example, signs and reads via GET-with-JSON-body (the HTTP method selects
+ // the operation on a single resource endpoint). caller pre-encodes the body.
+ BrokerHttpResponse send(const QString& method, const QString& url, const QByteArray& body,
+ const QString& content_type, const QMap<QString, QString>& headers = {});
+
// Timeout in ms (default 8s — tight enough to surface network issues fast,
// long enough to tolerate a cold TLS handshake).
void set_timeout(int ms) { timeout_ms_ = ms; }
diff --git a/fincept-qt/src/trading/brokers/aliceblue/AliceBlueBroker.cpp b/fincept-qt/src/trading/brokers/aliceblue/AliceBlueBroker.cpp
index 87510dd2c..535b7231e 100644
--- a/fincept-qt/src/trading/brokers/aliceblue/AliceBlueBroker.cpp
+++ b/fincept-qt/src/trading/brokers/aliceblue/AliceBlueBroker.cpp
@@ -2,6 +2,7 @@
#include "trading/adapter/BrokerEnumMap.h"
#include "trading/brokers/BrokerHttp.h"
+#include "trading/instruments/InstrumentService.h"
#include <QCryptographicHash>
#include <QDateTime>
@@ -497,28 +498,42 @@ ApiResponse<QVector<BrokerCandle>> AliceBlueBroker::get_history(const BrokerCred
int64_t ts = now_ts();
auto hdrs = auth_headers(creds);
- // BSE historical data not supported by AliceBlue
+ // Parse "EXCHANGE:SYMBOL[:TOKEN]". Exchange defaults to NSE when omitted; an
+ // explicit third part is taken as the numeric instrument token.
QString exchange = "NSE";
QString trading_symbol = symbol;
- int colon = symbol.indexOf(':');
- if (colon != -1) {
- exchange = symbol.left(colon);
- trading_symbol = symbol.mid(colon + 1);
- }
- if (exchange == "BSE" || exchange == "BCD")
- return {false, std::nullopt, "AliceBlue does not support BSE historical data", ts};
-
- // instrument_token should be passed in from the caller via symbol "NSE:RELIANCE:3045"
- // For now accept "EXCHANGE:SYMBOL:TOKEN" format if colon count == 2
QString instrument_token;
- QStringList parts = symbol.split(':');
- if (parts.size() == 3) {
+ const QStringList parts = symbol.split(':');
+ if (parts.size() == 1) {
+ trading_symbol = parts[0];
+ } else if (parts.size() == 2) {
+ exchange = parts[0];
+ trading_symbol = parts[1];
+ } else if (parts.size() >= 3) {
exchange = parts[0];
trading_symbol = parts[1];
- instrument_token = parts[2];
+ instrument_token = parts[2]; // explicit token overrides lookup
+ }
+
+ // AliceBlue's chart endpoint serves NSE/NFO/CDS/MCX only. BSE, BCD and BFO
+ // candle data are "added later" per the official ANT docs — reject early with
+ // a clear message rather than letting the server return stat:"Not_Ok".
+ if (exchange != "NSE" && exchange != "NFO" && exchange != "CDS" && exchange != "MCX")
+ return {false, std::nullopt,
+ "AliceBlue historical data is available only for NSE/NFO/CDS/MCX (got " + exchange + ")", ts};
+
+ // Resolve the numeric instrument token from InstrumentService when the caller
+ // didn't pass an explicit "EXCHANGE:SYMBOL:TOKEN" — parity with Zerodha so a
+ // plain "NSE:RELIANCE" works once instruments are loaded.
+ if (instrument_token.isEmpty()) {
+ auto tok = InstrumentService::instance().instrument_token(trading_symbol, exchange, creds.broker_id);
+ if (tok.has_value() && tok.value() > 0)
+ instrument_token = QString::number(static_cast<qlonglong>(tok.value()));
}
if (instrument_token.isEmpty())
- return {false, std::nullopt, "AliceBlue requires instrument token for historical data", ts};
+ return {false, std::nullopt,
+ "AliceBlue get_history: instrument token not found for " + symbol +
+ " (load instruments first, or pass EXCHANGE:SYMBOL:TOKEN)", ts};
// Convert YYYY-MM-DD to Unix milliseconds (IST 09:15 start, 23:59 end)
auto to_epoch_ms = [](const QString& date_str, bool is_end) -> QString {
diff --git a/fincept-qt/src/trading/brokers/icicidirect/IciciDirectBroker.cpp b/fincept-qt/src/trading/brokers/icicidirect/IciciDirectBroker.cpp
new file mode 100644
index 000000000..831832095
--- /dev/null
+++ b/fincept-qt/src/trading/brokers/icicidirect/IciciDirectBroker.cpp
@@ -0,0 +1,575 @@
+#include "trading/brokers/icicidirect/IciciDirectBroker.h"
+
+#include "core/logging/Logger.h"
+#include "trading/brokers/BrokerHttp.h"
+#include "trading/instruments/InstrumentService.h"
+
+#include <QCryptographicHash>
+#include <QDate>
+#include <QDateTime>
+#include <QJsonArray>
+#include <QJsonDocument>
+#include <QUrl>
+
+#include <cmath>
+
+namespace fincept::trading {
+
+static int64_t now_ts() {
+ return QDateTime::currentSecsSinceEpoch();
+}
+
+namespace {
+
+// Breeze returns most numbers as JSON strings; tolerate both representations.
+double jnum(const QJsonObject& o, const QString& key) {
+ const QJsonValue v = o.value(key);
+ if (v.isDouble())
+ return v.toDouble();
+ return v.toString().toDouble();
+}
+
+QString jstr(const QJsonObject& o, const QString& key) {
+ const QJsonValue v = o.value(key);
+ if (v.isString())
+ return v.toString();
+ if (v.isDouble())
+ return QString::number(v.toDouble());
+ return {};
+}
+
+// Breeze checksum timestamp: UTC ISO-8601 with a fixed ".000Z" millisecond part.
+QString breeze_timestamp() {
+ return QDateTime::currentDateTimeUtc().toString("yyyy-MM-ddThh:mm:ss") + ".000Z";
+}
+
+// Map the UnifiedOrder enums onto Breeze wire values.
+QString icici_order_type(OrderType t) {
+ switch (t) {
+ case OrderType::Market:
+ return "market";
+ case OrderType::Limit:
+ return "limit";
+ case OrderType::StopLoss:
+ case OrderType::StopLossLimit:
+ return "stoploss";
+ }
+ return "market";
+}
+
+// Breeze cash-segment product. Note: ICICI prohibits "marginplus"/"optionplus"
+// via API; intraday equity uses plain "margin".
+QString icici_equity_product(ProductType p) {
+ switch (p) {
+ case ProductType::Delivery:
+ return "cash";
+ case ProductType::Intraday:
+ case ProductType::Margin:
+ return "margin";
+ case ProductType::MTF:
+ return "mtf";
+ default:
+ return "cash";
+ }
+}
+
+// "30-MAR-2026" -> "2026-03-30T06:00:00.000Z" (Breeze expiry/date format).
+QString icici_iso_expiry(const QString& display) {
+ if (display.isEmpty())
+ return {};
+ const QStringList p = display.split('-');
+ if (p.size() != 3)
+ return {};
+ static const QMap<QString, QString> mon = {{"JAN", "01"}, {"FEB", "02"}, {"MAR", "03"}, {"APR", "04"},
+ {"MAY", "05"}, {"JUN", "06"}, {"JUL", "07"}, {"AUG", "08"},
+ {"SEP", "09"}, {"OCT", "10"}, {"NOV", "11"}, {"DEC", "12"}};
+ const QString mm = mon.value(p[1].toUpper());
+ if (mm.isEmpty())
+ return {};
+ const QString dd = p[0].rightJustified(2, '0');
+ return QStringLiteral("%1-%2-%3T06:00:00.000Z").arg(p[2], mm, dd);
+}
+
+// "yyyy-MM-dd" (caller format) -> Breeze ISO datetime. `end_of_day` selects the
+// session-close time; otherwise session-open. Passes through values that already
+// look like ISO datetimes.
+QString icici_iso_datetime(const QString& date, bool end_of_day) {
+ const QDate d = QDate::fromString(date, "yyyy-MM-dd");
+ if (!d.isValid())
+ return date;
+ return d.toString("yyyy-MM-dd") + (end_of_day ? "T15:30:00.000Z" : "T09:15:00.000Z");
+}
+
+// Map a generic resolution onto a Breeze historicalcharts interval.
+QString icici_interval(const QString& resolution) {
+ static const QMap<QString, QString> map = {
+ {"1", "1minute"}, {"1m", "1minute"}, {"5", "5minute"}, {"5m", "5minute"},
+ {"30", "30minute"}, {"30m", "30minute"}, {"D", "1day"}, {"1D", "1day"},
+ {"day", "1day"}, {"1day", "1day"},
+ };
+ return map.value(resolution, QString());
+}
+
+// Split "NSE:RELIANCE" -> ("NSE","RELIANCE"); bare "RELIANCE" -> ("NSE","RELIANCE").
+QPair<QString, QString> split_symbol(const QString& s) {
+ if (s.contains(':'))
+ return {s.section(':', 0, 0).toUpper(), s.section(':', 1)};
+ return {QStringLiteral("NSE"), s};
+}
+
+} // namespace
+
+QString IciciDirectBroker::icici_login_url(const QString& api_key) {
+ return QStringLiteral("https://api.icicidirect.com/apiuser/login?api_key=%1")
+ .arg(QString::fromUtf8(QUrl::toPercentEncoding(api_key)));
+}
+
+QMap<QString, QString> IciciDirectBroker::breeze_headers(const BrokerCredentials& creds, const QByteArray& body) const {
+ const QString ts = breeze_timestamp();
+ const QByteArray to_sign = ts.toUtf8() + body + creds.api_secret.toUtf8();
+ const QString checksum = QString::fromLatin1(QCryptographicHash::hash(to_sign, QCryptographicHash::Sha256).toHex());
+ return {
+ {"Content-Type", "application/json"},
+ {"X-Checksum", "token " + checksum},
+ {"X-Timestamp", ts},
+ {"X-AppKey", creds.api_key},
+ {"X-SessionToken", creds.access_token},
+ };
+}
+
+// Base (unsigned) headers — used for the one-time /customerdetails call, which
+// authenticates via the body rather than a checksum.
+QMap<QString, QString> IciciDirectBroker::auth_headers(const BrokerCredentials& creds) const {
+ return {
+ {"Content-Type", "application/json"},
+ {"X-AppKey", creds.api_key},
+ {"X-SessionToken", creds.access_token},
+ };
+}
+
+BrokerHttpResponse IciciDirectBroker::breeze_request(const QString& method, const QString& endpoint,
+ const QJsonObject& payload, const BrokerCredentials& creds) {
+ const QByteArray body = QJsonDocument(payload).toJson(QJsonDocument::Compact);
+ const QString url = QString(base_url()) + endpoint;
+ return BrokerHttp::instance().send(method, url, body, "application/json", breeze_headers(creds, body));
+}
+
+bool IciciDirectBroker::is_success(const BrokerHttpResponse& resp) {
+ if (!resp.success)
+ return false;
+ // Envelope: {"Success": <data>, "Status": 200, "Error": null}
+ const QJsonValue err = resp.json.value("Error");
+ if (err.isString() && !err.toString().isEmpty())
+ return false;
+ const int status = resp.json.value("Status").toInt(200);
+ return status >= 200 && status < 300;
+}
+
+QString IciciDirectBroker::checked_error(const BrokerHttpResponse& resp, const QString& fallback) {
+ const QString err = resp.json.value("Error").toString();
+ if (!err.isEmpty())
+ return err;
+ if (!resp.error.isEmpty())
+ return resp.error;
+ return fallback;
+}
+
+TokenExchangeResponse IciciDirectBroker::exchange_token(const QString& api_key, const QString& api_secret,
+ const QString& auth_code) {
+ Q_UNUSED(api_secret)
+ TokenExchangeResponse result;
+
+ // Trade the raw API Session for the base64 session token via /customerdetails.
+ // This call carries the session + app key in the body and is NOT checksum-signed.
+ QJsonObject body{{"SessionToken", auth_code}, {"AppKey", api_key}};
+ const QByteArray body_bytes = QJsonDocument(body).toJson(QJsonDocument::Compact);
+ QMap<QString, QString> headers{{"Content-Type", "application/json"}};
+ auto resp = BrokerHttp::instance().send("GET", QString(base_url()) + "/customerdetails", body_bytes,
+ "application/json", headers);
+
+ LOG_INFO("IciciDirect", QString("customerdetails HTTP %1 success=%2 body=%3")
+ .arg(resp.status_code)
+ .arg(resp.success)
+ .arg(resp.raw_body.left(300)));
+
+ if (!resp.success) {
+ result.error = resp.json.value("Error").toString(
+ resp.error.isEmpty() ? QString("HTTP %1").arg(resp.status_code) : resp.error);
+ return result;
+ }
+
+ const QJsonObject success = resp.json.value("Success").toObject();
+ const QString session_b64 = success.value("session_token").toString();
+ if (session_b64.isEmpty()) {
+ result.error = resp.json.value("Error").toString("ICICI session token missing in customerdetails response");
+ return result;
+ }
+
+ // session_token = base64("user_id:session_key"); decode for the user id and
+ // reuse the base64 value verbatim as the X-SessionToken header.
+ const QString decoded = QString::fromUtf8(QByteArray::fromBase64(session_b64.toUtf8()));
+ const QString user_id = decoded.section(':', 0, 0);
+
+ result.success = true;
+ result.access_token = session_b64;
+ result.user_id = user_id.isEmpty() ? success.value("idirect_userid").toString() : user_id;
+ LOG_INFO("IciciDirect", QString("exchange_token ok: user_id=%1").arg(result.user_id));
+ return result;
+}
+
+OrderPlaceResponse IciciDirectBroker::place_order(const BrokerCredentials& creds, const UnifiedOrder& order) {
+ OrderPlaceResponse result;
+
+ QString stock_code = order.symbol;
+ QString exchange_code = order.exchange.isEmpty() ? QStringLiteral("NSE") : order.exchange.toUpper();
+ QString product = icici_equity_product(order.product_type);
+ QString expiry_iso;
+ QString right = QStringLiteral("others");
+ QString strike_str;
+
+ // Resolve the ICICI stock_code (and F&O decomposition) from the master.
+ auto inst = InstrumentService::instance().find(order.symbol, exchange_code, "icicidirect");
+ if (inst.has_value()) {
+ stock_code = inst->brsymbol;
+ if (!inst->brexchange.isEmpty())
+ exchange_code = inst->brexchange.toUpper();
+ switch (inst->instrument_type) {
+ case InstrumentType::FUT:
+ product = "futures";
+ expiry_iso = icici_iso_expiry(inst->expiry);
+ break;
+ case InstrumentType::CE:
+ case InstrumentType::PE:
+ product = "options";
+ expiry_iso = icici_iso_expiry(inst->expiry);
+ right = (inst->instrument_type == InstrumentType::CE) ? "call" : "put";
+ strike_str = QString::number(inst->strike, 'f', 2);
+ break;
+ default:
+ break;
+ }
+ }
+
+ QJsonObject payload{
+ {"stock_code", stock_code},
+ {"exchange_code", exchange_code},
+ {"product", product},
+ {"action", (order.side == OrderSide::Buy) ? "buy" : "sell"},
+ {"order_type", icici_order_type(order.order_type)},
+ {"quantity", QString::number(static_cast<qlonglong>(order.quantity))},
+ {"validity", order.validity.isEmpty() ? QStringLiteral("day") : order.validity.toLower()},
+ {"disclosed_quantity", "0"},
+ {"price", order.price > 0 ? QString::number(order.price, 'f', 2) : QString()},
+ {"stoploss", order.stop_price > 0 ? QString::number(order.stop_price, 'f', 2) : QString()},
+ {"expiry_date", expiry_iso},
+ {"right", right},
+ {"strike_price", strike_str},
+ {"user_remark", "fincept"},
+ };
+
+ auto resp = breeze_request("POST", "/order", payload, creds);
+ if (!is_success(resp)) {
+ result.error = checked_error(resp, "Order placement failed");
+ return result;
+ }
+ result.success = true;
+ result.order_id = resp.json.value("Success").toObject().value("order_id").toString();
+ return result;
+}
+
+ApiResponse<QJsonObject> IciciDirectBroker::modify_order(const BrokerCredentials& creds, const QString& order_id,
+ const QJsonObject& mods) {
+ QJsonObject payload{
+ {"order_id", order_id},
+ {"exchange_code", mods.value("exchange_code").toString("NSE")},
+ };
+ for (const QString& k : {QStringLiteral("order_type"), QStringLiteral("quantity"), QStringLiteral("price"),
+ QStringLiteral("stoploss"), QStringLiteral("validity"),
+ QStringLiteral("disclosed_quantity"), QStringLiteral("validity_date")}) {
+ if (mods.contains(k))
+ payload[k] = mods.value(k);
+ }
+ auto resp = breeze_request("PUT", "/order", payload, creds);
+ int64_t ts = now_ts();
+ if (!is_success(resp))
+ return {false, std::nullopt, checked_error(resp, "Modify failed"), ts};
+ return {true, resp.json, "", ts};
+}
+
+ApiResponse<QJsonObject> IciciDirectBroker::cancel_order(const BrokerCredentials& creds, const QString& order_id) {
+ // Breeze cancel needs the exchange. Without it on this signature, default to
+ // NSE but honour an override packed in creds.additional_data {"exchange":...}.
+ QString exchange = "NSE";
+ if (!creds.additional_data.isEmpty()) {
+ const auto ad = QJsonDocument::fromJson(creds.additional_data.toUtf8()).object();
+ const QString e = ad.value("exchange").toString();
+ if (!e.isEmpty())
+ exchange = e.toUpper();
+ }
+ QJsonObject payload{{"order_id", order_id}, {"exchange_code", exchange}};
+ auto resp = breeze_request("DELETE", "/order", payload, creds);
+ int64_t ts = now_ts();
+ if (!is_success(resp))
+ return {false, std::nullopt, checked_error(resp, "Cancel failed"), ts};
+ return {true, resp.json, "", ts};
+}
+
+ApiResponse<QVector<BrokerOrderInfo>> IciciDirectBroker::get_orders(const BrokerCredentials& creds) {
+ // Breeze scopes the order book by exchange + date range. Query the common
+ // equity/derivative exchanges for today and merge.
+ const QString from = icici_iso_datetime(QDate::currentDate().toString("yyyy-MM-dd"), false);
+ const QString to = icici_iso_datetime(QDate::currentDate().toString("yyyy-MM-dd"), true);
+
+ QVector<BrokerOrderInfo> orders;
+ QString last_error;
+ bool any_ok = false;
+ for (const QString& exch : {QStringLiteral("NSE"), QStringLiteral("NFO"), QStringLiteral("BSE")}) {
+ QJsonObject payload{{"exchange_code", exch}, {"from_date", from}, {"to_date", to}};
+ auto resp = breeze_request("GET", "/order", payload, creds);
+ if (!is_success(resp)) {
+ last_error = checked_error(resp, "Failed to fetch orders");
+ continue;
+ }
+ any_ok = true;
+ for (const auto& v : resp.json.value("Success").toArray()) {
+ const auto o = v.toObject();
+ BrokerOrderInfo info;
+ info.order_id = jstr(o, "order_id");
+ info.exchange = jstr(o, "exchange_code");
+ info.symbol = jstr(o, "stock_code");
+ info.side = jstr(o, "action");
+ info.order_type = jstr(o, "order_type");
+ info.product_type = jstr(o, "product_type");
+ info.quantity = jnum(o, "quantity");
+ info.price = jnum(o, "price");
+ info.trigger_price = jnum(o, "stoploss");
+ info.filled_qty = jnum(o, "quantity") - jnum(o, "pending_quantity");
+ info.avg_price = jnum(o, "average_price");
+ info.status = jstr(o, "status");
+ info.timestamp = jstr(o, "order_datetime");
+ orders.append(info);
+ }
+ }
+ int64_t ts = now_ts();
+ if (!any_ok)
+ return {false, std::nullopt, last_error.isEmpty() ? "Failed to fetch orders" : last_error, ts};
+ return {true, orders, "", ts};
+}
+
+ApiResponse<QJsonObject> IciciDirectBroker::get_trade_book(const BrokerCredentials& creds) {
+ const QString from = icici_iso_datetime(QDate::currentDate().toString("yyyy-MM-dd"), false);
+ const QString to = icici_iso_datetime(QDate::currentDate().toString("yyyy-MM-dd"), true);
+ QJsonObject payload{{"exchange_code", "NSE"}, {"from_date", from}, {"to_date", to}};
+ auto resp = breeze_request("GET", "/trades", payload, creds);
+ int64_t ts = now_ts();
+ if (!is_success(resp))
+ return {false, std::nullopt, checked_error(resp, "Failed to fetch trades"), ts};
+ return {true, resp.json, "", ts};
+}
+
+ApiResponse<QVector<BrokerPosition>> IciciDirectBroker::get_positions(const BrokerCredentials& creds) {
+ auto resp = breeze_request("GET", "/portfoliopositions", QJsonObject{}, creds);
+ int64_t ts = now_ts();
+ if (!is_success(resp))
+ return {false, std::nullopt, checked_error(resp, "Failed to fetch positions"), ts};
+
+ QVector<BrokerPosition> out;
+ for (const auto& v : resp.json.value("Success").toArray()) {
+ const auto o = v.toObject();
+ BrokerPosition p;
+ const QString code = jstr(o, "stock_code");
+ p.exchange = jstr(o, "exchange_code");
+ auto norm = InstrumentService::instance().from_brsymbol(code, p.exchange, "icicidirect");
+ p.symbol = norm.has_value() ? norm.value() : code;
+ p.product_type = jstr(o, "product_type");
+ p.quantity = jnum(o, "quantity");
+ p.avg_price = jnum(o, "average_price");
+ p.ltp = jnum(o, "ltp");
+ p.pnl = jnum(o, "pnl");
+ p.side = jstr(o, "action");
+ const double cost = std::abs(p.avg_price * p.quantity);
+ p.pnl_pct = cost > 0 ? (p.pnl / cost) * 100.0 : 0.0;
+ out.append(p);
+ }
+ return {true, out, "", ts};
+}
+
+ApiResponse<QVector<BrokerHolding>> IciciDirectBroker::get_holdings(const BrokerCredentials& creds) {
+ QJsonObject payload{{"exchange_code", "NSE"}, {"from_date", ""}, {"to_date", ""},
+ {"stock_code", ""}, {"portfolio_type", ""}};
+ auto resp = breeze_request("GET", "/portfolioholdings", payload, creds);
+ int64_t ts = now_ts();
+ if (!is_success(resp))
+ return {false, std::nullopt, checked_error(resp, "Failed to fetch holdings"), ts};
+
+ QVector<BrokerHolding> out;
+ for (const auto& v : resp.json.value("Success").toArray()) {
+ const auto o = v.toObject();
+ BrokerHolding h;
+ const QString code = jstr(o, "stock_code");
+ h.exchange = jstr(o, "exchange_code");
+ auto norm = InstrumentService::instance().from_brsymbol(code, h.exchange, "icicidirect");
+ h.symbol = norm.has_value() ? norm.value() : code;
+ h.quantity = jnum(o, "quantity");
+ h.avg_price = jnum(o, "average_price");
+ h.ltp = jnum(o, "current_market_price");
+ h.invested_value = h.quantity * h.avg_price;
+ h.current_value = h.quantity * h.ltp;
+ h.pnl = h.current_value - h.invested_value;
+ h.pnl_pct = h.avg_price > 0 ? ((h.ltp - h.avg_price) / h.avg_price) * 100.0 : 0.0;
+ out.append(h);
+ }
+ return {true, out, "", ts};
+}
+
+ApiResponse<BrokerFunds> IciciDirectBroker::get_funds(const BrokerCredentials& creds) {
+ auto resp = breeze_request("GET", "/funds", QJsonObject{}, creds);
+ int64_t ts = now_ts();
+ if (!is_success(resp))
+ return {false, std::nullopt, checked_error(resp, "Failed to fetch funds"), ts};
+
+ const QJsonObject s = resp.json.value("Success").toObject();
+ BrokerFunds funds;
+ funds.total_balance = jnum(s, "total_bank_balance");
+ funds.available_balance = jnum(s, "unallocated_balance");
+ funds.used_margin = jnum(s, "block_by_trade_balance");
+ funds.raw_data = resp.json;
+ return {true, funds, "", ts};
+}
+
+ApiResponse<QVector<BrokerQuote>> IciciDirectBroker::get_quotes(const BrokerCredentials& creds,
+ const QVector<QString>& symbols) {
+ // Breeze quotes one instrument per call; loop and collect.
+ QVector<BrokerQuote> quotes;
+ QString last_error;
+ bool any_ok = false;
+
+ for (const QString& raw : symbols) {
+ auto [exch, sym] = split_symbol(raw);
+ QString stock_code = sym;
+ QString product = "cash";
+ QString expiry_iso;
+ QString right;
+ QString strike_str;
+
+ auto inst = InstrumentService::instance().find(sym, exch, "icicidirect");
+ if (inst.has_value()) {
+ stock_code = inst->brsymbol;
+ if (!inst->brexchange.isEmpty())
+ exch = inst->brexchange.toUpper();
+ if (inst->instrument_type == InstrumentType::FUT) {
+ product = "futures";
+ expiry_iso = icici_iso_expiry(inst->expiry);
+ } else if (inst->instrument_type == InstrumentType::CE || inst->instrument_type == InstrumentType::PE) {
+ product = "options";
+ expiry_iso = icici_iso_expiry(inst->expiry);
+ right = (inst->instrument_type == InstrumentType::CE) ? "call" : "put";
+ strike_str = QString::number(inst->strike, 'f', 2);
+ }
+ }
+
+ QJsonObject payload{
+ {"stock_code", stock_code}, {"exchange_code", exch}, {"product_type", product},
+ {"expiry_date", expiry_iso}, {"right", right}, {"strike_price", strike_str},
+ };
+ auto resp = breeze_request("GET", "/quotes", payload, creds);
+ if (!is_success(resp)) {
+ last_error = checked_error(resp, "Failed to fetch quote");
+ continue;
+ }
+ any_ok = true;
+ const QJsonArray arr = resp.json.value("Success").toArray();
+ if (arr.isEmpty())
+ continue;
+ const QJsonObject o = arr.first().toObject();
+ BrokerQuote q;
+ q.symbol = raw;
+ q.ltp = jnum(o, "ltp");
+ q.open = jnum(o, "open");
+ q.high = jnum(o, "high");
+ q.low = jnum(o, "low");
+ q.close = jnum(o, "previous_close");
+ q.volume = jnum(o, "total_quantity_traded");
+ q.bid = jnum(o, "best_bid_price");
+ q.bid_size = jnum(o, "best_bid_quantity");
+ q.ask = jnum(o, "best_offer_price");
+ q.ask_size = jnum(o, "best_offer_quantity");
+ q.change_pct = jnum(o, "ltp_percent_change");
+ q.change = q.close > 0 ? q.ltp - q.close : 0.0;
+ q.timestamp = now_ts();
+ quotes.append(q);
+ }
+
+ int64_t ts = now_ts();
+ if (!any_ok && !symbols.isEmpty())
+ return {false, std::nullopt, last_error.isEmpty() ? "Failed to fetch quotes" : last_error, ts};
+ return {true, quotes, "", ts};
+}
+
+ApiResponse<QVector<BrokerCandle>> IciciDirectBroker::get_history(const BrokerCredentials& creds, const QString& symbol,
+ const QString& resolution, const QString& from_date,
+ const QString& to_date) {
+ const QString interval = icici_interval(resolution);
+ if (interval.isEmpty())
+ return {false, std::nullopt, "ICICI get_history: unsupported resolution '" + resolution + "'", now_ts()};
+
+ auto [exch, sym] = split_symbol(symbol);
+ QString stock_code = sym;
+ QString product = "cash";
+ QString expiry_iso;
+ QString right;
+ QString strike_str;
+
+ auto inst = InstrumentService::instance().find(sym, exch, "icicidirect");
+ if (inst.has_value()) {
+ stock_code = inst->brsymbol;
+ if (!inst->brexchange.isEmpty())
+ exch = inst->brexchange.toUpper();
+ if (inst->instrument_type == InstrumentType::FUT) {
+ product = "futures";
+ expiry_iso = icici_iso_expiry(inst->expiry);
+ } else if (inst->instrument_type == InstrumentType::CE || inst->instrument_type == InstrumentType::PE) {
+ product = "options";
+ expiry_iso = icici_iso_expiry(inst->expiry);
+ right = (inst->instrument_type == InstrumentType::CE) ? "call" : "put";
+ strike_str = QString::number(inst->strike, 'f', 2);
+ }
+ }
+
+ QJsonObject payload{
+ {"interval", interval},
+ {"from_date", icici_iso_datetime(from_date, false)},
+ {"to_date", icici_iso_datetime(to_date, true)},
+ {"stock_code", stock_code},
+ {"exchange_code", exch},
+ {"product_type", product},
+ {"expiry_date", expiry_iso},
+ {"right", right},
+ {"strike_price", strike_str},
+ };
+ auto resp = breeze_request("GET", "/historicalcharts", payload, creds);
+ int64_t ts = now_ts();
+ if (!is_success(resp))
+ return {false, std::nullopt, checked_error(resp, "Failed to fetch history"), ts};
+
+ QVector<BrokerCandle> candles;
+ for (const auto& v : resp.json.value("Success").toArray()) {
+ const auto o = v.toObject();
+ BrokerCandle c;
+ const QString dt = jstr(o, "datetime");
+ QDateTime when = QDateTime::fromString(dt, Qt::ISODate);
+ if (!when.isValid())
+ when = QDateTime::fromString(dt, "yyyy-MM-dd hh:mm:ss");
+ c.timestamp = when.isValid() ? when.toSecsSinceEpoch() : 0;
+ c.open = jnum(o, "open");
+ c.high = jnum(o, "high");
+ c.low = jnum(o, "low");
+ c.close = jnum(o, "close");
+ c.volume = jnum(o, "volume");
+ c.oi = jnum(o, "open_interest");
+ candles.append(c);
+ }
+ return {true, candles, "", ts};
+}
+
+} // namespace fincept::trading
diff --git a/fincept-qt/src/trading/brokers/icicidirect/IciciDirectBroker.h b/fincept-qt/src/trading/brokers/icicidirect/IciciDirectBroker.h
new file mode 100644
index 000000000..92f8ef762
--- /dev/null
+++ b/fincept-qt/src/trading/brokers/icicidirect/IciciDirectBroker.h
@@ -0,0 +1,97 @@
+#pragma once
+#include "trading/BrokerInterface.h"
+#include "trading/brokers/BrokerHttp.h"
+
+namespace fincept::trading {
+
+/// ICICI Direct (Breeze API) broker integration.
+///
+/// Auth: the user enters API Key + Secret Key, visits icici_login_url() to obtain
+/// an "API Session" token, and pastes it back. exchange_token() trades that for a
+/// base64 session token (via /customerdetails) which becomes the X-SessionToken
+/// header. Every subsequent request is signed with
+/// X-Checksum: token <SHA256(timestamp + json_body + secret_key)>
+///
+/// Breeze quirk: reads use GET-with-JSON-body, and one resource endpoint serves
+/// multiple operations dispatched by HTTP verb (GET=read, POST=place, PUT=modify,
+/// DELETE=cancel). Symbol mapping (normal ticker <-> ICICI stock_code, plus F&O
+/// expiry/strike/right decomposition) comes from InstrumentService ("icicidirect").
+///
+/// Scope (v1): REST only. Live tick streaming (Breeze Socket.IO) is deferred, so
+/// ws_adapter_name() returns "".
+class IciciDirectBroker : public IBroker {
+ public:
+ BrokerId id() const override { return BrokerId::IciciDirect; }
+ const char* name() const override { return "ICICI Direct"; }
+ const char* base_url() const override { return "https://api.icicidirect.com/breezeapi/api/v1"; }
+ const char* ws_adapter_name() const override { return ""; } // streaming deferred
+
+ BrokerProfile profile() const override {
+ return BrokerProfile{
+ .id = "icicidirect",
+ .display_name = "ICICI Direct",
+ .region = "IN",
+ .currency = "INR",
+ .credential_fields =
+ {
+ {CredentialField::ApiKey, "API KEY", "Enter App Key (api_key)...", false},
+ {CredentialField::ApiSecret, "SECRET KEY", "Enter Secret Key...", true},
+ {CredentialField::AuthCode, "API SESSION", "Login via Breeze & paste API Session...", false},
+ },
+ .exchanges = {"NSE", "BSE", "NFO", "BFO", "MCX"},
+ .product_types =
+ {
+ {"Delivery (Cash)", ProductType::Delivery},
+ {"Intraday (Margin)", ProductType::Intraday},
+ {"Futures", ProductType::Margin},
+ {"MTF", ProductType::MTF},
+ },
+ .supports_intraday = true,
+ .supports_bracket_order = false,
+ .supports_cover_order = false,
+ .has_native_paper = false,
+ .default_paper_balance = 1000000.0,
+ .default_watchlist = {"ICICIBANK", "HDFCBANK", "SBIN", "RELIANCE", "TCS", "INFY", "AXISBANK",
+ "KOTAKBANK", "TATAMOTORS", "BAJFINANCE"},
+ .default_symbol = "RELIANCE",
+ .default_exchange = "NSE",
+ .brokerage_info = "0.05% (cash)/0.05% or ₹20 (intraday); free API",
+ };
+ }
+
+ /// URL the user visits to obtain an API Session token (pure string, any thread).
+ static QString icici_login_url(const QString& api_key);
+
+ TokenExchangeResponse exchange_token(const QString& api_key, const QString& api_secret,
+ const QString& auth_code) override;
+ OrderPlaceResponse place_order(const BrokerCredentials& creds, const UnifiedOrder& order) override;
+ ApiResponse<QJsonObject> modify_order(const BrokerCredentials& creds, const QString& order_id,
+ const QJsonObject& mods) override;
+ ApiResponse<QJsonObject> cancel_order(const BrokerCredentials& creds, const QString& order_id) override;
+ ApiResponse<QVector<BrokerOrderInfo>> get_orders(const BrokerCredentials& creds) override;
+ ApiResponse<QJsonObject> get_trade_book(const BrokerCredentials& creds) override;
+ ApiResponse<QVector<BrokerPosition>> get_positions(const BrokerCredentials& creds) override;
+ ApiResponse<QVector<BrokerHolding>> get_holdings(const BrokerCredentials& creds) override;
+ ApiResponse<BrokerFunds> get_funds(const BrokerCredentials& creds) override;
+ ApiResponse<QVector<BrokerQuote>> get_quotes(const BrokerCredentials& creds,
+ const QVector<QString>& symbols) override;
+ ApiResponse<QVector<BrokerCandle>> get_history(const BrokerCredentials& creds, const QString& symbol,
+ const QString& resolution, const QString& from_date,
+ const QString& to_date) override;
+
+ protected:
+ QMap<QString, QString> auth_headers(const BrokerCredentials& creds) const override;
+
+ private:
+ /// Fully-signed Breeze headers for a request whose exact serialised body is
+ /// `body` (the checksum signs timestamp + body + secret_key).
+ QMap<QString, QString> breeze_headers(const BrokerCredentials& creds, const QByteArray& body) const;
+ /// Serialise `payload`, sign it, and dispatch `method` to base_url()+endpoint.
+ BrokerHttpResponse breeze_request(const QString& method, const QString& endpoint, const QJsonObject& payload,
+ const BrokerCredentials& creds);
+ /// True when the Breeze envelope reports success ({"Status":200,"Error":null}).
+ static bool is_success(const BrokerHttpResponse& resp);
+ static QString checked_error(const BrokerHttpResponse& resp, const QString& fallback);
+};
+
+} // namespace fincept::trading
diff --git a/fincept-qt/src/trading/brokers/kotak/KotakBroker.cpp b/fincept-qt/src/trading/brokers/kotak/KotakBroker.cpp
index 7e6de00b5..8a64e9f61 100644
--- a/fincept-qt/src/trading/brokers/kotak/KotakBroker.cpp
+++ b/fincept-qt/src/trading/brokers/kotak/KotakBroker.cpp
@@ -742,7 +742,10 @@ ApiResponse<QVector<BrokerCandle>> KotakBroker::get_history(const BrokerCredenti
const QString& /*from_date*/, const QString& /*to_date*/) {
int64_t ts = now_ts();
LOG_WARN(TAG, "get_history called — Kotak Neo does not support historical data");
- return {true, QVector<BrokerCandle>{}, "", ts};
+ // Kotak Neo exposes no historical/candle REST endpoint (confirmed by Kotak's
+ // own support docs and the official Neo SDK). Return empty-but-successful with
+ // an explanatory message so charts render a graceful "no data" state.
+ return {true, QVector<BrokerCandle>{}, "Kotak Neo does not provide a historical data API", ts};
}
// ============================================================================
diff --git a/fincept-qt/src/trading/brokers/motilal/MotilalBroker.cpp b/fincept-qt/src/trading/brokers/motilal/MotilalBroker.cpp
index 5cbb4334d..6a6698b87 100644
--- a/fincept-qt/src/trading/brokers/motilal/MotilalBroker.cpp
+++ b/fincept-qt/src/trading/brokers/motilal/MotilalBroker.cpp
@@ -1,6 +1,9 @@
#include "trading/brokers/motilal/MotilalBroker.h"
#include "trading/brokers/BrokerHttp.h"
+#include "trading/instruments/InstrumentService.h"
+
+#include <algorithm>
#include <QCryptographicHash>
#include <QDateTime>
@@ -599,7 +602,8 @@ ApiResponse<QVector<BrokerCandle>> MotilalBroker::get_history(const BrokerCreden
const QString& to_date) {
int64_t ts = now_ts();
- // Only daily / weekly / monthly are supported.
+ // Only daily / weekly / monthly are supported — Motilal Oswal has no public
+ // intraday history endpoint.
const QString r = resolution.toUpper();
const bool is_daily = r == "D" || r == "1D" || r == "DAY" || r == "W" || r == "1W" || r == "WEEK" ||
r == "M" || r == "1M" || r == "MONTH";
@@ -607,17 +611,24 @@ ApiResponse<QVector<BrokerCandle>> MotilalBroker::get_history(const BrokerCreden
return {false, std::nullopt,
"Motilal Oswal historical API supports only EOD bars (D/W/M). Intraday is unavailable.", ts};
- // Parse "EX:SYMBOL:TOKEN" — token is required.
+ // Parse "EX:SYMBOL[:TOKEN]". Token keys the scripcode; resolve it from
+ // InstrumentService when the caller didn't pass it explicitly.
QStringList parts = symbol.split(':');
QString exch = parts.size() >= 1 ? parts[0] : "NSE";
QString name = parts.size() >= 2 ? parts[1] : symbol;
QString token = parts.size() >= 3 ? parts[2] : QString();
+ if (token.isEmpty()) {
+ auto tok = InstrumentService::instance().instrument_token(name, exch, creds.broker_id);
+ if (tok.has_value() && tok.value() > 0)
+ token = QString::number(static_cast<qlonglong>(tok.value()));
+ }
if (token.isEmpty())
return {false, std::nullopt, "MO history requires instrument token (format EXCHANGE:SYMBOL:TOKEN)", ts};
QJsonObject body;
body["clientcode"] = creds.user_id;
- body["exchange"] = mo_exchange(exch);
+ body["exchangename"] = mo_exchange(exch); // documented field name
+ body["exchange"] = mo_exchange(exch); // older deployments accept `exchange`
body["scripcode"] = token.toInt();
body["fromdate"] = from_date;
body["todate"] = to_date;
@@ -635,17 +646,35 @@ ApiResponse<QVector<BrokerCandle>> MotilalBroker::get_history(const BrokerCreden
if (obj.value("status").toString() != "SUCCESS")
return {false, std::nullopt, obj.value("message").toString("get_history failed"), ts};
+ // `geteoddatabyexchangename` can return one row per scrip for the whole
+ // exchange and may ignore the date range — keep only the requested scripcode
+ // and clamp [from, to] client-side so callers always get the right series.
+ const int want_scrip = token.toInt();
+ const QDate d_from = QDate::fromString(from_date, "yyyy-MM-dd");
+ const QDate d_to = QDate::fromString(to_date, "yyyy-MM-dd");
+
QVector<BrokerCandle> candles;
const QJsonArray rows = obj.value("data").toArray();
candles.reserve(rows.size());
for (const auto& v : rows) {
const QJsonObject o = v.toObject();
- BrokerCandle c;
+ if (want_scrip != 0 && o.contains("scripcode") &&
+ o.value("scripcode").toVariant().toInt() != want_scrip)
+ continue;
const QString date_str = o.value("date").toString();
- // MO returns "yyyy-MM-dd" or "dd-MMM-yyyy" depending on the deployment.
+ // Date formats seen across MO deployments: yyyy-MM-dd, dd-MM-yyyy, dd-MMM-yyyy.
QDate d = QDate::fromString(date_str, "yyyy-MM-dd");
+ if (!d.isValid())
+ d = QDate::fromString(date_str, "dd-MM-yyyy");
if (!d.isValid())
d = QDate::fromString(date_str, "dd-MMM-yyyy");
+ if (d.isValid()) {
+ if (d_from.isValid() && d < d_from)
+ continue;
+ if (d_to.isValid() && d > d_to)
+ continue;
+ }
+ BrokerCandle c;
c.timestamp = d.isValid() ? QDateTime(d, QTime(15, 30)).toSecsSinceEpoch() : 0;
c.open = o.value("open").toDouble();
c.high = o.value("high").toDouble();
@@ -654,6 +683,9 @@ ApiResponse<QVector<BrokerCandle>> MotilalBroker::get_history(const BrokerCreden
c.volume = o.value("volume").toDouble();
candles.append(c);
}
+
+ std::sort(candles.begin(), candles.end(),
+ [](const BrokerCandle& a, const BrokerCandle& b) { return a.timestamp < b.timestamp; });
return {true, candles, "", ts};
}
diff --git a/fincept-qt/src/trading/brokers/paytm/PaytmBroker.cpp b/fincept-qt/src/trading/brokers/paytm/PaytmBroker.cpp
index 7dd5df333..29b2b1fee 100644
--- a/fincept-qt/src/trading/brokers/paytm/PaytmBroker.cpp
+++ b/fincept-qt/src/trading/brokers/paytm/PaytmBroker.cpp
@@ -5,7 +5,11 @@
#include <QDateTime>
#include <QJsonArray>
#include <QJsonDocument>
+#include <QTimeZone>
#include <QUrl>
+#include <QUrlQuery>
+
+#include <algorithm>
namespace fincept::trading {
@@ -21,6 +25,45 @@ static QJsonValue pm_first(const QJsonObject& o, const QString& a, const QString
return o.contains(a) ? o.value(a) : o.value(b);
}
+// Map a unified exchange to the value Paytm's chart endpoint expects. The
+// undocumented price-charts route is exercised here for equities only, so only
+// the cash exchanges are accepted; anything else returns "" (caller errors).
+static QString api_exchange_for_history(const QString& exchange) {
+ const QString e = exchange.toUpper();
+ if (e == "NSE")
+ return "NSE";
+ if (e == "BSE")
+ return "BSE";
+ return QString();
+}
+
+// Best-effort timestamp -> epoch-milliseconds for the undocumented chart payload,
+// whose time field shape is unknown. Handles numeric seconds, numeric ms, and a
+// few string date/datetime formats (interpreted as IST). Returns 0 on failure.
+static int64_t pm_history_epoch_ms(const QJsonValue& v) {
+ if (v.isDouble()) {
+ const int64_t n = static_cast<int64_t>(v.toVariant().toLongLong());
+ return (n > 1000000000000LL) ? n : n * 1000LL; // 13-digit ms vs 10-digit s
+ }
+ const QString s = v.toVariant().toString();
+ if (s.isEmpty())
+ return 0;
+ bool ok = false;
+ const qint64 n = s.toLongLong(&ok);
+ if (ok)
+ return (n > 1000000000000LL) ? n : n * 1000LL;
+ const QTimeZone ist(19800); // +5:30
+ for (const char* fmt : {"yyyy-MM-ddTHH:mm:ss", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd"}) {
+ QDateTime dt = QDateTime::fromString(s, fmt);
+ if (dt.isValid()) {
+ dt.setTimeZone(ist);
+ return dt.toMSecsSinceEpoch();
+ }
+ }
+ QDateTime iso = QDateTime::fromString(s, Qt::ISODate);
+ return iso.isValid() ? iso.toMSecsSinceEpoch() : 0;
+}
+
// ---------- Static helpers ----------
const BrokerEnumMap<QString>& PaytmBroker::pm_enum_map() {
@@ -540,14 +583,132 @@ ApiResponse<QVector<BrokerQuote>> PaytmBroker::get_quotes(const BrokerCredential
}
// ---------- get_history ----------
-// Paytm Money does not expose a historical-data API. Return an empty result so
-// downstream consumers (charts, IV/straddle tooling) render a graceful no-data
-// state rather than erroring. Mirrors OpenAlgo's Paytm BrokerData.get_history.
-
-ApiResponse<QVector<BrokerCandle>> PaytmBroker::get_history(const BrokerCredentials& /*creds*/,
- const QString& /*symbol*/, const QString& /*resolution*/,
- const QString& /*from_date*/, const QString& /*to_date*/) {
- return {true, QVector<BrokerCandle>{}, "Paytm Money does not provide a historical data API", now_ts()};
+// EXPERIMENTAL / UNDOCUMENTED endpoint.
+//
+// Paytm Money publishes no historical-data API in its docs, but the official
+// pyPMClient SDK carries a disabled route under a "# historical_data endpoints"
+// comment: GET /data/v1/price-charts/sym (pmClient/constants.py). Live probes
+// confirm the route is real and JWT-gated — no token -> 400 PM_OPEN_API_400 (the
+// same app-layer error the live-quote endpoint returns), bad token -> 401, and
+// POST -> 405 (so the live verb is GET, not the POST in the stale SDK). The
+// request/response contract is NOT officially documented; the query fields below
+// mirror the SDK's commented signature. Parsing is deliberately defensive and the
+// method fails soft (empty success) when the shape doesn't match, so charts
+// degrade gracefully. Verify against a live token before relying on this.
+//
+// Symbol format: "EXCHANGE:SYMBOL" (equity). SYMBOL is the trading symbol, NOT
+// the numeric security_id used by get_quotes — this endpoint keys on symbol.
+
+ApiResponse<QVector<BrokerCandle>> PaytmBroker::get_history(const BrokerCredentials& creds, const QString& symbol,
+ const QString& resolution, const QString& from_date,
+ const QString& to_date) {
+ int64_t ts = now_ts();
+
+ QString exchange = "NSE";
+ QString name = symbol;
+ if (symbol.contains(':')) {
+ exchange = symbol.section(':', 0, 0);
+ name = symbol.section(':', 1, 1);
+ }
+ if (api_exchange_for_history(exchange).isEmpty())
+ return {false, std::nullopt, "Paytm history: unsupported exchange " + exchange, ts};
+ if (name.isEmpty())
+ return {false, std::nullopt, "Paytm history: empty symbol", ts};
+
+ // Map the unified resolution to Paytm's chart interval token. The SDK sample
+ // shows "MINUTE"; daily/weekly/monthly tokens are inferred and may need
+ // adjustment once the live contract is confirmed.
+ const QString r = resolution.toUpper();
+ QString interval;
+ if (r == "D" || r == "1D" || r == "DAY")
+ interval = "DAY";
+ else if (r == "W" || r == "1W" || r == "WEEK")
+ interval = "WEEK";
+ else if (r == "M" || r == "1M" || r == "MONTH")
+ interval = "MONTH";
+ else
+ interval = "MINUTE"; // 1/5/15/30/60-minute all map here (count is implicit)
+
+ QUrlQuery q;
+ q.addQueryItem("symbol", name);
+ q.addQueryItem("exchange", api_exchange_for_history(exchange));
+ q.addQueryItem("instType", "EQUITY");
+ q.addQueryItem("interval", interval);
+ q.addQueryItem("fromDate", from_date);
+ q.addQueryItem("toDate", to_date);
+ q.addQueryItem("cont", "false");
+
+ const QString url = QString("%1/data/v1/price-charts/sym?%2").arg(BASE, q.toString(QUrl::FullyEncoded));
+ auto resp = BrokerHttp::instance().get(url, auth_headers(creds));
+
+ if (is_token_expired(resp))
+ return {false, std::nullopt, "[TOKEN_EXPIRED] Session expired, please re-login", ts};
+ if (!resp.success && resp.status_code == 0)
+ return {false, std::nullopt, checked_error(resp, "get_history failed"), ts};
+
+ QJsonDocument doc = QJsonDocument::fromJson(resp.raw_body.toUtf8());
+
+ // Locate the candle array across the shapes this undocumented endpoint might
+ // return: a bare array, {data:[...]}, or {data:{candles|data:[...]}}.
+ QJsonArray rows;
+ if (doc.isArray()) {
+ rows = doc.array();
+ } else if (doc.isObject()) {
+ const QJsonObject root = doc.object();
+ const QJsonValue d = root.value("data");
+ if (d.isArray())
+ rows = d.toArray();
+ else if (d.isObject()) {
+ const QJsonObject dobj = d.toObject();
+ rows = dobj.value("candles").toArray();
+ if (rows.isEmpty())
+ rows = dobj.value("data").toArray();
+ }
+ if (rows.isEmpty())
+ rows = root.value("candles").toArray();
+ }
+
+ QVector<BrokerCandle> candles;
+ candles.reserve(rows.size());
+ for (const QJsonValue& v : rows) {
+ BrokerCandle c;
+ if (v.isArray()) {
+ // [time, open, high, low, close, volume]
+ const QJsonArray row = v.toArray();
+ if (row.size() < 6)
+ continue;
+ c.timestamp = pm_history_epoch_ms(row[0]);
+ c.open = row[1].toVariant().toDouble();
+ c.high = row[2].toVariant().toDouble();
+ c.low = row[3].toVariant().toDouble();
+ c.close = row[4].toVariant().toDouble();
+ c.volume = row[5].toVariant().toDouble();
+ } else if (v.isObject()) {
+ const QJsonObject o = v.toObject();
+ QJsonValue tv = o.contains("time") ? o.value("time")
+ : o.contains("timestamp") ? o.value("timestamp")
+ : o.contains("date") ? o.value("date") : o.value("dateTime");
+ c.timestamp = pm_history_epoch_ms(tv);
+ c.open = pm_first(o, "open", "o").toVariant().toDouble();
+ c.high = pm_first(o, "high", "h").toVariant().toDouble();
+ c.low = pm_first(o, "low", "l").toVariant().toDouble();
+ c.close = pm_first(o, "close", "c").toVariant().toDouble();
+ c.volume = pm_first(o, "volume", "v").toVariant().toDouble();
+ } else {
+ continue;
+ }
+ candles.append(c);
+ }
+
+ std::sort(candles.begin(), candles.end(),
+ [](const BrokerCandle& a, const BrokerCandle& b) { return a.timestamp < b.timestamp; });
+
+ // Fail soft: if the undocumented contract didn't yield candles, return
+ // empty-success with a hint rather than erroring, so charts show "no data".
+ if (candles.isEmpty())
+ return {true, candles,
+ "Paytm history returned no parseable candles (undocumented endpoint — verify contract)", ts};
+ return {true, candles, "", ts};
}
} // namespace fincept::trading
diff --git a/fincept-qt/src/trading/brokers/tradejini/TradejiniBroker.cpp b/fincept-qt/src/trading/brokers/tradejini/TradejiniBroker.cpp
index c23ae4bd8..014ce35e8 100644
--- a/fincept-qt/src/trading/brokers/tradejini/TradejiniBroker.cpp
+++ b/fincept-qt/src/trading/brokers/tradejini/TradejiniBroker.cpp
@@ -456,8 +456,40 @@ ApiResponse<QVector<BrokerQuote>> TradejiniBroker::get_quotes(const BrokerCreden
"Tradejini quotes are WebSocket-only — use the streaming adapter (no REST quote endpoint)", now_ts()};
}
+// Roll up intraday OHLCV bars into one bar per IST civil day. Input must be
+// sorted ascending by timestamp (ms). Used to synthesise daily candles, since
+// Tradejini's chart API has no native daily endpoint.
+static QVector<BrokerCandle> tj_aggregate_to_daily(const QVector<BrokerCandle>& bars) {
+ QVector<BrokerCandle> out;
+ constexpr qint64 kIstOffsetSecs = 19800; // +5:30
+ qint64 cur_day = 0;
+ bool started = false;
+ for (const auto& b : bars) {
+ const qint64 day = (b.timestamp / 1000 + kIstOffsetSecs) / 86400;
+ if (!started || day != cur_day) {
+ BrokerCandle d = b;
+ // Stamp the daily bar at IST midnight, expressed back as UTC ms.
+ d.timestamp = (day * 86400 - kIstOffsetSecs) * 1000LL;
+ out.append(d);
+ cur_day = day;
+ started = true;
+ } else {
+ BrokerCandle& d = out.last();
+ d.high = std::max(d.high, b.high);
+ d.low = std::min(d.low, b.low);
+ d.close = b.close; // last bar of the day
+ d.volume += b.volume; // summed
+ d.oi = b.oi; // last
+ }
+ }
+ return out;
+}
+
// ---------- get_history ----------
// GET /api/mkt-data/chart/interval-data?id=<symId>&interval=<min>&from=<sec>&to=<sec>
+// Native intervals are minutes (1/5/15/30). Daily ("D") is synthesised by
+// fetching 1-minute bars and aggregating client-side — note Tradejini retains
+// only ~30 days of 1-minute history, so synthesised daily history is limited.
ApiResponse<QVector<BrokerCandle>> TradejiniBroker::get_history(const BrokerCredentials& creds, const QString& symbol,
const QString& resolution, const QString& from_date,
@@ -478,14 +510,22 @@ ApiResponse<QVector<BrokerCandle>> TradejiniBroker::get_history(const BrokerCred
int64_t from_epoch = QDateTime(from, QTime(9, 15, 0)).toSecsSinceEpoch();
int64_t to_epoch = QDateTime(to, QTime(23, 59, 59)).toSecsSinceEpoch();
- // Tradejini intervals are integer minutes; daily is unsupported via this endpoint.
+ // Native intervals are integer minutes. Daily ("D"/"1D"/"DAY") has no native
+ // endpoint, so fetch 1-minute bars and aggregate to daily after collection.
static const QMap<QString, QString> interval_map = {
{"1", "1"}, {"5", "5"}, {"15", "15"}, {"30", "30"},
};
- if (!interval_map.contains(resolution))
+ const QString res_upper = resolution.toUpper();
+ const bool want_daily = (res_upper == "D" || res_upper == "1D" || res_upper == "DAY");
+ QString interval;
+ if (want_daily)
+ interval = "1"; // fetch minute bars, roll up below
+ else if (interval_map.contains(resolution))
+ interval = interval_map.value(resolution);
+ else
return {false, std::nullopt,
- QString("Tradejini chart supports only minute intervals (1,5,30); resolution '%1' (e.g. daily) is not supported by this endpoint").arg(resolution), ts};
- QString interval = interval_map.value(resolution);
+ QString("Tradejini chart supports minute intervals (1,5,15,30) and synthesised daily (D); "
+ "resolution '%1' is not supported").arg(resolution), ts};
auto& http = BrokerHttp::instance();
@@ -623,6 +663,10 @@ ApiResponse<QVector<BrokerCandle>> TradejiniBroker::get_history(const BrokerCred
}),
candles.end());
+ // Synthesise daily candles from the collected 1-minute bars when requested.
+ if (want_daily)
+ candles = tj_aggregate_to_daily(candles);
+
return {true, candles, "", ts};
}
diff --git a/fincept-qt/src/trading/instruments/DhanInstrumentParser.cpp b/fincept-qt/src/trading/instruments/DhanInstrumentParser.cpp
index 5de7f1367..cf3b9beb6 100644
--- a/fincept-qt/src/trading/instruments/DhanInstrumentParser.cpp
+++ b/fincept-qt/src/trading/instruments/DhanInstrumentParser.cpp
@@ -1,5 +1,7 @@
#include "trading/instruments/DhanInstrumentParser.h"
+#include "trading/instruments/InstrumentNormalize.h"
+
#include "core/logging/Logger.h"
#include <QDate>
@@ -51,11 +53,10 @@ InstrumentType map_dhan_type(const QString& instrument_name, const QString& opti
QString DhanInstrumentParser::map_index_name(const QString& trading_symbol) {
const QString up = trading_symbol.toUpper();
- auto it = dhan_index_map().constFind(up);
- if (it != dhan_index_map().constEnd())
- return it.value();
- // Unmapped index: strip spaces (e.g. "NIFTY MIDCAP 150" → "NIFTYMIDCAP150").
- return QString(up).remove(' ');
+ // Broker map first (handles Dhan's spaced names), then the shared normalizer
+ // as the final authority so the canonical index name matches every broker.
+ const QString mapped = dhan_index_map().value(up, QString(up).remove(' '));
+ return norm::normalise_index_symbol(mapped);
}
// "2024-08-28 14:30:00" (or "2024-08-28") → "28AUG24"
@@ -95,11 +96,7 @@ QString DhanInstrumentParser::normalise_symbol(const QString& trading_symbol, co
}
if (itype == "CE" || itype == "PE") {
if (!underlying.isEmpty() && !expiry_nd.isEmpty()) {
- QString strike_str;
- if (strike == static_cast<qint64>(strike))
- strike_str = QString::number(static_cast<qint64>(strike));
- else
- strike_str = QString::number(strike, 'f', 2);
+ QString strike_str = norm::format_strike(strike);
return map_index_name(underlying) + expiry_nd + strike_str + itype;
}
return trading_symbol.toUpper();
diff --git a/fincept-qt/src/trading/instruments/FyersInstrumentParser.cpp b/fincept-qt/src/trading/instruments/FyersInstrumentParser.cpp
index 9effc9c69..3175b9b30 100644
--- a/fincept-qt/src/trading/instruments/FyersInstrumentParser.cpp
+++ b/fincept-qt/src/trading/instruments/FyersInstrumentParser.cpp
@@ -1,5 +1,7 @@
#include "trading/instruments/FyersInstrumentParser.h"
+#include "trading/instruments/InstrumentNormalize.h"
+
#include "core/logging/Logger.h"
#include <QDateTime>
@@ -102,8 +104,7 @@ QVector<Instrument> FyersInstrumentParser::parse(const QByteArray& json_data) {
// CE/PE: NIFTY + 26MAY26 + 24000 + CE
QString exp_compact = inst.expiry;
exp_compact.remove('-');
- int strike_int = static_cast<int>(inst.strike);
- inst.symbol = inst.name + exp_compact + QString::number(strike_int) +
+ inst.symbol = inst.name + exp_compact + norm::format_strike(inst.strike) +
instrument_type_str(inst.instrument_type);
}
diff --git a/fincept-qt/src/trading/instruments/GrowwInstrumentParser.cpp b/fincept-qt/src/trading/instruments/GrowwInstrumentParser.cpp
index deb69665b..5548e7bbe 100644
--- a/fincept-qt/src/trading/instruments/GrowwInstrumentParser.cpp
+++ b/fincept-qt/src/trading/instruments/GrowwInstrumentParser.cpp
@@ -1,5 +1,7 @@
#include "trading/instruments/GrowwInstrumentParser.h"
+#include "trading/instruments/InstrumentNormalize.h"
+
#include "core/logging/Logger.h"
#include <QDate>
@@ -63,7 +65,8 @@ QString GrowwInstrumentParser::expiry_nodashes(const QString& expiry_iso) {
}
QString GrowwInstrumentParser::map_index_name(const QString& trading_symbol) {
- return groww_index_map().value(trading_symbol.toUpper(), trading_symbol.toUpper());
+ // Broker map first, then the shared normalizer so index naming matches every broker.
+ return norm::normalise_index_symbol(groww_index_map().value(trading_symbol.toUpper(), trading_symbol.toUpper()));
}
// Groww exchange column is NSE/BSE/MCX even for derivatives; segment distinguishes
@@ -101,12 +104,8 @@ QString GrowwInstrumentParser::normalise_symbol(const QString& trading_symbol, c
}
if (itype == "CE" || itype == "PE") {
if (!underlying.isEmpty() && !expiry_nd.isEmpty()) {
- // Drop decimals for whole-number strikes; keep decimals otherwise (e.g. silver)
- QString strike_str;
- if (strike == static_cast<qint64>(strike))
- strike_str = QString::number(static_cast<qint64>(strike));
- else
- strike_str = QString::number(strike, 'f', 2);
+ // Shared strike formatting — identical across all brokers.
+ QString strike_str = norm::format_strike(strike);
return underlying.toUpper() + expiry_nd + strike_str + itype;
}
return trading_symbol;
diff --git a/fincept-qt/src/trading/instruments/IciciInstrumentParser.cpp b/fincept-qt/src/trading/instruments/IciciInstrumentParser.cpp
new file mode 100644
index 000000000..e5410563e
--- /dev/null
+++ b/fincept-qt/src/trading/instruments/IciciInstrumentParser.cpp
@@ -0,0 +1,180 @@
+#include "trading/instruments/IciciInstrumentParser.h"
+
+#include "trading/instruments/InstrumentNormalize.h"
+
+#include "core/logging/Logger.h"
+
+#include <QString>
+#include <QTextStream>
+
+namespace fincept::trading {
+namespace {
+
+// Format a strike for use inside a normalised option symbol: drop the decimal
+// when it is a whole number ("22750"), keep two places otherwise ("22750.50").
+// Uniquely named so it cannot collide with the other parsers' helpers when the
+// instrument parsers are concatenated under a unity build.
+QString icici_strike_str(double strike) {
+ // Shared strike formatting — identical across every broker.
+ return norm::format_strike(strike);
+}
+
+// "30-Mar-2026" → {dd:"30", mon:"MAR", yy:"26"}. ICICI always ships the
+// "DD-Mon-YYYY" form, so a split on '-' is both correct and locale-independent
+// (avoids QDate's locale-sensitive MMM parsing).
+struct IciciExpiry {
+ QString display; // "30-MAR-2026"
+ QString ddmmmyy; // "30MAR26"
+ bool valid = false;
+};
+
+IciciExpiry icici_parse_expiry(const QString& raw) {
+ IciciExpiry e;
+ const QStringList p = raw.split('-');
+ if (p.size() != 3)
+ return e;
+ const QString dd = p[0].trimmed();
+ const QString mon = p[1].trimmed().toUpper();
+ const QString yyyy = p[2].trimmed();
+ if (dd.isEmpty() || mon.isEmpty() || yyyy.size() < 2)
+ return e;
+ e.display = dd + "-" + mon + "-" + yyyy;
+ e.ddmmmyy = dd + mon + yyyy.right(2);
+ e.valid = true;
+ return e;
+}
+
+} // namespace
+
+Instrument IciciInstrumentParser::parse_row(const QStringList& cols) {
+ const int n = cols.size();
+ if (n < 13)
+ return {};
+
+ // The only free-text field is SN (the company name, col 1), which could in
+ // theory contain a comma in this unquoted CSV. Anchor the structured fields:
+ // SC from the front, everything else from the end so a comma in the name
+ // never shifts the columns we rely on.
+ const QString sc = cols[0].trimmed(); // ICICI stock code
+ const QString ec = cols[n - 11].trimmed(); // exchange (NSE/BSE/NFO/BFO/MCX)
+ const QString sm = cols[n - 10].trimmed(); // short mnemonic / contract encoding
+ const QString sg = cols[n - 9].trimmed(); // segment
+ const QString tk = cols[n - 8].trimmed(); // numeric token
+ const QString ls = cols[n - 7].trimmed(); // lot size
+ const QString ns = cols[n - 5].trimmed(); // exchange ticker symbol
+ const QString ts = cols[n - 4].trimmed(); // tick size
+
+ if (sc.isEmpty() || ec.isEmpty())
+ return {};
+
+ Instrument inst;
+ inst.broker_id = QStringLiteral("icicidirect");
+ inst.brexchange = ec.toUpper();
+ inst.exchange = ec.toUpper();
+
+ bool token_ok = false;
+ const qint64 token = tk.toLongLong(&token_ok);
+ inst.instrument_token = token_ok ? token : 0;
+ inst.exchange_token = inst.instrument_token;
+
+ const double lot = ls.toDouble();
+ inst.lot_size = lot > 0 ? static_cast<int>(lot) : 1;
+ const double tick = ts.toDouble();
+ inst.tick_size = tick > 0 ? tick : 0.05;
+
+ const QString underlying_ticker = ns.isEmpty() ? sc.toUpper() : ns.toUpper();
+
+ // Derivatives encode the contract in SM as "<UNDER>~F:…" or "<UNDER>~O:…".
+ // Equities have no '~'.
+ const int tilde = sm.indexOf('~');
+ const bool is_derivative = tilde >= 0 && (sg.compare("EQUITY", Qt::CaseInsensitive) != 0);
+
+ if (!is_derivative) {
+ // Cash equity / ETF.
+ inst.instrument_type = InstrumentType::EQ;
+ inst.brsymbol = sc;
+ inst.symbol = underlying_ticker;
+ inst.name = underlying_ticker;
+ return inst;
+ }
+
+ // Derivative: decode the part after '~'. "F:DD-Mon-YYYY" or
+ // "O:DD-Mon-YYYY:CE|PE:<strike×100>".
+ const QString rest = sm.mid(tilde + 1);
+ // brsymbol carries the underlying ICICI code — Breeze's `stock_code` on F&O
+ // orders — with expiry/strike/right supplied separately from these fields.
+ inst.brsymbol = sc;
+ inst.name = underlying_ticker;
+
+ if (rest.startsWith("F:")) {
+ const IciciExpiry exp = icici_parse_expiry(rest.mid(2));
+ if (!exp.valid)
+ return {};
+ inst.instrument_type = InstrumentType::FUT;
+ inst.expiry = exp.display;
+ inst.strike = 0.0;
+ inst.symbol = underlying_ticker + exp.ddmmmyy + "FUT";
+ return inst;
+ }
+
+ if (rest.startsWith("O:")) {
+ const QStringList parts = rest.mid(2).split(':'); // [expiry, CE|PE, strike×100]
+ if (parts.size() < 3)
+ return {};
+ const IciciExpiry exp = icici_parse_expiry(parts[0]);
+ if (!exp.valid)
+ return {};
+ const QString right = parts[1].trimmed().toUpper();
+ const double strike = parts[2].trimmed().toDouble() / 100.0;
+ inst.instrument_type = (right == "CE") ? InstrumentType::CE
+ : (right == "PE") ? InstrumentType::PE
+ : InstrumentType::UNKNOWN;
+ if (inst.instrument_type == InstrumentType::UNKNOWN)
+ return {};
+ inst.expiry = exp.display;
+ inst.strike = strike;
+ inst.symbol = underlying_ticker + exp.ddmmmyy + icici_strike_str(strike) + right;
+ return inst;
+ }
+
+ return {};
+}
+
+QVector<Instrument> IciciInstrumentParser::parse(const QByteArray& csv_data) {
+ QVector<Instrument> results;
+ if (csv_data.isEmpty()) {
+ LOG_WARN("IciciParser", "Empty CSV data received");
+ return results;
+ }
+
+ QTextStream stream(csv_data);
+ const QString header = stream.readLine();
+ Q_UNUSED(header)
+
+ int skipped = 0;
+ results.reserve(35000); // ICICI ships ~33k rows (equity + F&O + commodity)
+ while (!stream.atEnd()) {
+ const QString line = stream.readLine();
+ if (line.isEmpty())
+ continue;
+
+ const QStringList cols = line.split(',');
+ if (cols.size() < 13) {
+ ++skipped;
+ continue;
+ }
+
+ Instrument inst = parse_row(cols);
+ if (inst.symbol.isEmpty() || inst.exchange.isEmpty() || inst.brsymbol.isEmpty()) {
+ ++skipped;
+ continue;
+ }
+ results.append(inst);
+ }
+
+ LOG_INFO("IciciParser",
+ QString("Parsed %1 instruments (skipped %2 malformed rows)").arg(results.size()).arg(skipped));
+ return results;
+}
+
+} // namespace fincept::trading
diff --git a/fincept-qt/src/trading/instruments/IciciInstrumentParser.h b/fincept-qt/src/trading/instruments/IciciInstrumentParser.h
new file mode 100644
index 000000000..177ee051b
--- /dev/null
+++ b/fincept-qt/src/trading/instruments/IciciInstrumentParser.h
@@ -0,0 +1,49 @@
+#pragma once
+#include "trading/instruments/InstrumentTypes.h"
+
+#include <QByteArray>
+#include <QStringList>
+#include <QVector>
+
+namespace fincept::trading {
+
+/// Parses ICICI Direct's StockScriptNew.csv (from
+/// https://traderweb.icicidirect.com/Content/File/txtFile/ScripFile/StockScriptNew.csv)
+/// into normalised Instrument rows. This single, unzipped CSV is the full ICICI
+/// security master — equity, F&O, and commodity across NSE/BSE/NFO/BFO/MCX —
+/// which lets us avoid the SecurityMaster.zip (and a Qt private-header unzip dep).
+///
+/// CSV columns (13 fields, header "SC,SN,EC,SM,SG,TK,LS,CD,NS,TS,ISIN,SR,SI"):
+/// 0: SC — ICICI stock code (e.g. "ICIBAN", "NIFTY") → brsymbol
+/// 1: SN — security / company name (free text; may rarely contain commas)
+/// 2: EC — exchange (NSE/BSE/NFO/BFO/MCX)
+/// 3: SM — short mnemonic. EQ: == SC. Derivative encodes the contract:
+/// "<UNDER>~F:DD-Mon-YYYY" (future)
+/// "<UNDER>~O:DD-Mon-YYYY:CE|PE:<strike×100>" (option)
+/// 4: SG — segment (EQUITY/DERIVATIVE/COMMODITY)
+/// 5: TK — ICICI numeric token → instrument_token / exchange_token
+/// 6: LS — lot size
+/// 7: CD — descriptive code (FUT-… / OPT-…; unused, we decode SM instead)
+/// 8: NS — exchange ticker symbol (e.g. "ICICIBANK", "NIFTY") → symbol
+/// 9: TS — tick size
+/// 10: ISIN 11: SR (series) 12: SI (alt scrip id)
+///
+/// Normalisation mirrors the other parsers so cross-broker lookups behave
+/// identically:
+/// EQ : symbol = NS (exchange ticker), brsymbol = SC (ICICI code)
+/// FUT : symbol = underlying + DDMMMYY + "FUT"
+/// CE/PE : symbol = underlying + DDMMMYY + strike + CE/PE
+/// For derivatives brsymbol carries the *underlying* ICICI code (SC) — that is
+/// the `stock_code` Breeze wants on F&O orders, with expiry/strike/right passed
+/// separately (the broker reads them from the Instrument's fields).
+class IciciInstrumentParser {
+ public:
+ /// Parse raw CSV bytes downloaded from the StockScriptNew.csv URL.
+ /// Returns empty vector on parse failure (logged internally).
+ static QVector<Instrument> parse(const QByteArray& csv_data);
+
+ private:
+ static Instrument parse_row(const QStringList& cols);
+};
+
+} // namespace fincept::trading
diff --git a/fincept-qt/src/trading/instruments/InstrumentDecompress.cpp b/fincept-qt/src/trading/instruments/InstrumentDecompress.cpp
new file mode 100644
index 000000000..74453ac43
--- /dev/null
+++ b/fincept-qt/src/trading/instruments/InstrumentDecompress.cpp
@@ -0,0 +1,107 @@
+#include "trading/instruments/InstrumentDecompress.h"
+
+#include "core/logging/Logger.h"
+
+#include <zlib.h>
+
+#include <cstring>
+
+namespace fincept::trading::decompress {
+
+namespace {
+
+// Inflate `in` using the given window-bits setting. 15|16 → gzip, -15 → raw deflate.
+QByteArray inflate_stream(const QByteArray& in, int window_bits) {
+ if (in.isEmpty())
+ return {};
+
+ z_stream s;
+ std::memset(&s, 0, sizeof(s));
+ if (inflateInit2(&s, window_bits) != Z_OK)
+ return {};
+
+ s.next_in = reinterpret_cast<Bytef*>(const_cast<char*>(in.constData()));
+ s.avail_in = static_cast<uInt>(in.size());
+
+ QByteArray out;
+ char chunk[32768];
+ int rc = Z_OK;
+ do {
+ s.next_out = reinterpret_cast<Bytef*>(chunk);
+ s.avail_out = sizeof(chunk);
+ rc = inflate(&s, Z_NO_FLUSH);
+ if (rc != Z_OK && rc != Z_STREAM_END && rc != Z_BUF_ERROR) {
+ inflateEnd(&s);
+ return {};
+ }
+ const int produced = static_cast<int>(sizeof(chunk) - s.avail_out);
+ if (produced > 0)
+ out.append(chunk, produced);
+ // Z_BUF_ERROR with no progress and no input left → done.
+ if (rc == Z_BUF_ERROR && s.avail_in == 0 && produced == 0)
+ break;
+ } while (rc != Z_STREAM_END);
+
+ inflateEnd(&s);
+ return out;
+}
+
+quint16 le16(const QByteArray& b, int off) {
+ return static_cast<quint16>(static_cast<unsigned char>(b[off])) |
+ (static_cast<quint16>(static_cast<unsigned char>(b[off + 1])) << 8);
+}
+
+quint32 le32(const QByteArray& b, int off) {
+ return static_cast<quint32>(static_cast<unsigned char>(b[off])) |
+ (static_cast<quint32>(static_cast<unsigned char>(b[off + 1])) << 8) |
+ (static_cast<quint32>(static_cast<unsigned char>(b[off + 2])) << 16) |
+ (static_cast<quint32>(static_cast<unsigned char>(b[off + 3])) << 24);
+}
+
+} // namespace
+
+QByteArray gunzip(const QByteArray& gz) {
+ QByteArray out = inflate_stream(gz, 15 + 16);
+ if (out.isEmpty())
+ LOG_WARN("InstrumentDecompress", "gunzip produced no output");
+ return out;
+}
+
+QByteArray unzip_first_entry(const QByteArray& zip) {
+ // Local file header: "PK\x03\x04", then at fixed offsets:
+ // 8 compression method (u16) 18 compressed size (u32)
+ // 26 file name length (u16) 28 extra field length (u16)
+ // 30 + nameLen + extraLen → start of compressed data.
+ if (zip.size() < 30 || !zip.startsWith("PK\x03\x04")) {
+ LOG_WARN("InstrumentDecompress", "not a zip (bad local header signature)");
+ return {};
+ }
+ const quint16 method = le16(zip, 8);
+ const quint16 flags = le16(zip, 6);
+ quint32 comp_size = le32(zip, 18);
+ const quint16 name_len = le16(zip, 26);
+ const quint16 extra_len = le16(zip, 28);
+ const int data_off = 30 + name_len + extra_len;
+ if (data_off > zip.size()) {
+ LOG_WARN("InstrumentDecompress", "zip data offset past end");
+ return {};
+ }
+
+ // When a data descriptor is used (bit 3), the local header size may be 0;
+ // hand the rest of the buffer to the inflater and let Z_STREAM_END stop it.
+ if (comp_size == 0 || (flags & 0x08))
+ comp_size = static_cast<quint32>(zip.size() - data_off);
+ if (data_off + static_cast<int>(comp_size) > zip.size())
+ comp_size = static_cast<quint32>(zip.size() - data_off);
+
+ const QByteArray payload = zip.mid(data_off, static_cast<int>(comp_size));
+ if (method == 0) // stored
+ return payload;
+ if (method == 8) // deflate
+ return inflate_stream(payload, -15);
+
+ LOG_WARN("InstrumentDecompress", QString("unsupported zip method %1").arg(method));
+ return {};
+}
+
+} // namespace fincept::trading::decompress
diff --git a/fincept-qt/src/trading/instruments/InstrumentDecompress.h b/fincept-qt/src/trading/instruments/InstrumentDecompress.h
new file mode 100644
index 000000000..dfe06806d
--- /dev/null
+++ b/fincept-qt/src/trading/instruments/InstrumentDecompress.h
@@ -0,0 +1,19 @@
+#pragma once
+// InstrumentDecompress — minimal zlib-backed decompression for instrument masters.
+// Upstox ships gzip JSON; Shoonya ships per-exchange .txt.zip (single entry).
+// Qt's qUncompress only handles its own length-prefixed zlib stream, so we use
+// zlib directly.
+
+#include <QByteArray>
+
+namespace fincept::trading::decompress {
+
+/// Inflate a gzip stream (RFC 1952). Returns {} on error/empty.
+QByteArray gunzip(const QByteArray& gz);
+
+/// Extract the FIRST entry of a ZIP archive (sufficient for Noren symbol zips
+/// which contain a single "<EX>_symbols.txt"). Supports stored (method 0) and
+/// deflate (method 8). Returns {} on error/empty.
+QByteArray unzip_first_entry(const QByteArray& zip);
+
+} // namespace fincept::trading::decompress
diff --git a/fincept-qt/src/trading/instruments/InstrumentDownload.cpp b/fincept-qt/src/trading/instruments/InstrumentDownload.cpp
new file mode 100644
index 000000000..64d6f256e
--- /dev/null
+++ b/fincept-qt/src/trading/instruments/InstrumentDownload.cpp
@@ -0,0 +1,81 @@
+#include "trading/instruments/InstrumentDownload.h"
+
+#include "core/logging/Logger.h"
+
+#include <QCoreApplication>
+#include <QEvent>
+#include <QEventLoop>
+#include <QNetworkAccessManager>
+#include <QNetworkReply>
+#include <QNetworkRequest>
+#include <QTimer>
+#include <QUrl>
+
+namespace fincept::trading {
+
+namespace {
+
+// Run one request to completion on a private QNAM and return the raw body.
+QByteArray run_request(const QString& method, const QString& url, const QByteArray& body,
+ const QString& content_type, const QMap<QString, QString>& headers, int timeout_ms) {
+ auto* nam = new QNetworkAccessManager;
+ QNetworkRequest req{QUrl(url)};
+ req.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy);
+ for (auto it = headers.constBegin(); it != headers.constEnd(); ++it)
+ req.setRawHeader(it.key().toUtf8(), it.value().toUtf8());
+
+ QNetworkReply* reply = nullptr;
+ if (method == "POST") {
+ if (!content_type.isEmpty())
+ req.setHeader(QNetworkRequest::ContentTypeHeader, content_type);
+ reply = nam->post(req, body);
+ } else {
+ reply = nam->get(req);
+ }
+
+ QEventLoop loop;
+ QTimer timer;
+ timer.setSingleShot(true);
+ QObject::connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
+ QObject::connect(&timer, &QTimer::timeout, &loop, &QEventLoop::quit);
+ timer.start(timeout_ms);
+ loop.exec();
+
+ auto drain = [&]() {
+ reply->deleteLater();
+ nam->deleteLater();
+ QCoreApplication::sendPostedEvents(nullptr, QEvent::DeferredDelete);
+ };
+
+ if (!timer.isActive()) {
+ reply->abort();
+ LOG_ERROR("InstrumentDownload", QString("Timeout fetching %1").arg(url));
+ drain();
+ return {};
+ }
+ timer.stop();
+
+ if (reply->error() != QNetworkReply::NoError) {
+ LOG_ERROR("InstrumentDownload", QString("Failed %1: %2").arg(url, reply->errorString()));
+ drain();
+ return {};
+ }
+
+ QByteArray data = reply->readAll();
+ drain();
+ LOG_INFO("InstrumentDownload", QString("Fetched %1 (%2 bytes)").arg(url).arg(data.size()));
+ return data;
+}
+
+} // namespace
+
+QByteArray http_get_blocking(const QString& url, const QMap<QString, QString>& headers, int timeout_ms) {
+ return run_request("GET", url, {}, {}, headers, timeout_ms);
+}
+
+QByteArray http_post_blocking(const QString& url, const QByteArray& body, const QString& content_type,
+ const QMap<QString, QString>& headers, int timeout_ms) {
+ return run_request("POST", url, body, content_type, headers, timeout_ms);
+}
+
+} // namespace fincept::trading
diff --git a/fincept-qt/src/trading/instruments/InstrumentDownload.h b/fincept-qt/src/trading/instruments/InstrumentDownload.h
new file mode 100644
index 000000000..5f9a1154a
--- /dev/null
+++ b/fincept-qt/src/trading/instruments/InstrumentDownload.h
@@ -0,0 +1,26 @@
+#pragma once
+// InstrumentDownload — blocking HTTP helpers for instrument-master downloads.
+//
+// Master files are large (5–30 MB) and fetched on the InstrumentService worker
+// thread. We use a dedicated QNetworkAccessManager per call (heap-allocated with
+// a DeferredDelete drain) rather than the shared BrokerHttp client, so a slow
+// multi-second download does not hold BrokerHttp's mutex and starve concurrent
+// quote/order calls. Mirrors the pattern in download_angel_master_json().
+
+#include <QByteArray>
+#include <QMap>
+#include <QString>
+
+namespace fincept::trading {
+
+/// Blocking GET. Returns the raw body, or {} on error/timeout. `timeout_ms`
+/// defaults high because masters are large.
+QByteArray http_get_blocking(const QString& url, const QMap<QString, QString>& headers = {},
+ int timeout_ms = 60000);
+
+/// Blocking POST with a raw body + content type (used by XTS instrument master
+/// and login). Returns the raw body, or {} on error/timeout.
+QByteArray http_post_blocking(const QString& url, const QByteArray& body, const QString& content_type,
+ const QMap<QString, QString>& headers = {}, int timeout_ms = 60000);
+
+} // namespace fincept::trading
diff --git a/fincept-qt/src/trading/instruments/InstrumentNormalize.cpp b/fincept-qt/src/trading/instruments/InstrumentNormalize.cpp
new file mode 100644
index 000000000..961b737d5
--- /dev/null
+++ b/fincept-qt/src/trading/instruments/InstrumentNormalize.cpp
@@ -0,0 +1,205 @@
+#include "trading/instruments/InstrumentNormalize.h"
+
+#include <QDate>
+#include <QDateTime>
+#include <QHash>
+#include <QRegularExpression>
+
+namespace fincept::trading::norm {
+
+namespace {
+
+// Spaced-name index map (broker tradingsymbol/name → canonical). Mirrors
+// OpenAlgo's index_mapping dict and the existing Zerodha parser. Comprehensive
+// so index naming is uniform across every broker.
+const QHash<QString, QString>& spaced_index_map() {
+ static const QHash<QString, QString> m = {
+ {"NIFTY 50", "NIFTY"},
+ {"NIFTY BANK", "BANKNIFTY"},
+ {"NIFTY FIN SERVICE", "FINNIFTY"},
+ {"NIFTY MID SELECT", "MIDCPNIFTY"},
+ {"NIFTY MIDCAP SELECT", "MIDCPNIFTY"},
+ {"NIFTY NEXT 50", "NIFTYNXT50"},
+ {"INDIA VIX", "INDIAVIX"},
+ {"NIFTY100 LIQ 15", "NIFTY100LIQ15"},
+ {"NIFTY MIDCAP 50", "NIFTYMIDCAP50"},
+ {"NIFTY MIDCAP 100", "NIFTYMIDCAP100"},
+ {"NIFTY SMALLCAP 50", "NIFTYSMALLCAP50"},
+ {"NIFTY SMALLCAP 100", "NIFTYSMALLCAP100"},
+ {"NIFTY 100", "NIFTY100"},
+ {"NIFTY 200", "NIFTY200"},
+ {"NIFTY 500", "NIFTY500"},
+ {"NIFTY AUTO", "NIFTYAUTO"},
+ {"NIFTY ENERGY", "NIFTYENERGY"},
+ {"NIFTY FMCG", "NIFTYFMCG"},
+ {"NIFTY IT", "NIFTYIT"},
+ {"NIFTY MEDIA", "NIFTYMEDIA"},
+ {"NIFTY METAL", "NIFTYMETAL"},
+ {"NIFTY PHARMA", "NIFTYPHARMA"},
+ {"NIFTY PSU BANK", "NIFTYPSUBANK"},
+ {"NIFTY REALTY", "NIFTYREALTY"},
+ {"NIFTY INFRA", "NIFTYINFRA"},
+ {"NIFTY SERV SECTOR", "NIFTYSERVSECTOR"},
+ {"NIFTY COMMODITIES", "NIFTYCOMMODITIES"},
+ {"NIFTY CONSUMPTION", "NIFTYCONSUMPTION"},
+ {"NIFTY CPSE", "NIFTYCPSE"},
+ {"NIFTY GROWSECT 15", "NIFTYGROWSECT15"},
+ {"NIFTY100 QUALTY30", "NIFTY100QUALTY30"},
+ {"NIFTY50 VALUE 20", "NIFTY50VALUE20"},
+ {"NIFTY ALPHA 50", "NIFTYALPHA50"},
+ {"NIFTY ALPHA LOW-VOL", "NIFTYALPHALOWVOL"},
+ {"NIFTY200 QUALTY30", "NIFTY200QUALTY30"},
+ // BSE indices
+ {"SENSEX", "SENSEX"},
+ {"BSE SENSEX", "SENSEX"},
+ {"SENSEX 50", "SENSEX50"},
+ {"BANKEX", "BANKEX"},
+ {"BSE BANKEX", "BANKEX"},
+ };
+ return m;
+}
+
+// Pre-stripped index map (spaces/hyphens already removed, upper-cased).
+const QHash<QString, QString>& stripped_index_map() {
+ static const QHash<QString, QString> m = {
+ {"NIFTY50", "NIFTY"},
+ {"NIFTYBANK", "BANKNIFTY"},
+ {"NIFTYFINSERVICE", "FINNIFTY"},
+ {"NIFTYNEXT50", "NIFTYNXT50"},
+ {"NIFTYMIDSELECT", "MIDCPNIFTY"},
+ {"NIFTYMIDCAPSELECT", "MIDCPNIFTY"},
+ {"SNSX50", "SENSEX50"},
+ {"INDIAVIX", "INDIAVIX"},
+ {"BSESENSEX", "SENSEX"},
+ {"BSEBANKEX", "BANKEX"},
+ {"NIFTYMIDCAPSELECT", "MIDCPNIFTY"},
+ {"NIFTYMCAP50", "NIFTYMIDCAP50"},
+ };
+ return m;
+}
+
+} // namespace
+
+QString expiry_to_nodash(const QString& raw) {
+ const QString s = raw.trimmed();
+ if (s.isEmpty())
+ return {};
+
+ // Try the most specific / common formats first. Upper-case so month names match.
+ const QString up = s.toUpper();
+ static const char* fmts[] = {"yyyy-MM-dd", "ddMMMyyyy", "dd-MMM-yyyy", "dd-MMM-yy",
+ "ddMMMyy", "dd/MM/yyyy", "dd/MM/yy"};
+ for (const char* f : fmts) {
+ QDate d = QDate::fromString(up, QString::fromLatin1(f));
+ if (d.isValid())
+ return d.toString("ddMMMyy").toUpper();
+ }
+ // Datetime forms like "2026-06-30 14:00:00".
+ QDateTime dt = QDateTime::fromString(s, "yyyy-MM-dd HH:mm:ss");
+ if (dt.isValid())
+ return dt.date().toString("ddMMMyy").toUpper();
+ // ISO-ish fallback.
+ QDate d = QDate::fromString(s.left(10), "yyyy-MM-dd");
+ if (d.isValid())
+ return d.toString("ddMMMyy").toUpper();
+ return {};
+}
+
+QString nodash_to_display(const QString& nd) {
+ if (nd.size() != 7)
+ return {};
+ return nd.left(2) + "-" + nd.mid(2, 3) + "-" + nd.right(2);
+}
+
+QString expiry_display(const QString& raw) {
+ return nodash_to_display(expiry_to_nodash(raw));
+}
+
+QString format_strike(double strike) {
+ // Whole number → no decimal. e.g. 25000.0 → "25000".
+ if (qFuzzyCompare(strike, static_cast<double>(qRound64(strike))))
+ return QString::number(qRound64(strike));
+ // Fractional → trim trailing zeros (and a dangling '.').
+ QString s = QString::number(strike, 'f', 4);
+ while (s.endsWith('0'))
+ s.chop(1);
+ if (s.endsWith('.'))
+ s.chop(1);
+ return s;
+}
+
+QString strip_eq_suffix(const QString& trading_symbol) {
+ QString s = trading_symbol.trimmed().toUpper();
+ static const QRegularExpression re("(-EQ|-BE|-MF|-SG|-SM)$");
+ s.replace(re, "");
+ return s;
+}
+
+QString normalise_index_symbol(const QString& raw_name) {
+ QString up = raw_name.trimmed().toUpper();
+ up.replace("S&P ", "");
+ // Spaced form first (preserves multi-word keys).
+ auto it = spaced_index_map().constFind(up);
+ if (it != spaced_index_map().constEnd())
+ return it.value();
+ // Strip spaces/hyphens, retry.
+ QString stripped = up;
+ stripped.remove(' ');
+ stripped.remove('-');
+ auto jt = stripped_index_map().constFind(stripped);
+ if (jt != stripped_index_map().constEnd())
+ return jt.value();
+ return stripped;
+}
+
+QString synthesize_symbol(const QString& name, InstrumentType itype, const QString& expiry_nd, double strike,
+ const QString& eq_or_index_fallback) {
+ switch (itype) {
+ case InstrumentType::FUT:
+ return name.toUpper() + expiry_nd + "FUT";
+ case InstrumentType::CE:
+ return name.toUpper() + expiry_nd + format_strike(strike) + "CE";
+ case InstrumentType::PE:
+ return name.toUpper() + expiry_nd + format_strike(strike) + "PE";
+ case InstrumentType::INDEX:
+ return normalise_index_symbol(eq_or_index_fallback);
+ case InstrumentType::EQ:
+ case InstrumentType::UNKNOWN:
+ default:
+ return strip_eq_suffix(eq_or_index_fallback);
+ }
+}
+
+QString normalise_exchange(const QString& exchange, InstrumentType itype) {
+ QString ex = exchange.trimmed().toUpper();
+ if (itype == InstrumentType::INDEX && !ex.endsWith("_INDEX"))
+ ex += "_INDEX";
+ return ex;
+}
+
+qint64 stable_token(const QString& broker_native_token) {
+ const QString s = broker_native_token.trimmed();
+ if (s.isEmpty())
+ return 0;
+ // Leading integer (e.g. Samco "758960_NSE" → 758960).
+ int i = 0;
+ while (i < s.size() && s[i].isDigit())
+ ++i;
+ if (i > 0) {
+ bool ok = false;
+ const qint64 n = QStringView(s).left(i).toLongLong(&ok);
+ if (ok && n > 0)
+ return n;
+ }
+ // 64-bit FNV-1a hash of the full key, forced positive & non-zero.
+ const QByteArray bytes = s.toUtf8();
+ quint64 h = 1469598103934665603ULL; // FNV offset basis
+ for (char c : bytes) {
+ h ^= static_cast<unsigned char>(c);
+ h *= 1099511628211ULL; // FNV prime
+ }
+ qint64 v = static_cast<qint64>(h & 0x7FFFFFFFFFFFFFFFULL);
+ return v == 0 ? 1 : v;
+}
+
+} // namespace fincept::trading::norm
diff --git a/fincept-qt/src/trading/instruments/InstrumentNormalize.h b/fincept-qt/src/trading/instruments/InstrumentNormalize.h
new file mode 100644
index 000000000..ca0999903
--- /dev/null
+++ b/fincept-qt/src/trading/instruments/InstrumentNormalize.h
@@ -0,0 +1,58 @@
+#pragma once
+// InstrumentNormalize — the single source of truth for the CANONICAL instrument
+// format shared by every broker parser ("equalize"). Every broker's master is
+// reduced to native fields, then these pure functions synthesise the identical
+// canonical `symbol` / `exchange` regardless of which broker produced the row.
+//
+// Canonical forms (mirrors OpenAlgo):
+// FUT NAME + DDMMMYY + "FUT" e.g. NIFTY28MAR24FUT
+// CE/PE NAME + DDMMMYY + STRIKE + "CE"|"PE" e.g. NIFTY28MAR2425000CE
+// EQ trading symbol, -EQ/-BE/-MF/-SG/-SM suffix stripped
+// INDEX mapped underlying name (alias map → spaces/hyphens stripped)
+// expiry stored "DD-MMM-YY" (upper); in-symbol form is "DDMMMYY".
+
+#include "trading/instruments/InstrumentTypes.h"
+
+#include <QString>
+
+namespace fincept::trading::norm {
+
+/// Parse many broker expiry formats into the compact in-symbol form "28MAR24".
+/// Accepts: "2024-03-28", "28MAR2024", "28-MAR-2026", "28/07/26", "ddMMMyy",
+/// "yyyy-MM-dd HH:mm:ss". Returns "" if unparseable/empty.
+QString expiry_to_nodash(const QString& raw);
+
+/// "28MAR24" → "28-MAR-24". Returns "" unless input is exactly 7 chars.
+QString nodash_to_display(const QString& nd);
+
+/// Convenience: raw broker expiry → display "28-MAR-24" ("" if unparseable).
+QString expiry_display(const QString& raw);
+
+/// 25000.0 → "25000"; 287.5 → "287.5"; 133.75 → "133.75". Whole numbers drop the
+/// decimal; fractional values are trimmed of trailing zeros.
+QString format_strike(double strike);
+
+/// RELIANCE-EQ / -BE / -MF / -SG / -SM → RELIANCE (case-insensitive suffix).
+QString strip_eq_suffix(const QString& trading_symbol);
+
+/// Underlying/index name → canonical ("NIFTY 50"→"NIFTY", "NIFTYBANK"→"BANKNIFTY",
+/// "SNSX50"→"SENSEX50"). Handles both spaced and pre-stripped inputs.
+QString normalise_index_symbol(const QString& raw_name);
+
+/// Build the canonical symbol. `expiry_nd` is the compact "28MAR24" form (""
+/// for EQ/INDEX). `eq_or_index_fallback` is the broker trading symbol (EQ) or
+/// raw index name (INDEX) used when no synthesis applies.
+QString synthesize_symbol(const QString& name, InstrumentType itype, const QString& expiry_nd, double strike,
+ const QString& eq_or_index_fallback);
+
+/// Canonical exchange. Brokers pass an already-broker-mapped exchange (NSE/BSE/
+/// NFO/BFO/CDS/BCD/MCX). For INDEX types the "_INDEX" suffix is ensured.
+QString normalise_exchange(const QString& exchange, InstrumentType itype);
+
+/// Stable numeric token for brokers whose native token is non-numeric (Upstox
+/// "NSE_EQ|INE...", Samco "758960_NSE"). Uses the leading integer when present,
+/// else a positive 63-bit FNV-1a hash of the full key. Guarantees a non-zero,
+/// per-key-distinct value so UNIQUE(instrument_token, broker_id) never collapses.
+qint64 stable_token(const QString& broker_native_token);
+
+} // namespace fincept::trading::norm
diff --git a/fincept-qt/src/trading/instruments/InstrumentRepository.cpp b/fincept-qt/src/trading/instruments/InstrumentRepository.cpp
index d4d4e2dee..7b41d4b33 100644
--- a/fincept-qt/src/trading/instruments/InstrumentRepository.cpp
+++ b/fincept-qt/src/trading/instruments/InstrumentRepository.cpp
@@ -28,6 +28,7 @@ Instrument InstrumentRepository::map_row(QSqlQuery& q) {
i.instrument_type = parse_instrument_type(q.value(10).toString());
i.tick_size = q.value(11).toDouble();
i.broker_id = q.value(12).toString();
+ i.broker_token = q.value(13).toString();
return i;
}
@@ -53,8 +54,8 @@ fincept::Result<void> InstrumentRepository::replace_all(const QString& broker_id
// Bulk insert — one prepared statement, many binds
const QString sql = "INSERT OR IGNORE INTO instruments "
"(instrument_token, exchange_token, symbol, brsymbol, name, exchange, brexchange, "
- " expiry, strike, lot_size, instrument_type, tick_size, broker_id) "
- "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
+ " expiry, strike, lot_size, instrument_type, tick_size, broker_id, broker_token) "
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
for (const auto& inst : instruments) {
auto ri = exec_write(sql, {
@@ -71,6 +72,7 @@ fincept::Result<void> InstrumentRepository::replace_all(const QString& broker_id
QString(instrument_type_str(inst.instrument_type)),
inst.tick_size,
broker_id,
+ inst.broker_token,
});
if (ri.is_err()) {
db().rollback();
@@ -97,14 +99,14 @@ fincept::Result<void> InstrumentRepository::clear(const QString& broker_id) {
std::optional<Instrument> InstrumentRepository::find(const QString& symbol, const QString& exchange,
const QString& broker_id) const {
return query_optional("SELECT instrument_token, exchange_token, symbol, brsymbol, name, exchange, brexchange, "
- "expiry, strike, lot_size, instrument_type, tick_size, broker_id "
+ "expiry, strike, lot_size, instrument_type, tick_size, broker_id, broker_token "
"FROM instruments WHERE symbol = ? AND exchange = ? AND broker_id = ? LIMIT 1",
{symbol, exchange, broker_id}, map_row);
}
std::optional<Instrument> InstrumentRepository::find_by_token(qint64 instrument_token, const QString& broker_id) const {
return query_optional("SELECT instrument_token, exchange_token, symbol, brsymbol, name, exchange, brexchange, "
- "expiry, strike, lot_size, instrument_type, tick_size, broker_id "
+ "expiry, strike, lot_size, instrument_type, tick_size, broker_id, broker_token "
"FROM instruments WHERE instrument_token = ? AND broker_id = ? LIMIT 1",
{instrument_token, broker_id}, map_row);
}
@@ -112,7 +114,7 @@ std::optional<Instrument> InstrumentRepository::find_by_token(qint64 instrument_
std::optional<Instrument> InstrumentRepository::find_by_brsymbol(const QString& brsymbol, const QString& brexchange,
const QString& broker_id) const {
return query_optional("SELECT instrument_token, exchange_token, symbol, brsymbol, name, exchange, brexchange, "
- "expiry, strike, lot_size, instrument_type, tick_size, broker_id "
+ "expiry, strike, lot_size, instrument_type, tick_size, broker_id, broker_token "
"FROM instruments WHERE brsymbol = ? AND brexchange = ? AND broker_id = ? LIMIT 1",
{brsymbol, brexchange, broker_id}, map_row);
}
@@ -123,7 +125,7 @@ QVector<Instrument> InstrumentRepository::search(const QString& query, const QSt
// Exchange is stored upper-case; normalise the filter so "nse" matches. Empty = any.
const QString exch = exchange.toUpper();
QString sql = "SELECT instrument_token, exchange_token, symbol, brsymbol, name, exchange, brexchange, "
- "expiry, strike, lot_size, instrument_type, tick_size, broker_id "
+ "expiry, strike, lot_size, instrument_type, tick_size, broker_id, broker_token "
"FROM instruments "
"WHERE broker_id = ? "
"AND (exchange = ? OR ? = '') "
@@ -141,10 +143,52 @@ QVector<Instrument> InstrumentRepository::search(const QString& query, const QSt
return results;
}
+QVector<Instrument> InstrumentRepository::search_all(const QString& query, const QString& exchange,
+ const QStringList& broker_ids, int limit) const {
+ const QString pattern = "%" + query.toUpper() + "%";
+ // Exchange stored upper-case; normalise the filter. Empty = any exchange.
+ const QString exch = exchange.toUpper();
+
+ QString sql = "SELECT instrument_token, exchange_token, symbol, brsymbol, name, exchange, brexchange, "
+ "expiry, strike, lot_size, instrument_type, tick_size, broker_id, broker_token "
+ "FROM instruments "
+ "WHERE (exchange = ? OR ? = '') "
+ "AND (UPPER(symbol) LIKE ? OR UPPER(brsymbol) LIKE ? OR UPPER(name) LIKE ?) ";
+ QVariantList params = {exch, exch, pattern, pattern, pattern};
+
+ // Scope to the connected brokers. Empty list = all brokers in the catalog.
+ if (!broker_ids.isEmpty()) {
+ QStringList placeholders;
+ for (const QString& b : broker_ids) {
+ placeholders << "?";
+ params.append(b);
+ }
+ sql += "AND broker_id IN (" + placeholders.join(",") + ") ";
+ }
+
+ // Active broker (first in the list) sorts first, then by type, symbol, broker.
+ const QString active = broker_ids.isEmpty() ? QString() : broker_ids.first();
+ sql += "ORDER BY CASE WHEN broker_id = ? THEN 0 ELSE 1 END, "
+ "CASE instrument_type WHEN 'EQ' THEN 0 WHEN 'INDEX' THEN 1 WHEN 'FUT' THEN 2 ELSE 3 END, "
+ "symbol, broker_id "
+ "LIMIT ?";
+ params.append(active);
+ params.append(limit);
+
+ auto r = db().execute(sql, params);
+ if (r.is_err())
+ return {};
+ QVector<Instrument> results;
+ auto& q = r.value();
+ while (q.next())
+ results.append(map_row(q));
+ return results;
+}
+
QVector<Instrument> InstrumentRepository::list(const QString& exchange, const QString& broker_id,
InstrumentType type) const {
QString sql = "SELECT instrument_token, exchange_token, symbol, brsymbol, name, exchange, brexchange, "
- "expiry, strike, lot_size, instrument_type, tick_size, broker_id "
+ "expiry, strike, lot_size, instrument_type, tick_size, broker_id, broker_token "
"FROM instruments WHERE exchange = ? AND broker_id = ?";
QVariantList params = {exchange, broker_id};
if (type != InstrumentType::UNKNOWN) {
diff --git a/fincept-qt/src/trading/instruments/InstrumentRepository.h b/fincept-qt/src/trading/instruments/InstrumentRepository.h
index e8a1e5090..bb60ac722 100644
--- a/fincept-qt/src/trading/instruments/InstrumentRepository.h
+++ b/fincept-qt/src/trading/instruments/InstrumentRepository.h
@@ -38,6 +38,13 @@ class InstrumentRepository : public fincept::BaseRepository<Instrument> {
QVector<Instrument> search(const QString& query, const QString& exchange, const QString& broker_id,
int limit = 50) const;
+ /// Cross-broker search for the unified symbol picker. Searches the union of
+ /// `broker_ids` (empty = all brokers), one row per (broker, instrument),
+ /// with the first broker in the list sorted first. Same match semantics as
+ /// `search` (symbol/brsymbol/name LIKE).
+ QVector<Instrument> search_all(const QString& query, const QString& exchange,
+ const QStringList& broker_ids, int limit = 50) const;
+
/// All instruments for a broker+exchange (used for option chains etc.)
QVector<Instrument> list(const QString& exchange, const QString& broker_id,
InstrumentType type = InstrumentType::UNKNOWN) const;
diff --git a/fincept-qt/src/trading/instruments/InstrumentService.cpp b/fincept-qt/src/trading/instruments/InstrumentService.cpp
index e9e895fc8..84aa4f1bc 100644
--- a/fincept-qt/src/trading/instruments/InstrumentService.cpp
+++ b/fincept-qt/src/trading/instruments/InstrumentService.cpp
@@ -6,7 +6,10 @@
#include "trading/instruments/DhanInstrumentParser.h"
#include "trading/instruments/FyersInstrumentParser.h"
#include "trading/instruments/GrowwInstrumentParser.h"
+#include "trading/instruments/IciciInstrumentParser.h"
+#include "trading/instruments/InstrumentNormalize.h"
#include "trading/instruments/InstrumentRepository.h"
+#include "trading/instruments/InstrumentSources.h"
#include "trading/instruments/SymbolResolver.h"
#include "trading/instruments/ZerodhaInstrumentParser.h"
@@ -170,12 +173,13 @@ static QVector<Instrument> parse_angel_master_json(const QByteArray& json_data)
if (raw_type == "AMXIDX") {
inst.exchange = inst.brexchange + "_INDEX";
- inst.symbol = normalise_index_symbol(inst.name.isEmpty() ? inst.brsymbol : inst.name);
+ // Final pass through the shared normalizer so the index name matches every broker.
+ inst.symbol = norm::normalise_index_symbol(normalise_index_symbol(inst.name.isEmpty() ? inst.brsymbol : inst.name));
} else if (raw_type.startsWith("FUT")) {
inst.symbol = inst.name.toUpper() + exp_nd + "FUT";
} else if (raw_type.startsWith("OPT")) {
QString suffix = option_suffix(inst.brsymbol);
- QString strike_str = QString::number(static_cast<int>(inst.strike));
+ QString strike_str = norm::format_strike(inst.strike);
inst.symbol = inst.name.toUpper() + exp_nd + strike_str + suffix;
} else {
inst.symbol = normalise_spot_symbol(inst.brsymbol);
@@ -216,6 +220,11 @@ void ensure_builtin_sources_registered() {
r.register_source({QStringLiteral("dhan"),
[](const BrokerCredentials&) { return InstrumentService::download_dhan_csv(); },
[](const QByteArray& p) { return DhanInstrumentParser::parse(p); }});
+ r.register_source({QStringLiteral("icicidirect"),
+ [](const BrokerCredentials&) { return InstrumentService::download_icici_csv(); },
+ [](const QByteArray& p) { return IciciInstrumentParser::parse(p); }});
+ // The 11 additional Indian brokers (unified cross-broker search).
+ register_extra_instrument_sources();
return true;
}();
Q_UNUSED(registered);
@@ -245,6 +254,15 @@ void InstrumentService::refresh(const QString& broker_id, const BrokerCredential
.arg(broker_id)
.arg(age_hours)
.arg(max_age_hours));
+ // Instruments on disk are fresh but may not be in the in-memory
+ // cache yet (e.g. first refresh() of a relaunch within
+ // max_age_hours). Without this, is_loaded() stays false forever
+ // and every lookup fails. load_from_db() uses the shared
+ // main-thread QSqlDatabase connection; refresh() is only ever
+ // called from the UI/main thread (ChainSubTab + EquityTradingScreen
+ // callbacks), so this is safe here.
+ if (!is_loaded(broker_id))
+ load_from_db(broker_id);
return;
}
}
@@ -347,7 +365,7 @@ void InstrumentService::load_from_db_async(const QString& broker_id,
QSqlQuery q(db);
q.prepare("SELECT instrument_token, exchange_token, symbol, brsymbol, name, "
"exchange, brexchange, expiry, strike, lot_size, instrument_type, "
- "tick_size, broker_id "
+ "tick_size, broker_id, broker_token "
"FROM instruments WHERE broker_id = ?");
q.addBindValue(broker_id);
if (q.exec()) {
@@ -500,6 +518,13 @@ QVector<Instrument> InstrumentService::search(const QString& query, const QStrin
return InstrumentRepository::instance().search(query, exchange, broker_id, limit);
}
+QVector<Instrument> InstrumentService::search_all(const QString& query, const QString& exchange,
+ const QStringList& broker_ids, int limit) const {
+ // Delegate to DB — the repository handles the broker_id IN(...) scoping and
+ // active-broker-first ordering.
+ return InstrumentRepository::instance().search_all(query, exchange, broker_ids, limit);
+}
+
// ── F&O / Options chain helpers ─────────────────────────────────────────────
QStringList InstrumentService::list_underlyings(const QString& broker_id, const QString& exchange) const {
@@ -874,6 +899,57 @@ QByteArray InstrumentService::download_dhan_csv() {
return data;
}
+QByteArray InstrumentService::download_icici_csv() {
+ // Public, unauthenticated security master (~4MB plain CSV, 13 columns: equity
+ // + F&O + commodity across NSE/BSE/NFO/BFO/MCX). Deliberately the unzipped
+ // StockScriptNew.csv rather than SecurityMaster.zip so we need no ZIP decoder
+ // (Qt's QZipReader is a private-header dependency, gated on Qt6::GuiPrivate).
+ // Own QNAM (not BrokerHttp) for the same reason as download_dhan_csv: a long
+ // download must not starve concurrent quote/order calls.
+ static const QString kUrl =
+ "https://traderweb.icicidirect.com/Content/File/txtFile/ScripFile/StockScriptNew.csv";
+
+ auto* nam = new QNetworkAccessManager;
+ QNetworkRequest req{QUrl(kUrl)};
+ req.setRawHeader("Accept", "text/csv");
+ req.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy);
+
+ QNetworkReply* reply = nam->get(req);
+
+ QEventLoop loop;
+ QTimer timer;
+ timer.setSingleShot(true);
+ QObject::connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
+ QObject::connect(&timer, &QTimer::timeout, &loop, &QEventLoop::quit);
+ timer.start(60000); // 60s — ~4MB file on slow connection
+ loop.exec();
+
+ auto drain = [&]() {
+ reply->deleteLater();
+ nam->deleteLater();
+ QCoreApplication::sendPostedEvents(nullptr, QEvent::DeferredDelete);
+ };
+
+ if (!timer.isActive()) {
+ reply->abort();
+ LOG_ERROR("InstrumentService", "ICICI security master download timed out");
+ drain();
+ return {};
+ }
+ timer.stop();
+
+ if (reply->error() != QNetworkReply::NoError) {
+ LOG_ERROR("InstrumentService", "Failed to download ICICI security master: " + reply->errorString());
+ drain();
+ return {};
+ }
+
+ QByteArray data = reply->readAll();
+ drain();
+ LOG_INFO("InstrumentService", QString("Downloaded ICICI security master: %1 bytes").arg(data.size()));
+ return data;
+}
+
QByteArray InstrumentService::download_fyers_json() {
static const QStringList urls = {
"https://public.fyers.in/sym_details/NSE_CM_sym_master.json",
diff --git a/fincept-qt/src/trading/instruments/InstrumentService.h b/fincept-qt/src/trading/instruments/InstrumentService.h
index 962424863..179640ac3 100644
--- a/fincept-qt/src/trading/instruments/InstrumentService.h
+++ b/fincept-qt/src/trading/instruments/InstrumentService.h
@@ -81,6 +81,14 @@ class InstrumentService : public QObject {
QVector<Instrument> search(const QString& query, const QString& exchange, const QString& broker_id,
int limit = 50) const;
+ /// Unified cross-broker search. Returns one row per (broker, instrument)
+ /// across all `broker_ids` (empty = every broker in the catalog), with the
+ /// first broker in the list sorted first. Used by the watchlist when more
+ /// than one broker is connected. Each row carries its own broker_id +
+ /// brsymbol + token, so selection routes to that broker.
+ QVector<Instrument> search_all(const QString& query, const QString& exchange, const QStringList& broker_ids,
+ int limit = 50) const;
+
// ── F&O / Options chain helpers ──────────────────────────────────────────
//
// All three read the in-memory cache; they expect refresh()/load_from_db()
@@ -148,6 +156,7 @@ class InstrumentService : public QObject {
static QByteArray download_groww_csv();
static QByteArray download_fyers_json();
static QByteArray download_dhan_csv();
+ static QByteArray download_icici_csv();
};
} // namespace fincept::trading
diff --git a/fincept-qt/src/trading/instruments/InstrumentSources.cpp b/fincept-qt/src/trading/instruments/InstrumentSources.cpp
new file mode 100644
index 000000000..45e52eec4
--- /dev/null
+++ b/fincept-qt/src/trading/instruments/InstrumentSources.cpp
@@ -0,0 +1,36 @@
+#include "trading/instruments/InstrumentSources.h"
+
+#include "trading/instruments/parsers/AliceBlueInstrumentParser.h"
+#include "trading/instruments/parsers/FivePaisaInstrumentParser.h"
+#include "trading/instruments/parsers/FlattradeInstrumentSource.h"
+#include "trading/instruments/parsers/KotakInstrumentParser.h"
+#include "trading/instruments/parsers/MotilalInstrumentParser.h"
+#include "trading/instruments/parsers/PaytmInstrumentParser.h"
+#include "trading/instruments/parsers/SamcoInstrumentParser.h"
+#include "trading/instruments/parsers/ShoonyaInstrumentSource.h"
+#include "trading/instruments/parsers/TradejiniInstrumentParser.h"
+#include "trading/instruments/parsers/UpstoxInstrumentParser.h"
+#include "trading/instruments/parsers/XtsInstrumentParser.h"
+
+namespace fincept::trading {
+
+void register_extra_instrument_sources() {
+ static bool done = false;
+ if (done)
+ return;
+ done = true;
+
+ register_upstox_source();
+ register_fivepaisa_source();
+ register_kotak_source();
+ register_motilal_source();
+ register_paytm_source();
+ register_aliceblue_source();
+ register_shoonya_source();
+ register_flattrade_source();
+ register_samco_source();
+ register_tradejini_source();
+ register_iifl_source();
+}
+
+} // namespace fincept::trading
diff --git a/fincept-qt/src/trading/instruments/InstrumentSources.h b/fincept-qt/src/trading/instruments/InstrumentSources.h
new file mode 100644
index 000000000..938ad45ad
--- /dev/null
+++ b/fincept-qt/src/trading/instruments/InstrumentSources.h
@@ -0,0 +1,7 @@
+#pragma once
+// Aggregator for the broker instrument sources added by the unified cross-broker
+// search work. Called once from InstrumentService alongside the original
+// first-party (zerodha/angelone/groww/fyers/dhan/icicidirect) registrations.
+namespace fincept::trading {
+void register_extra_instrument_sources();
+}
diff --git a/fincept-qt/src/trading/instruments/InstrumentTypes.h b/fincept-qt/src/trading/instruments/InstrumentTypes.h
index 822f0c760..49944d356 100644
--- a/fincept-qt/src/trading/instruments/InstrumentTypes.h
+++ b/fincept-qt/src/trading/instruments/InstrumentTypes.h
@@ -52,6 +52,9 @@ struct Instrument {
InstrumentType instrument_type = InstrumentType::UNKNOWN;
double tick_size = 0.05;
QString broker_id; // "zerodha", "angelone", etc.
+ QString broker_token; // Native non-numeric key (Upstox instrument_key "NSE_EQ|INE…",
+ // Samco "758960_NSE"). Empty for numeric-token brokers, which
+ // keep their value in instrument_token.
/// Canonical DataHub topic id for this instrument: "<exchange>:<symbol>"
/// when exchange is set, else just the symbol. Stable across brokers.
diff --git a/fincept-qt/src/trading/instruments/ZerodhaInstrumentParser.cpp b/fincept-qt/src/trading/instruments/ZerodhaInstrumentParser.cpp
index b0e5dd446..9b272a6d9 100644
--- a/fincept-qt/src/trading/instruments/ZerodhaInstrumentParser.cpp
+++ b/fincept-qt/src/trading/instruments/ZerodhaInstrumentParser.cpp
@@ -1,6 +1,7 @@
#include "trading/instruments/ZerodhaInstrumentParser.h"
#include "core/logging/Logger.h"
+#include "trading/instruments/InstrumentNormalize.h"
#include <QDate>
#include <QMap>
@@ -89,7 +90,9 @@ QString ZerodhaInstrumentParser::expiry_nodashes(const QString& expiry_iso) {
}
QString ZerodhaInstrumentParser::map_index_name(const QString& tradingsymbol) {
- return index_map().value(tradingsymbol.toUpper(), tradingsymbol);
+ // Broker map first, then the shared normalizer as the final authority so the
+ // canonical index name matches every other broker's output.
+ return norm::normalise_index_symbol(index_map().value(tradingsymbol.toUpper(), tradingsymbol));
}
QString ZerodhaInstrumentParser::normalise_exchange(const QString& exchange, const QString& segment) {
@@ -107,8 +110,8 @@ QString ZerodhaInstrumentParser::normalise_symbol(const QString& tradingsymbol,
return name.toUpper() + expiry_nd + "FUT";
}
if (instrument_type == "CE" || instrument_type == "PE") {
- // strike as integer (drop .0)
- QString strike_str = QString::number(static_cast<int>(strike));
+ // Shared strike formatting (preserves fractional strikes — matches every broker).
+ QString strike_str = norm::format_strike(strike);
return name.toUpper() + expiry_nd + strike_str + instrument_type.toUpper();
}
if (instrument_type == "INDEX") {
diff --git a/fincept-qt/src/trading/instruments/parsers/AliceBlueInstrumentParser.cpp b/fincept-qt/src/trading/instruments/parsers/AliceBlueInstrumentParser.cpp
new file mode 100644
index 000000000..b82438fd9
--- /dev/null
+++ b/fincept-qt/src/trading/instruments/parsers/AliceBlueInstrumentParser.cpp
@@ -0,0 +1,144 @@
+#include "trading/instruments/parsers/AliceBlueInstrumentParser.h"
+
+#include "core/logging/Logger.h"
+#include "trading/TradingTypes.h"
+#include "trading/instruments/InstrumentDownload.h"
+#include "trading/instruments/InstrumentNormalize.h"
+#include "trading/instruments/InstrumentSource.h"
+#include "trading/instruments/SymbolResolver.h"
+#include "trading/instruments/parsers/CsvUtil.h"
+
+#include <QHash>
+#include <QStringList>
+#include <QStringView>
+
+namespace fincept::trading {
+namespace {
+
+const QStringList kKeys = {"NSE", "BSE", "NFO", "BFO", "CDS", "BCD", "MCX", "INDICES"};
+const QString kMarker = QStringLiteral("#EX:");
+
+QByteArray download_aliceblue(const BrokerCredentials&) {
+ QByteArray combined;
+ for (const QString& key : kKeys) {
+ const QString url =
+ QString("https://v2api.aliceblueonline.com/restpy/static/contract_master/V2/%1.csv").arg(key);
+ const QByteArray csv = http_get_blocking(url);
+ if (csv.isEmpty())
+ continue;
+ combined += (kMarker + key + "\n").toUtf8();
+ combined += csv;
+ if (!csv.endsWith('\n'))
+ combined += '\n';
+ }
+ return combined;
+}
+
+QVector<Instrument> parse_aliceblue(const QByteArray& payload) {
+ QVector<Instrument> out;
+ if (payload.isEmpty())
+ return out;
+
+ const QString text = QString::fromUtf8(payload);
+ const QList<QStringView> lines = QStringView(text).split(u'\n');
+
+ QString key;
+ QHash<QString, int> idx;
+ bool want_header = false;
+ for (const QStringView lv : lines) {
+ const QString line = lv.trimmed().toString();
+ if (line.isEmpty())
+ continue;
+ if (line.startsWith(kMarker)) {
+ key = line.mid(kMarker.size());
+ want_header = true;
+ continue;
+ }
+ if (want_header) { // first line after a marker is that file's header
+ idx = csv::header_index(line);
+ want_header = false;
+ continue;
+ }
+ const QStringList row = csv::split_csv_line(line);
+
+ if (key == "INDICES") {
+ // lowercase 3-col: exch, symbol, token
+ const QString raw_exch = csv::field(row, idx, "exch");
+ const QString raw_sym = csv::field(row, idx, "symbol");
+ const QString token = csv::field(row, idx, "token");
+ if (raw_sym.isEmpty())
+ continue;
+ Instrument inst;
+ inst.broker_id = "aliceblue";
+ inst.instrument_token = token.toLongLong();
+ if (inst.instrument_token == 0)
+ inst.instrument_token = norm::stable_token(raw_exch + raw_sym);
+ inst.exchange_token = inst.instrument_token;
+ inst.instrument_type = InstrumentType::INDEX;
+ inst.name = norm::normalise_index_symbol(raw_sym);
+ inst.symbol = inst.name;
+ inst.brsymbol = raw_sym;
+ inst.brexchange = raw_exch.trimmed().toUpper();
+ inst.exchange = norm::normalise_exchange(raw_exch, InstrumentType::INDEX);
+ inst.lot_size = 1;
+ inst.tick_size = 0.05;
+ out.append(inst);
+ continue;
+ }
+
+ const QString exch = csv::field(row, idx, "Exch").trimmed().toUpper(); // already canonical
+ const QString token = csv::field(row, idx, "Token");
+ if (exch.isEmpty() || token.isEmpty())
+ continue;
+ const QString symbol_col = csv::field(row, idx, "Symbol");
+ const QString br = csv::field(row, idx, "Trading Symbol");
+ const QString ot = csv::field(row, idx, "Option Type").trimmed().toUpper();
+
+ const bool is_deriv = (exch == "NFO" || exch == "BFO" || exch == "CDS" || exch == "BCD" || exch == "MCX");
+ InstrumentType t;
+ if (!is_deriv)
+ t = InstrumentType::EQ;
+ else if (ot == "CE")
+ t = InstrumentType::CE;
+ else if (ot == "PE")
+ t = InstrumentType::PE;
+ else
+ t = InstrumentType::FUT; // XX / SF / IF / FUTCUR / FUTCOM / FUTIDX …
+
+ Instrument inst;
+ inst.broker_id = "aliceblue";
+ inst.instrument_token = token.toLongLong();
+ inst.exchange_token = inst.instrument_token;
+ inst.brsymbol = br.isEmpty() ? symbol_col : br;
+ inst.name = symbol_col.toUpper(); // underlying
+ inst.brexchange = exch;
+ inst.instrument_type = t;
+ inst.exchange = norm::normalise_exchange(exch, t);
+ inst.strike = csv::field(row, idx, "Strike Price").toDouble();
+ inst.lot_size = qMax(1, csv::field(row, idx, "Lot Size").toInt());
+ const double tick = csv::field(row, idx, "Tick Size").toDouble();
+ inst.tick_size = tick > 0.0 ? tick : 0.05;
+
+ const QString exp_nd = norm::expiry_to_nodash(csv::field(row, idx, "Expiry Date"));
+ inst.expiry = norm::nodash_to_display(exp_nd);
+
+ const QString fallback = (t == InstrumentType::EQ) ? inst.brsymbol : inst.name;
+ inst.symbol = norm::synthesize_symbol(inst.name, t, exp_nd, inst.strike, fallback);
+ if (inst.symbol.isEmpty())
+ continue;
+ out.append(inst);
+ }
+
+ LOG_INFO("AliceBlueSource", QString("Parsed %1 AliceBlue instruments").arg(out.size()));
+ return out;
+}
+
+} // namespace
+
+void register_aliceblue_source() {
+ SymbolResolver::instance().register_source({QStringLiteral("aliceblue"),
+ [](const BrokerCredentials& c) { return download_aliceblue(c); },
+ [](const QByteArray& p) { return parse_aliceblue(p); }});
+}
+
+} // namespace fincept::trading
diff --git a/fincept-qt/src/trading/instruments/parsers/AliceBlueInstrumentParser.h b/fincept-qt/src/trading/instruments/parsers/AliceBlueInstrumentParser.h
new file mode 100644
index 000000000..11e437fb4
--- /dev/null
+++ b/fincept-qt/src/trading/instruments/parsers/AliceBlueInstrumentParser.h
@@ -0,0 +1,7 @@
+#pragma once
+// AliceBlue instrument source. Public per-exchange contract_master CSVs (column
+// layout differs per file); futures rebuilt canonically rather than copying
+// AliceBlue's non-canonical trading-symbol forms.
+namespace fincept::trading {
+void register_aliceblue_source();
+}
diff --git a/fincept-qt/src/trading/instruments/parsers/CsvUtil.h b/fincept-qt/src/trading/instruments/parsers/CsvUtil.h
new file mode 100644
index 000000000..09ce49ae7
--- /dev/null
+++ b/fincept-qt/src/trading/instruments/parsers/CsvUtil.h
@@ -0,0 +1,66 @@
+#pragma once
+// CsvUtil — minimal CSV helpers for instrument-master parsing. Header-only.
+//
+// Several broker masters double-quote fields and embed commas inside names
+// (Paytm fully-quoted, 5paisa FullName, etc.), so a plain split(',') corrupts
+// rows. split_csv_line handles RFC-4180-style quoting. header_index builds a
+// case-insensitive column-name → index map so parsers read by name rather than
+// fragile positional offsets.
+
+#include <QHash>
+#include <QString>
+#include <QStringList>
+#include <QStringView>
+
+namespace fincept::trading::csv {
+
+/// Split one CSV line, honouring double-quoted fields ("" = literal quote).
+inline QStringList split_csv_line(QStringView line) {
+ QStringList out;
+ QString field;
+ bool in_quotes = false;
+ for (int i = 0; i < line.size(); ++i) {
+ const QChar ch = line[i];
+ if (in_quotes) {
+ if (ch == '"') {
+ if (i + 1 < line.size() && line[i + 1] == '"') { // escaped quote
+ field += '"';
+ ++i;
+ } else {
+ in_quotes = false;
+ }
+ } else {
+ field += ch;
+ }
+ } else if (ch == '"') {
+ in_quotes = true;
+ } else if (ch == ',') {
+ out.append(field);
+ field.clear();
+ } else {
+ field += ch;
+ }
+ }
+ out.append(field);
+ return out;
+}
+
+/// Build a case-insensitive {column name (trimmed, upper) → index} map from a
+/// header line.
+inline QHash<QString, int> header_index(QStringView header_line) {
+ QHash<QString, int> idx;
+ const QStringList cols = split_csv_line(header_line);
+ for (int i = 0; i < cols.size(); ++i)
+ idx.insert(cols[i].trimmed().toUpper(), i);
+ return idx;
+}
+
+/// Safe field read by header name. Returns "" if the column or row cell is absent.
+inline QString field(const QStringList& row, const QHash<QString, int>& idx, const QString& name) {
+ const auto it = idx.constFind(name.toUpper());
+ if (it == idx.constEnd() || it.value() >= row.size())
+ return {};
+ return row[it.value()].trimmed();
+}
+
+} // namespace fincept::trading::csv
diff --git a/fincept-qt/src/trading/instruments/parsers/FivePaisaInstrumentParser.cpp b/fincept-qt/src/trading/instruments/parsers/FivePaisaInstrumentParser.cpp
new file mode 100644
index 000000000..eabd89f67
--- /dev/null
+++ b/fincept-qt/src/trading/instruments/parsers/FivePaisaInstrumentParser.cpp
@@ -0,0 +1,141 @@
+#include "trading/instruments/parsers/FivePaisaInstrumentParser.h"
+
+#include "core/logging/Logger.h"
+#include "trading/TradingTypes.h"
+#include "trading/instruments/InstrumentDownload.h"
+#include "trading/instruments/InstrumentNormalize.h"
+#include "trading/instruments/InstrumentSource.h"
+#include "trading/instruments/SymbolResolver.h"
+#include "trading/instruments/parsers/CsvUtil.h"
+
+#include <QStringList>
+#include <QStringView>
+
+namespace fincept::trading {
+namespace {
+
+QByteArray download_fivepaisa(const BrokerCredentials&) {
+ // Public ScripMaster CSV (all segments) — no auth.
+ return http_get_blocking("https://openapi.5paisa.com/VendorsAPI/Service1.svc/ScripMaster/segment/all", {},
+ 120000);
+}
+
+// Map the 5paisa (Exch,ExchType) tuple to a canonical exchange. Returns "" if
+// the tuple is unmapped (caller skips the row).
+QString canon_exchange(const QString& exch, const QString& exch_type) {
+ const QString e = exch.trimmed().toUpper();
+ const QString t = exch_type.trimmed().toUpper();
+ if (e == "N" && t == "C")
+ return "NSE";
+ if (e == "B" && t == "C")
+ return "BSE";
+ if (e == "N" && t == "D")
+ return "NFO";
+ if (e == "B" && t == "D")
+ return "BFO";
+ if (e == "N" && t == "U")
+ return "CDS";
+ if (e == "B" && t == "U")
+ return "BCD";
+ if (e == "M" && t == "D")
+ return "MCX";
+ return {};
+}
+
+QVector<Instrument> parse_fivepaisa(const QByteArray& payload) {
+ QVector<Instrument> out;
+ if (payload.isEmpty())
+ return out;
+
+ const QString text = QString::fromUtf8(payload);
+ const QList<QStringView> lines = QStringView(text).split(u'\n');
+ if (lines.isEmpty())
+ return out;
+
+ const QHash<QString, int> idx = csv::header_index(lines.first());
+ for (int i = 1; i < lines.size(); ++i) {
+ const QString line = lines[i].trimmed().toString();
+ if (line.isEmpty())
+ continue;
+ // FullName may contain commas — always use the quoting-aware splitter.
+ const QStringList row = csv::split_csv_line(line);
+
+ const QString token = csv::field(row, idx, "ScripCode");
+ if (token.isEmpty() || token.toLongLong() == 0)
+ continue;
+
+ const QString rawExch = csv::field(row, idx, "Exch");
+ const QString rawExchType = csv::field(row, idx, "ExchType");
+ QString canonExch = canon_exchange(rawExch, rawExchType);
+ if (canonExch.isEmpty())
+ continue;
+
+ const QString brsym = csv::field(row, idx, "Name").toUpper();
+ const QString fullName = csv::field(row, idx, "FullName");
+ QString symbolRoot = csv::field(row, idx, "SymbolRoot");
+ QString underlyingName = symbolRoot.isEmpty() ? (fullName.isEmpty() ? brsym : fullName) : symbolRoot;
+
+ // INDEX override: pseudo-scrip codes above 999900 are indices.
+ const qint64 scripCode = token.toLongLong();
+ const QString eUp = rawExch.trimmed().toUpper();
+ const QString tUp = rawExchType.trimmed().toUpper();
+ if (eUp == "N" && tUp == "C" && scripCode > 999900)
+ canonExch = "NSE_INDEX";
+ else if (eUp == "B" && tUp == "C" && scripCode > 999900)
+ canonExch = "BSE_INDEX";
+
+ const bool is_index = (canonExch == "NSE_INDEX" || canonExch == "BSE_INDEX");
+ const bool is_deriv =
+ (canonExch == "NFO" || canonExch == "BFO" || canonExch == "CDS" || canonExch == "BCD" ||
+ canonExch == "MCX");
+
+ InstrumentType t;
+ if (is_index)
+ t = InstrumentType::INDEX;
+ else if (is_deriv) {
+ if (brsym.endsWith("CE"))
+ t = InstrumentType::CE;
+ else if (brsym.endsWith("PE"))
+ t = InstrumentType::PE;
+ else
+ t = InstrumentType::FUT;
+ } else
+ t = InstrumentType::EQ;
+
+ Instrument inst;
+ inst.broker_id = "fivepaisa";
+ inst.instrument_token = token.toLongLong();
+ inst.exchange_token = inst.instrument_token;
+ inst.brsymbol = brsym;
+ inst.name = underlyingName.toUpper();
+ inst.brexchange = canonExch;
+ inst.instrument_type = t;
+ inst.exchange = norm::normalise_exchange(canonExch, t);
+ inst.strike = csv::field(row, idx, "StrikeRate").toDouble();
+ inst.lot_size = qMax(1, csv::field(row, idx, "LotSize").toInt());
+ const double tick = csv::field(row, idx, "TickSize").toDouble();
+ inst.tick_size = tick > 0.0 ? tick : 0.05;
+
+ const QString exp_nd = norm::expiry_to_nodash(csv::field(row, idx, "Expiry"));
+ inst.expiry = norm::nodash_to_display(exp_nd);
+
+ const QString fallback = (t == InstrumentType::EQ) ? brsym : underlyingName;
+ inst.symbol = norm::synthesize_symbol(inst.name, t, exp_nd, inst.strike, fallback);
+ if (inst.symbol.isEmpty())
+ continue;
+ out.append(inst);
+ }
+
+ LOG_INFO("FivePaisaSource", QString("Parsed %1 FivePaisa instruments").arg(out.size()));
+ return out;
+}
+
+} // namespace
+
+void register_fivepaisa_source() {
+ SymbolResolver::instance().register_source({QStringLiteral("fivepaisa"),
+ [](const BrokerCredentials& c) { return download_fivepaisa(c); },
+ [](const QByteArray& p) { return parse_fivepaisa(p); }});
+}
+
+} // namespace fincept::trading
diff --git a/fincept-qt/src/trading/instruments/parsers/FivePaisaInstrumentParser.h b/fincept-qt/src/trading/instruments/parsers/FivePaisaInstrumentParser.h
new file mode 100644
index 000000000..84809a157
--- /dev/null
+++ b/fincept-qt/src/trading/instruments/parsers/FivePaisaInstrumentParser.h
@@ -0,0 +1,6 @@
+#pragma once
+// 5paisa instrument source. Public ScripMaster CSV (segment/all); token is the
+// numeric ScripCode. Exchange resolved from the (Exch,ExchType) tuple.
+namespace fincept::trading {
+void register_fivepaisa_source();
+}
diff --git a/fincept-qt/src/trading/instruments/parsers/FlattradeInstrumentSource.cpp b/fincept-qt/src/trading/instruments/parsers/FlattradeInstrumentSource.cpp
new file mode 100644
index 000000000..3cf200061
--- /dev/null
+++ b/fincept-qt/src/trading/instruments/parsers/FlattradeInstrumentSource.cpp
@@ -0,0 +1,82 @@
+#include "trading/instruments/parsers/FlattradeInstrumentSource.h"
+
+#include "core/logging/Logger.h"
+#include "trading/TradingTypes.h"
+#include "trading/instruments/InstrumentDownload.h"
+#include "trading/instruments/InstrumentSource.h"
+#include "trading/instruments/SymbolResolver.h"
+#include "trading/instruments/parsers/NorenSymbolParser.h"
+
+#include <QStringList>
+
+namespace fincept::trading {
+namespace {
+
+const QStringList kFiles = {
+ "NSE_Equity.csv", "Nfo_Equity_Derivatives.csv", "Nfo_Index_Derivatives.csv",
+ "Currency_Derivatives.csv", "Commodity.csv", "BSE_Equity.csv",
+ "Bfo_Index_Derivatives.csv", "Bfo_Equity_Derivatives.csv",
+};
+
+QByteArray download_flattrade(const BrokerCredentials&) {
+ QByteArray combined;
+ for (const QString& f : kFiles) {
+ const QString url = QString("https://flattrade.s3.ap-south-1.amazonaws.com/scripmaster/%1").arg(f);
+ const QByteArray csv = http_get_blocking(url);
+ if (csv.isEmpty())
+ continue;
+ combined += csv;
+ if (!csv.endsWith('\n'))
+ combined += '\n';
+ }
+ return combined;
+}
+
+QVector<Instrument> parse_flattrade(const QByteArray& payload) {
+ QVector<Instrument> out;
+ if (payload.isEmpty())
+ return out;
+
+ // Uniform 9-col layout across all files:
+ // Exchange, Token, Lotsize, Symbol, Tradingsymbol, Instrument, Expiry, Strike, Optiontype
+ const QString text = QString::fromUtf8(payload);
+ const QList<QStringView> lines = QStringView(text).split(u'\n');
+ for (const QStringView lv : lines) {
+ const QString line = lv.trimmed().toString();
+ if (line.isEmpty())
+ continue;
+ const QStringList c = line.split(',');
+ if (c.size() < 9)
+ continue;
+ if (c[0].compare("Exchange", Qt::CaseInsensitive) == 0) // per-file header row
+ continue;
+ if (c[1].toLongLong() == 0)
+ continue;
+
+ NorenRow r;
+ r.brexchange = c[0].trimmed().toUpper();
+ r.token = c[1];
+ r.lot_size = c[2].toInt();
+ r.name = c[3];
+ r.brsymbol = c[4];
+ r.raw_instrument = c[5];
+ r.expiry_raw = c[6];
+ r.strike = c[7].toDouble();
+ r.option_type = c[8];
+ r.tick_size = (r.brexchange == "CDS") ? 0.0025 : 0.05; // no tick column in master
+ out.append(noren_build(QStringLiteral("flattrade"), r));
+ }
+
+ LOG_INFO("FlattradeSource", QString("Parsed %1 Flattrade instruments").arg(out.size()));
+ return out;
+}
+
+} // namespace
+
+void register_flattrade_source() {
+ SymbolResolver::instance().register_source({QStringLiteral("flattrade"),
+ [](const BrokerCredentials& c) { return download_flattrade(c); },
+ [](const QByteArray& p) { return parse_flattrade(p); }});
+}
+
+} // namespace fincept::trading
diff --git a/fincept-qt/src/trading/instruments/parsers/FlattradeInstrumentSource.h b/fincept-qt/src/trading/instruments/parsers/FlattradeInstrumentSource.h
new file mode 100644
index 000000000..7fdf823fe
--- /dev/null
+++ b/fincept-qt/src/trading/instruments/parsers/FlattradeInstrumentSource.h
@@ -0,0 +1,7 @@
+#pragma once
+// Flattrade instrument source. Downloads the 8 per-segment scripmaster CSVs from
+// the public Flattrade S3 bucket (uniform 9-column layout) and parses them via
+// the shared NorenSymbolParser.
+namespace fincept::trading {
+void register_flattrade_source();
+}
diff --git a/fincept-qt/src/trading/instruments/parsers/KotakInstrumentParser.cpp b/fincept-qt/src/trading/instruments/parsers/KotakInstrumentParser.cpp
new file mode 100644
index 000000000..6750c07bf
--- /dev/null
+++ b/fincept-qt/src/trading/instruments/parsers/KotakInstrumentParser.cpp
@@ -0,0 +1,191 @@
+#include "trading/instruments/parsers/KotakInstrumentParser.h"
+
+#include "core/logging/Logger.h"
+#include "trading/TradingTypes.h"
+#include "trading/instruments/InstrumentDownload.h"
+#include "trading/instruments/InstrumentNormalize.h"
+#include "trading/instruments/InstrumentSource.h"
+#include "trading/instruments/SymbolResolver.h"
+#include "trading/instruments/parsers/CsvUtil.h"
+
+#include <QDateTime>
+#include <QJsonArray>
+#include <QJsonDocument>
+#include <QJsonObject>
+#include <QStringList>
+#include <QStringView>
+
+namespace fincept::trading {
+namespace {
+
+const QString kMarker = QStringLiteral("#SEG:");
+
+// Map a master CSV filename to its segment key.
+QString segment_for_file(const QString& url) {
+ const QString f = url.toLower();
+ if (f.contains("nse_cm"))
+ return "NSE_CM";
+ if (f.contains("bse_cm"))
+ return "BSE_CM";
+ if (f.contains("nse_fo"))
+ return "NSE_FO";
+ if (f.contains("bse_fo"))
+ return "BSE_FO";
+ if (f.contains("cde_fo"))
+ return "CDE_FO";
+ if (f.contains("mcx_fo"))
+ return "MCX_FO";
+ return {};
+}
+
+QByteArray download_kotak(const BrokerCredentials& creds) {
+ // access_token packed: trading_token:::trading_sid:::base_url:::portal_token:::server_id
+ const QStringList parts = creds.access_token.split(":::");
+ if (parts.size() < 4) {
+ LOG_WARN("KotakSource", "Kotak access_token not in packed form — cannot fetch master");
+ return {};
+ }
+ const QString base_url = parts[2];
+ const QString token = parts[3];
+ if (base_url.isEmpty() || token.isEmpty())
+ return {};
+
+ const QByteArray paths_resp =
+ http_get_blocking(base_url + "/script-details/1.0/masterscrip/file-paths", {{"Authorization", token}}, 30000);
+ if (paths_resp.isEmpty())
+ return {};
+ const QJsonArray files = QJsonDocument::fromJson(paths_resp)
+ .object()
+ .value("data")
+ .toObject()
+ .value("filesPaths")
+ .toArray();
+
+ QByteArray combined;
+ for (const QJsonValue& fv : files) {
+ const QString url = fv.toString();
+ const QString seg = segment_for_file(url);
+ if (seg.isEmpty())
+ continue; // skip nse_com etc.
+ const QByteArray csv = http_get_blocking(url, {}, 30000);
+ if (csv.isEmpty())
+ continue;
+ combined += (kMarker + seg + "\n").toUtf8();
+ combined += csv;
+ if (!csv.endsWith('\n'))
+ combined += '\n';
+ }
+ return combined;
+}
+
+QVector<Instrument> parse_kotak(const QByteArray& payload) {
+ QVector<Instrument> out;
+ if (payload.isEmpty())
+ return out;
+
+ const QString text = QString::fromUtf8(payload);
+ const QList<QStringView> lines = QStringView(text).split(u'\n');
+
+ QString seg;
+ QHash<QString, int> idx;
+ bool want_header = false;
+ for (const QStringView lv : lines) {
+ const QString line = lv.trimmed().toString();
+ if (line.isEmpty())
+ continue;
+ if (line.startsWith(kMarker)) {
+ seg = line.mid(kMarker.size());
+ want_header = true;
+ continue;
+ }
+ if (want_header) {
+ // Kotak headers carry stray ';' and spaces (e.g. "dStrikePrice;", "dTickSize ").
+ QString clean = line;
+ clean.remove(';');
+ idx = csv::header_index(clean);
+ want_header = false;
+ continue;
+ }
+ const QStringList row = csv::split_csv_line(line);
+ const bool is_fo = (seg == "NSE_FO" || seg == "BSE_FO" || seg == "CDE_FO" || seg == "MCX_FO");
+
+ const QString token = csv::field(row, idx, "pSymbol");
+ if (token.isEmpty() || token.toLongLong() == 0)
+ continue;
+
+ Instrument inst;
+ inst.broker_id = "kotak";
+ inst.instrument_token = token.toLongLong();
+ inst.exchange_token = inst.instrument_token;
+ inst.brsymbol = csv::field(row, idx, "pTrdSymbol");
+ inst.lot_size = qMax(1, csv::field(row, idx, "lLotSize").toInt());
+ const double tick = csv::field(row, idx, "dTickSize").toDouble();
+ inst.tick_size = tick > 0.0 ? tick / 100.0 : 0.05;
+
+ if (!is_fo) {
+ // Equity / index: NSE_CM, BSE_CM
+ const bool is_nse = (seg == "NSE_CM");
+ const QString isin = csv::field(row, idx, "pISIN");
+ const QString name = csv::field(row, idx, "pSymbolName");
+ inst.name = name.toUpper();
+ if (isin.trimmed().isEmpty()) { // no ISIN → index
+ inst.instrument_type = InstrumentType::INDEX;
+ inst.brexchange = is_nse ? "NSE" : "BSE";
+ inst.exchange = is_nse ? "NSE_INDEX" : "BSE_INDEX";
+ inst.symbol = norm::normalise_index_symbol(name);
+ } else {
+ inst.instrument_type = InstrumentType::EQ;
+ inst.brexchange = is_nse ? "NSE" : "BSE";
+ inst.exchange = inst.brexchange;
+ inst.symbol = norm::strip_eq_suffix(name);
+ }
+ if (inst.symbol.isEmpty())
+ continue;
+ out.append(inst);
+ continue;
+ }
+
+ // F&O segments.
+ const QString opt = csv::field(row, idx, "pOptionType").toUpper();
+ InstrumentType t = (opt == "CE") ? InstrumentType::CE
+ : (opt == "PE") ? InstrumentType::PE
+ : InstrumentType::FUT; // XX
+ inst.instrument_type = t;
+ inst.name = csv::field(row, idx, "pSymbolName").toUpper();
+ inst.strike = csv::field(row, idx, "dStrikePrice").toDouble() / 100.0;
+ inst.brexchange = csv::field(row, idx, "pExchSeg");
+
+ QString canon_exch = (seg == "NSE_FO") ? "NFO" : (seg == "BSE_FO") ? "BFO"
+ : (seg == "CDE_FO") ? "CDS"
+ : "MCX";
+ inst.exchange = norm::normalise_exchange(canon_exch, t);
+
+ // Expiry: unix seconds; NSE_FO & CDE_FO carry a +315513000 epoch offset.
+ qint64 esec = csv::field(row, idx, "lExpiryDate").toLongLong();
+ QString exp_nd;
+ if (esec > 0) {
+ if (seg == "NSE_FO" || seg == "CDE_FO")
+ esec += 315513000;
+ const QDate d = QDateTime::fromSecsSinceEpoch(esec, Qt::UTC).date();
+ exp_nd = norm::expiry_to_nodash(d.toString("yyyy-MM-dd"));
+ inst.expiry = norm::nodash_to_display(exp_nd);
+ }
+ inst.symbol = norm::synthesize_symbol(inst.name, t, exp_nd, inst.strike, inst.name);
+ if (inst.symbol.isEmpty())
+ continue;
+ out.append(inst);
+ }
+
+ LOG_INFO("KotakSource", QString("Parsed %1 Kotak instruments").arg(out.size()));
+ return out;
+}
+
+} // namespace
+
+void register_kotak_source() {
+ SymbolResolver::instance().register_source({QStringLiteral("kotak"),
+ [](const BrokerCredentials& c) { return download_kotak(c); },
+ [](const QByteArray& p) { return parse_kotak(p); }});
+}
+
+} // namespace fincept::trading
diff --git a/fincept-qt/src/trading/instruments/parsers/KotakInstrumentParser.h b/fincept-qt/src/trading/instruments/parsers/KotakInstrumentParser.h
new file mode 100644
index 000000000..8f3adcb8f
--- /dev/null
+++ b/fincept-qt/src/trading/instruments/parsers/KotakInstrumentParser.h
@@ -0,0 +1,8 @@
+#pragma once
+// Kotak Neo instrument source. Authenticated: reads the master file-paths API
+// (Authorization + base_url unpacked from the account's :::-packed access_token),
+// then downloads the per-segment CSVs. Strike/tick are paise (÷100); F&O expiry
+// is a unix epoch with a +315513000 offset for NSE_FO/CDE_FO only.
+namespace fincept::trading {
+void register_kotak_source();
+}
diff --git a/fincept-qt/src/trading/instruments/parsers/MotilalInstrumentParser.cpp b/fincept-qt/src/trading/instruments/parsers/MotilalInstrumentParser.cpp
new file mode 100644
index 000000000..ba5b8ce53
--- /dev/null
+++ b/fincept-qt/src/trading/instruments/parsers/MotilalInstrumentParser.cpp
@@ -0,0 +1,214 @@
+#include "trading/instruments/parsers/MotilalInstrumentParser.h"
+
+#include "core/logging/Logger.h"
+#include "trading/TradingTypes.h"
+#include "trading/instruments/InstrumentDownload.h"
+#include "trading/instruments/InstrumentNormalize.h"
+#include "trading/instruments/InstrumentSource.h"
+#include "trading/instruments/SymbolResolver.h"
+#include "trading/instruments/parsers/CsvUtil.h"
+
+#include <QRegularExpression>
+#include <QStringList>
+#include <QStringView>
+
+namespace fincept::trading {
+namespace {
+
+// Public scrip-master + index CSVs per exchange (no auth). Each file has its own
+// header row, so download joins them into one payload with section markers and
+// parse rebuilds a csv::header_index per section.
+const QStringList kScripExchanges = {"NSE", "BSE", "NSEFO", "NSECD", "MCX", "BSEFO"};
+const QStringList kIndexExchanges = {"NSE", "BSE"};
+
+const QString kScripMarker = QStringLiteral("#SCRIP:");
+const QString kIndexMarker = QStringLiteral("#INDEX:");
+
+QByteArray download_motilal(const BrokerCredentials&) {
+ QByteArray combined;
+ for (const QString& ex : kScripExchanges) {
+ const QString url = QString("https://openapi.motilaloswal.com/getscripmastercsv?name=%1").arg(ex);
+ const QByteArray body = http_get_blocking(url, {}, 120000);
+ if (body.isEmpty())
+ continue;
+ combined += (kScripMarker + ex + "\n").toUtf8();
+ combined += body;
+ combined += '\n';
+ }
+ for (const QString& ex : kIndexExchanges) {
+ const QString url = QString("https://openapi.motilaloswal.com/getindexdatacsv?name=%1").arg(ex);
+ const QByteArray body = http_get_blocking(url, {}, 120000);
+ if (body.isEmpty())
+ continue;
+ combined += (kIndexMarker + ex + "\n").toUtf8();
+ combined += body;
+ combined += '\n';
+ }
+ return combined;
+}
+
+// Motilal exchange code → canonical exchange. Unmapped codes are skipped.
+QString canon_exchange(const QString& raw) {
+ const QString e = raw.trimmed().toUpper();
+ if (e == "NSE")
+ return "NSE";
+ if (e == "BSE")
+ return "BSE";
+ if (e == "NSEFO")
+ return "NFO";
+ if (e == "NSECD")
+ return "CDS";
+ if (e == "MCX")
+ return "MCX";
+ if (e == "BSEFO")
+ return "BFO";
+ if (e == "BSECD")
+ return "BCD";
+ return {};
+}
+
+void parse_scrip_row(const QStringList& row, const QHash<QString, int>& idx, QVector<Instrument>& out) {
+ const QString token = csv::field(row, idx, "scripcode");
+ if (token.isEmpty() || token.toLongLong() == 0)
+ return;
+
+ const QString raw_exch = csv::field(row, idx, "exchangename");
+ const QString exch = canon_exchange(raw_exch);
+ if (exch.isEmpty())
+ return;
+
+ const QString brsym = csv::field(row, idx, "scripname");
+ const QString underlying = csv::field(row, idx, "scripshortname").toUpper();
+ const QString instr = csv::field(row, idx, "instrumentname").toUpper();
+ const QString opt = csv::field(row, idx, "optiontype").toUpper();
+
+ const bool is_deriv = (exch == "NFO" || exch == "BFO" || exch == "CDS" || exch == "MCX");
+
+ InstrumentType t;
+ if (opt == "CE")
+ t = InstrumentType::CE;
+ else if (opt == "PE")
+ t = InstrumentType::PE;
+ else if (opt == "XX")
+ t = InstrumentType::FUT;
+ else if (instr.contains("IDX") && (exch == "NSE" || exch == "BSE" || exch == "MCX"))
+ t = InstrumentType::INDEX;
+ else if (is_deriv)
+ t = InstrumentType::FUT;
+ else
+ t = InstrumentType::EQ;
+
+ double strike = csv::field(row, idx, "strikeprice").toDouble();
+ if (strike <= 0.0)
+ strike = 0.0;
+ const double tick = csv::field(row, idx, "ticksize").toDouble();
+
+ // Expiry is embedded in the scrip name string, e.g. "NIFTY 25-Aug-2026 CE".
+ static const QRegularExpression kExpRe(QStringLiteral("\\d{1,2}-[A-Za-z]{3}-\\d{4}"));
+ QString exp_nd;
+ const QRegularExpressionMatch m = kExpRe.match(brsym);
+ if (m.hasMatch())
+ exp_nd = norm::expiry_to_nodash(m.captured(0)); // "25-Aug-2026"
+
+ Instrument inst;
+ inst.broker_id = "motilal";
+ inst.instrument_token = token.toLongLong();
+ inst.exchange_token = inst.instrument_token;
+ inst.brsymbol = brsym;
+ inst.name = underlying;
+ inst.brexchange = raw_exch.trimmed().toUpper();
+ inst.instrument_type = t;
+ inst.exchange = norm::normalise_exchange(exch, t);
+ inst.strike = strike;
+ inst.lot_size = qMax(1, csv::field(row, idx, "marketlot").toInt());
+ inst.tick_size = tick > 0.0 ? tick : 0.05;
+ inst.expiry = norm::nodash_to_display(exp_nd);
+
+ const QString fallback = (t == InstrumentType::EQ) ? brsym : underlying;
+ inst.symbol = norm::synthesize_symbol(underlying, t, exp_nd, strike, fallback);
+ if (inst.symbol.isEmpty())
+ return;
+ out.append(inst);
+}
+
+void parse_index_row(const QString& section_ex, const QStringList& row, const QHash<QString, int>& idx,
+ QVector<Instrument>& out) {
+ const QString token = csv::field(row, idx, "indexcode");
+ const QString raw_exch = csv::field(row, idx, "exchangename");
+ const QString index_name = csv::field(row, idx, "indexname");
+ if (index_name.isEmpty())
+ return;
+
+ Instrument inst;
+ inst.broker_id = "motilal";
+ inst.symbol = norm::normalise_index_symbol(index_name);
+ inst.name = inst.symbol;
+ inst.brsymbol = index_name;
+ inst.brexchange = raw_exch.trimmed().toUpper();
+ inst.exchange = (section_ex == "BSE") ? "BSE_INDEX" : "NSE_INDEX";
+ inst.instrument_type = InstrumentType::INDEX;
+ inst.lot_size = 1;
+ inst.tick_size = 0.05;
+ const qint64 tok = token.toLongLong();
+ inst.instrument_token = tok != 0 ? tok : norm::stable_token(index_name);
+ inst.exchange_token = inst.instrument_token;
+ if (inst.symbol.isEmpty())
+ return;
+ out.append(inst);
+}
+
+QVector<Instrument> parse_motilal(const QByteArray& payload) {
+ QVector<Instrument> out;
+ if (payload.isEmpty())
+ return out;
+
+ const QString text = QString::fromUtf8(payload);
+ const QList<QStringView> lines = QStringView(text).split(u'\n');
+
+ enum class Kind { None, Scrip, Index };
+ Kind kind = Kind::None;
+ QString section_ex;
+ QHash<QString, int> idx;
+ bool want_header = false;
+
+ for (const QStringView lv : lines) {
+ const QString line = lv.trimmed().toString();
+ if (line.isEmpty())
+ continue;
+ if (line.startsWith(kScripMarker)) {
+ kind = Kind::Scrip;
+ section_ex = line.mid(kScripMarker.size());
+ want_header = true; // next line is this file's CSV header
+ continue;
+ }
+ if (line.startsWith(kIndexMarker)) {
+ kind = Kind::Index;
+ section_ex = line.mid(kIndexMarker.size());
+ want_header = true;
+ continue;
+ }
+ if (want_header) {
+ idx = csv::header_index(lv);
+ want_header = false;
+ continue;
+ }
+ const QStringList row = csv::split_csv_line(lv);
+ if (kind == Kind::Scrip)
+ parse_scrip_row(row, idx, out);
+ else if (kind == Kind::Index)
+ parse_index_row(section_ex, row, idx, out);
+ }
+
+ LOG_INFO("MotilalSource", QString("Parsed %1 Motilal instruments").arg(out.size()));
+ return out;
+}
+
+} // namespace
+
+void register_motilal_source() {
+ SymbolResolver::instance().register_source({QStringLiteral("motilal"),
+ [](const BrokerCredentials& c) { return download_motilal(c); },
+ [](const QByteArray& p) { return parse_motilal(p); }});
+}
+
+} // namespace fincept::trading
diff --git a/fincept-qt/src/trading/instruments/parsers/MotilalInstrumentParser.h b/fincept-qt/src/trading/instruments/parsers/MotilalInstrumentParser.h
new file mode 100644
index 000000000..8a7680521
--- /dev/null
+++ b/fincept-qt/src/trading/instruments/parsers/MotilalInstrumentParser.h
@@ -0,0 +1,7 @@
+#pragma once
+// Motilal Oswal (OpenAPI) instrument source. Public per-exchange scrip-master
+// and index CSVs; no auth. Download combines all files into one payload with
+// "#SCRIP:<EX>" / "#INDEX:<EX>" section markers (each file has its own header).
+namespace fincept::trading {
+void register_motilal_source();
+}
diff --git a/fincept-qt/src/trading/instruments/parsers/NorenSymbolParser.cpp b/fincept-qt/src/trading/instruments/parsers/NorenSymbolParser.cpp
new file mode 100644
index 000000000..b0663e5fb
--- /dev/null
+++ b/fincept-qt/src/trading/instruments/parsers/NorenSymbolParser.cpp
@@ -0,0 +1,47 @@
+#include "trading/instruments/parsers/NorenSymbolParser.h"
+
+#include "trading/instruments/InstrumentNormalize.h"
+
+namespace fincept::trading {
+
+Instrument noren_build(const QString& broker_id, const NorenRow& r) {
+ Instrument inst;
+ inst.broker_id = broker_id;
+ inst.brexchange = r.brexchange.trimmed().toUpper();
+ inst.brsymbol = r.brsymbol.trimmed();
+ inst.name = r.name.trimmed().toUpper();
+ inst.instrument_token = r.token.toLongLong();
+ inst.exchange_token = inst.instrument_token;
+ inst.strike = r.strike;
+ inst.lot_size = r.lot_size > 0 ? r.lot_size : 1;
+ inst.tick_size = r.tick_size > 0 ? r.tick_size : 0.05;
+
+ const QString ot = r.option_type.trimmed().toUpper();
+ const QString rawi = r.raw_instrument.trimmed().toUpper();
+
+ InstrumentType t;
+ if (r.is_bse_index || rawi == "INDEX" || rawi == "UNDIND")
+ t = InstrumentType::INDEX;
+ else if (ot == "XX")
+ t = InstrumentType::FUT;
+ else if (ot == "CE")
+ t = InstrumentType::CE;
+ else if (ot == "PE")
+ t = InstrumentType::PE;
+ else
+ t = InstrumentType::EQ;
+ inst.instrument_type = t;
+
+ const QString exch = r.is_bse_index ? QStringLiteral("BSE_INDEX") : inst.brexchange;
+ inst.exchange = norm::normalise_exchange(exch, t);
+
+ const QString exp_nd = norm::expiry_to_nodash(r.expiry_raw);
+ inst.expiry = norm::nodash_to_display(exp_nd);
+
+ // EQ → strip suffix off the native trading symbol; INDEX → map the underlying.
+ const QString fallback = (t == InstrumentType::EQ) ? inst.brsymbol : inst.name;
+ inst.symbol = norm::synthesize_symbol(inst.name, t, exp_nd, r.strike, fallback);
+ return inst;
+}
+
+} // namespace fincept::trading
diff --git a/fincept-qt/src/trading/instruments/parsers/NorenSymbolParser.h b/fincept-qt/src/trading/instruments/parsers/NorenSymbolParser.h
new file mode 100644
index 000000000..4b283f15b
--- /dev/null
+++ b/fincept-qt/src/trading/instruments/parsers/NorenSymbolParser.h
@@ -0,0 +1,33 @@
+#pragma once
+// NorenSymbolParser — shared canonical builder for NorenAPI-family masters
+// (Shoonya, Flattrade). Each broker has its own download + column front-end
+// (their file formats differ), but the symbol/expiry/exchange synthesis is
+// identical, so it lives here.
+
+#include "trading/instruments/InstrumentTypes.h"
+
+#include <QString>
+
+namespace fincept::trading {
+
+/// Normalised native fields extracted from one Noren-family master row.
+struct NorenRow {
+ QString brexchange; ///< Already-canonical exch: NSE/BSE/NFO/BFO/CDS/MCX.
+ QString token; ///< Numeric token string.
+ QString name; ///< Underlying (the Symbol column).
+ QString brsymbol; ///< Native trading symbol (TradingSymbol column).
+ QString raw_instrument; ///< Instrument column: EQ/BE/INDEX/UNDIND/OPTSTK/…
+ QString option_type; ///< XX (future) / CE / PE / "" (cash).
+ double strike = 0.0;
+ QString expiry_raw; ///< e.g. "30-JUN-2026".
+ int lot_size = 1;
+ double tick_size = 0.05;
+ bool is_bse_index = false; ///< Manually-injected BSE index (SENSEX/BANKEX).
+};
+
+/// Build a canonical Instrument from a NorenRow. Decides instrument type from
+/// option_type + raw_instrument, synthesises the canonical symbol, and maps the
+/// exchange (adding _INDEX for indices).
+Instrument noren_build(const QString& broker_id, const NorenRow& r);
+
+} // namespace fincept::trading
diff --git a/fincept-qt/src/trading/instruments/parsers/PaytmInstrumentParser.cpp b/fincept-qt/src/trading/instruments/parsers/PaytmInstrumentParser.cpp
new file mode 100644
index 000000000..59ee51aed
--- /dev/null
+++ b/fincept-qt/src/trading/instruments/parsers/PaytmInstrumentParser.cpp
@@ -0,0 +1,114 @@
+#include "trading/instruments/parsers/PaytmInstrumentParser.h"
+
+#include "core/logging/Logger.h"
+#include "trading/TradingTypes.h"
+#include "trading/instruments/InstrumentDownload.h"
+#include "trading/instruments/InstrumentNormalize.h"
+#include "trading/instruments/InstrumentSource.h"
+#include "trading/instruments/SymbolResolver.h"
+#include "trading/instruments/parsers/CsvUtil.h"
+
+#include <QStringList>
+#include <QStringView>
+
+namespace fincept::trading {
+namespace {
+
+QByteArray download_paytm(const BrokerCredentials&) {
+ // Public static CSV — no auth.
+ return http_get_blocking("https://developer.paytmmoney.com/data/v1/scrips/security_master.csv", {}, 120000);
+}
+
+QVector<Instrument> parse_paytm(const QByteArray& payload) {
+ QVector<Instrument> out;
+ if (payload.isEmpty())
+ return out;
+
+ const QString text = QString::fromUtf8(payload);
+ const QList<QStringView> lines = QStringView(text).split(u'\n');
+ if (lines.isEmpty())
+ return out;
+
+ const QHash<QString, int> idx = csv::header_index(lines.first());
+ for (int i = 1; i < lines.size(); ++i) {
+ const QString line = lines[i].trimmed().toString();
+ if (line.isEmpty())
+ continue;
+ const QStringList row = csv::split_csv_line(line);
+
+ const QString token = csv::field(row, idx, "security_id");
+ if (token.isEmpty())
+ continue;
+ const QString brsym = csv::field(row, idx, "symbol");
+ const QString name = csv::field(row, idx, "name");
+ const QString raw_exch = csv::field(row, idx, "exchange").toUpper(); // "NSE"/"BSE"
+ const QString itf = csv::field(row, idx, "instrument_type").toUpper();
+
+ InstrumentType t;
+ QString canon_exch;
+ if (itf == "ES" || itf == "ETF") {
+ t = InstrumentType::EQ;
+ canon_exch = raw_exch;
+ } else if (itf == "I") {
+ t = InstrumentType::INDEX;
+ canon_exch = (raw_exch == "BSE") ? "BSE_INDEX" : "NSE_INDEX";
+ } else if (itf == "FUTIDX" || itf == "FUTSTK") {
+ t = InstrumentType::FUT;
+ canon_exch = (raw_exch == "BSE") ? "BFO" : "NFO";
+ } else if (itf == "OPTIDX" || itf == "OPTSTK") {
+ canon_exch = (raw_exch == "BSE") ? "BFO" : "NFO";
+ const QString name_up = name.toUpper();
+ if (name_up.contains("PUT"))
+ t = InstrumentType::PE;
+ else
+ t = InstrumentType::CE; // CALL or default
+ } else {
+ continue;
+ }
+
+ const QString base = name.split(' ').value(0).toUpper();
+
+ Instrument inst;
+ inst.broker_id = "paytm";
+ inst.broker_token = token;
+ inst.instrument_token = token.toLongLong();
+ inst.exchange_token = inst.instrument_token;
+ inst.brsymbol = brsym;
+ inst.name = base;
+ inst.brexchange = raw_exch;
+ inst.instrument_type = t;
+ inst.exchange = norm::normalise_exchange(canon_exch, t);
+ inst.strike = csv::field(row, idx, "strike_price").toDouble();
+ inst.lot_size = qMax(1, csv::field(row, idx, "lot_size").toInt());
+ const double tick = csv::field(row, idx, "tick_size").toDouble();
+ inst.tick_size = tick > 0.0 ? tick : 0.05;
+
+ const QString exp_nd = norm::expiry_to_nodash(csv::field(row, idx, "expiry_date")); // "YYYY-MM-DD HH:MM:SS"
+ inst.expiry = norm::nodash_to_display(exp_nd);
+
+ QString fallback;
+ if (t == InstrumentType::EQ)
+ fallback = brsym;
+ else if (t == InstrumentType::INDEX)
+ fallback = name;
+ else
+ fallback = base;
+ inst.symbol = norm::synthesize_symbol(base, t, exp_nd, inst.strike, fallback);
+ if (inst.symbol.isEmpty())
+ continue;
+ out.append(inst);
+ }
+
+ LOG_INFO("PaytmSource", QString("Parsed %1 Paytm instruments").arg(out.size()));
+ return out;
+}
+
+} // namespace
+
+void register_paytm_source() {
+ SymbolResolver::instance().register_source({QStringLiteral("paytm"),
+ [](const BrokerCredentials& c) { return download_paytm(c); },
+ [](const QByteArray& p) { return parse_paytm(p); }});
+}
+
+} // namespace fincept::trading
diff --git a/fincept-qt/src/trading/instruments/parsers/PaytmInstrumentParser.h b/fincept-qt/src/trading/instruments/parsers/PaytmInstrumentParser.h
new file mode 100644
index 000000000..8e9eb4535
--- /dev/null
+++ b/fincept-qt/src/trading/instruments/parsers/PaytmInstrumentParser.h
@@ -0,0 +1,6 @@
+#pragma once
+// Paytm Money instrument source. Public fully-quoted security_master.csv; token
+// is the numeric security_id. instrument_type field drives canonical type/exchange.
+namespace fincept::trading {
+void register_paytm_source();
+}
diff --git a/fincept-qt/src/trading/instruments/parsers/SamcoInstrumentParser.cpp b/fincept-qt/src/trading/instruments/parsers/SamcoInstrumentParser.cpp
new file mode 100644
index 000000000..fd9d70f2a
--- /dev/null
+++ b/fincept-qt/src/trading/instruments/parsers/SamcoInstrumentParser.cpp
@@ -0,0 +1,134 @@
+#include "trading/instruments/parsers/SamcoInstrumentParser.h"
+
+#include "core/logging/Logger.h"
+#include "trading/TradingTypes.h"
+#include "trading/instruments/InstrumentDownload.h"
+#include "trading/instruments/InstrumentNormalize.h"
+#include "trading/instruments/InstrumentSource.h"
+#include "trading/instruments/SymbolResolver.h"
+#include "trading/instruments/parsers/CsvUtil.h"
+
+#include <QStringList>
+#include <QStringView>
+
+namespace fincept::trading {
+namespace {
+
+QByteArray download_samco(const BrokerCredentials&) {
+ // Public static CSV — no auth.
+ return http_get_blocking("https://developers.stocknote.com/doc/ScripMaster.csv");
+}
+
+// Samco MFO is the MCX F&O exchange code → canonical MCX. Others pass through.
+QString canon_exchange(const QString& raw) {
+ const QString e = raw.trimmed().toUpper();
+ if (e == "MFO")
+ return "MCX";
+ return e;
+}
+
+QVector<Instrument> parse_samco(const QByteArray& payload) {
+ QVector<Instrument> out;
+ if (payload.isEmpty())
+ return out;
+
+ const QString text = QString::fromUtf8(payload);
+ const QList<QStringView> lines = QStringView(text).split(u'\n');
+ if (lines.isEmpty())
+ return out;
+
+ const QHash<QString, int> idx = csv::header_index(lines.first());
+ for (int i = 1; i < lines.size(); ++i) {
+ const QString line = lines[i].trimmed().toString();
+ if (line.isEmpty())
+ continue;
+ const QStringList row = csv::split_csv_line(line);
+
+ const QString token = csv::field(row, idx, "symbolCode"); // "758960_NSE"
+ if (token.isEmpty())
+ continue;
+ const QString raw_exch = csv::field(row, idx, "exchange");
+ const QString exch = canon_exchange(raw_exch);
+ const QString brsym = csv::field(row, idx, "tradingSymbol");
+ const QString name = csv::field(row, idx, "name");
+
+ const bool is_deriv = (exch == "NFO" || exch == "BFO" || exch == "CDS" || exch == "MCX");
+ const QString bsym_up = brsym.toUpper();
+
+ InstrumentType t;
+ if (!is_deriv)
+ t = InstrumentType::EQ;
+ else if (bsym_up.endsWith("CE"))
+ t = InstrumentType::CE;
+ else if (bsym_up.endsWith("PE"))
+ t = InstrumentType::PE;
+ else
+ t = InstrumentType::FUT;
+
+ Instrument inst;
+ inst.broker_id = "samco";
+ inst.broker_token = token;
+ inst.instrument_token = norm::stable_token(token);
+ inst.exchange_token = inst.instrument_token;
+ inst.brsymbol = brsym;
+ inst.name = name.toUpper();
+ inst.brexchange = raw_exch.trimmed().toUpper();
+ inst.instrument_type = t;
+ inst.exchange = norm::normalise_exchange(exch, t);
+ inst.strike = csv::field(row, idx, "strikePrice").toDouble();
+ inst.lot_size = qMax(1, csv::field(row, idx, "lotSize").toInt());
+ const double tick = csv::field(row, idx, "tickSize").toDouble();
+ inst.tick_size = tick > 0.0 ? tick : 0.05;
+
+ const QString exp_nd = norm::expiry_to_nodash(csv::field(row, idx, "expiryDate")); // DD/MM/YY
+ inst.expiry = norm::nodash_to_display(exp_nd);
+
+ const QString fallback = (t == InstrumentType::EQ) ? brsym : name;
+ inst.symbol = norm::synthesize_symbol(inst.name, t, exp_nd, inst.strike, fallback);
+ if (inst.symbol.isEmpty())
+ continue;
+ out.append(inst);
+ }
+
+ // Indices are not in the CSV — inject the tradeable ones. brsymbol is the
+ // exact name Samco's indexQuote API expects; symbol is canonical.
+ struct Idx {
+ const char* sym;
+ const char* name;
+ const char* exch;
+ };
+ static const Idx kIdx[] = {
+ {"NIFTY", "NIFTY 50", "NSE"}, {"BANKNIFTY", "NIFTY BANK", "NSE"},
+ {"FINNIFTY", "NIFTY FIN SERVICE", "NSE"}, {"MIDCPNIFTY", "NIFTY MID SELECT", "NSE"},
+ {"SENSEX", "SENSEX", "BSE"}, {"BANKEX", "BANKEX", "BSE"},
+ };
+ for (const auto& ix : kIdx) {
+ Instrument inst;
+ inst.broker_id = "samco";
+ inst.broker_token = QString("%1_INDEX").arg(ix.sym);
+ inst.instrument_token = norm::stable_token(inst.broker_token);
+ inst.exchange_token = inst.instrument_token;
+ inst.symbol = ix.sym;
+ inst.brsymbol = ix.name;
+ inst.name = ix.sym;
+ inst.brexchange = ix.exch;
+ inst.exchange = QString("%1_INDEX").arg(ix.exch);
+ inst.instrument_type = InstrumentType::INDEX;
+ inst.lot_size = 1;
+ inst.tick_size = 0.05;
+ out.append(inst);
+ }
+
+ LOG_INFO("SamcoSource", QString("Parsed %1 Samco instruments").arg(out.size()));
+ return out;
+}
+
+} // namespace
+
+void register_samco_source() {
+ SymbolResolver::instance().register_source({QStringLiteral("samco"),
+ [](const BrokerCredentials& c) { return download_samco(c); },
+ [](const QByteArray& p) { return parse_samco(p); }});
+}
+
+} // namespace fincept::trading
diff --git a/fincept-qt/src/trading/instruments/parsers/SamcoInstrumentParser.h b/fincept-qt/src/trading/instruments/parsers/SamcoInstrumentParser.h
new file mode 100644
index 000000000..f4838b160
--- /dev/null
+++ b/fincept-qt/src/trading/instruments/parsers/SamcoInstrumentParser.h
@@ -0,0 +1,6 @@
+#pragma once
+// Samco (StockNote) instrument source. Public ScripMaster.csv; token is a
+// "<num>_<EXCH>" composite string (kept in broker_token). Indices injected.
+namespace fincept::trading {
+void register_samco_source();
+}
diff --git a/fincept-qt/src/trading/instruments/parsers/ShoonyaInstrumentSource.cpp b/fincept-qt/src/trading/instruments/parsers/ShoonyaInstrumentSource.cpp
new file mode 100644
index 000000000..bb739d5fb
--- /dev/null
+++ b/fincept-qt/src/trading/instruments/parsers/ShoonyaInstrumentSource.cpp
@@ -0,0 +1,162 @@
+#include "trading/instruments/parsers/ShoonyaInstrumentSource.h"
+
+#include "core/logging/Logger.h"
+#include "trading/TradingTypes.h"
+#include "trading/instruments/InstrumentDecompress.h"
+#include "trading/instruments/InstrumentDownload.h"
+#include "trading/instruments/InstrumentSource.h"
+#include "trading/instruments/SymbolResolver.h"
+#include "trading/instruments/parsers/NorenSymbolParser.h"
+
+#include <QStringList>
+
+namespace fincept::trading {
+namespace {
+
+// Per-exchange "<EX>_symbols.txt.zip" masters. Column layout differs per file.
+const QStringList kExchanges = {"NSE", "NFO", "CDS", "MCX", "BSE", "BFO"};
+
+// Combined-payload section marker (download joins all exchanges into one blob;
+// parse splits on it because each exchange has a different column layout).
+const QString kMarker = QStringLiteral("#EX:");
+
+QByteArray download_shoonya(const BrokerCredentials&) {
+ QByteArray combined;
+ for (const QString& ex : kExchanges) {
+ const QString url = QString("https://api.shoonya.com/%1_symbols.txt.zip").arg(ex);
+ const QByteArray zip = http_get_blocking(url);
+ if (zip.isEmpty())
+ continue;
+ const QByteArray txt = decompress::unzip_first_entry(zip);
+ if (txt.isEmpty()) {
+ LOG_WARN("ShoonyaSource", QString("Could not unzip %1").arg(url));
+ continue;
+ }
+ combined += (kMarker + ex + "\n").toUtf8();
+ combined += txt;
+ if (!txt.endsWith('\n'))
+ combined += '\n';
+ }
+ return combined;
+}
+
+// Extract a NorenRow from one comma-split line, per the exchange's column layout.
+bool extract_row(const QString& ex, const QStringList& c, NorenRow& out) {
+ out.brexchange = ex;
+ if (ex == "NSE" || ex == "BSE") {
+ // Exchange, Token, LotSize, Symbol, TradingSymbol, Instrument, TickSize
+ if (c.size() < 6)
+ return false;
+ out.token = c[1];
+ out.lot_size = c[2].toInt();
+ out.name = c[3];
+ out.brsymbol = c[4];
+ out.raw_instrument = c[5];
+ out.tick_size = (c.size() > 6 ? c[6].toDouble() : 5.0) / 100.0; // paise → rupees
+ return true;
+ }
+ if (ex == "NFO" || ex == "BFO") {
+ // Exchange, Token, LotSize, Symbol, TradingSymbol, Expiry, Instrument, OptionType, StrikePrice, TickSize
+ if (c.size() < 10)
+ return false;
+ out.token = c[1];
+ out.lot_size = c[2].toInt();
+ out.name = c[3];
+ out.brsymbol = c[4];
+ out.expiry_raw = c[5];
+ out.raw_instrument = c[6];
+ out.option_type = c[7];
+ out.strike = c[8].toDouble();
+ out.tick_size = c[9].toDouble();
+ return true;
+ }
+ if (ex == "CDS") {
+ // Exchange, Token, LotSize, Precision, Multiplier, Symbol, TradingSymbol, Expiry, Instrument, OptionType, StrikePrice, TickSize
+ if (c.size() < 12)
+ return false;
+ out.token = c[1];
+ out.lot_size = c[2].toInt();
+ out.name = c[5];
+ out.brsymbol = c[6];
+ out.expiry_raw = c[7];
+ out.raw_instrument = c[8];
+ out.option_type = c[9];
+ out.strike = c[10].toDouble();
+ out.tick_size = c[11].toDouble();
+ return true;
+ }
+ if (ex == "MCX") {
+ // Exchange, Token, LotSize, GNGD, Symbol, TradingSymbol, Expiry, Instrument, OptionType, StrikePrice, TickSize
+ if (c.size() < 11)
+ return false;
+ out.token = c[1];
+ out.lot_size = c[2].toInt();
+ out.name = c[4];
+ out.brsymbol = c[5];
+ out.expiry_raw = c[6];
+ out.raw_instrument = c[7];
+ out.option_type = c[8];
+ out.strike = c[9].toDouble();
+ out.tick_size = c[10].toDouble();
+ return true;
+ }
+ return false;
+}
+
+QVector<Instrument> parse_shoonya(const QByteArray& payload) {
+ QVector<Instrument> out;
+ if (payload.isEmpty())
+ return out;
+
+ const QString text = QString::fromUtf8(payload);
+ const QList<QStringView> lines = QStringView(text).split(u'\n');
+ QString ex;
+ bool skip_header = false;
+ for (const QStringView lv : lines) {
+ const QString line = lv.trimmed().toString();
+ if (line.isEmpty())
+ continue;
+ if (line.startsWith(kMarker)) {
+ ex = line.mid(kMarker.size());
+ skip_header = true; // next line is the file's own header row
+ continue;
+ }
+ if (skip_header) {
+ skip_header = false;
+ continue;
+ }
+ const QStringList c = line.split(',');
+ NorenRow r;
+ if (!extract_row(ex, c, r))
+ continue;
+ if (r.token.toLongLong() == 0)
+ continue;
+ out.append(noren_build(QStringLiteral("shoonya"), r));
+ }
+
+ // BSE indices are not present in the master — Shoonya documents fixed tokens.
+ for (const auto& idx : {qMakePair(QStringLiteral("SENSEX"), QStringLiteral("1")),
+ qMakePair(QStringLiteral("BANKEX"), QStringLiteral("12"))}) {
+ NorenRow r;
+ r.brexchange = "BSE";
+ r.token = idx.second;
+ r.name = idx.first;
+ r.brsymbol = idx.first;
+ r.raw_instrument = "INDEX";
+ r.is_bse_index = true;
+ out.append(noren_build(QStringLiteral("shoonya"), r));
+ }
+
+ LOG_INFO("ShoonyaSource", QString("Parsed %1 Shoonya instruments").arg(out.size()));
+ return out;
+}
+
+} // namespace
+
+void register_shoonya_source() {
+ SymbolResolver::instance().register_source({QStringLiteral("shoonya"),
+ [](const BrokerCredentials& c) { return download_shoonya(c); },
+ [](const QByteArray& p) { return parse_shoonya(p); }});
+}
+
+} // namespace fincept::trading
diff --git a/fincept-qt/src/trading/instruments/parsers/ShoonyaInstrumentSource.h b/fincept-qt/src/trading/instruments/parsers/ShoonyaInstrumentSource.h
new file mode 100644
index 000000000..e89e11de8
--- /dev/null
+++ b/fincept-qt/src/trading/instruments/parsers/ShoonyaInstrumentSource.h
@@ -0,0 +1,7 @@
+#pragma once
+// Shoonya (Finvasia) instrument source. Downloads the 6 per-exchange
+// "<EX>_symbols.txt.zip" masters from api.shoonya.com, unzips, and parses the
+// comma-delimited symbol files (column layout differs per exchange).
+namespace fincept::trading {
+void register_shoonya_source();
+}
diff --git a/fincept-qt/src/trading/instruments/parsers/TradejiniInstrumentParser.cpp b/fincept-qt/src/trading/instruments/parsers/TradejiniInstrumentParser.cpp
new file mode 100644
index 000000000..3aa197466
--- /dev/null
+++ b/fincept-qt/src/trading/instruments/parsers/TradejiniInstrumentParser.cpp
@@ -0,0 +1,181 @@
+#include "trading/instruments/parsers/TradejiniInstrumentParser.h"
+
+#include "core/logging/Logger.h"
+#include "trading/TradingTypes.h"
+#include "trading/instruments/InstrumentDownload.h"
+#include "trading/instruments/InstrumentNormalize.h"
+#include "trading/instruments/InstrumentSource.h"
+#include "trading/instruments/SymbolResolver.h"
+#include "trading/instruments/parsers/CsvUtil.h"
+
+#include <QJsonArray>
+#include <QJsonDocument>
+#include <QJsonObject>
+#include <QStringList>
+#include <QStringView>
+
+namespace fincept::trading {
+namespace {
+
+const QString kBase = QStringLiteral("https://api.tradejini.com/v2/api/mkt-data/scrips/symbol-store");
+const QString kMarker = QStringLiteral("#GRP:");
+
+// Stable fallback group list (used if the store index fetch fails). "Spot" is
+// intentionally excluded.
+const QStringList kFallbackGroups = {"Securities", "FutureContracts", "NSEOptions", "BSEOptions",
+ "CurrencyFuture", "CurrencyOptions", "CommodityFuture", "CommodityOptions",
+ "Index"};
+
+QByteArray download_tradejini(const BrokerCredentials&) {
+ // Step 1: fetch the group list (public; no auth needed for the scrip store).
+ QStringList groups;
+ const QByteArray index = http_get_blocking(kBase + "?version=0");
+ if (!index.isEmpty()) {
+ const QJsonObject root = QJsonDocument::fromJson(index).object();
+ const QJsonArray store = root.value("d").toObject().value("symbolStore").toArray();
+ for (const QJsonValue& g : store) {
+ const QString name = g.toObject().value("name").toString();
+ if (!name.isEmpty() && name.compare("Spot", Qt::CaseInsensitive) != 0)
+ groups << name;
+ }
+ }
+ if (groups.isEmpty())
+ groups = kFallbackGroups;
+
+ // Step 2: fetch each group's CSV, combined with markers.
+ QByteArray combined;
+ for (const QString& g : groups) {
+ const QByteArray csv = http_get_blocking(QString("%1/%2?version=0").arg(kBase, g));
+ if (csv.isEmpty())
+ continue;
+ combined += (kMarker + g + "\n").toUtf8();
+ combined += csv;
+ if (!csv.endsWith('\n'))
+ combined += '\n';
+ }
+ return combined;
+}
+
+QVector<Instrument> parse_tradejini(const QByteArray& payload) {
+ QVector<Instrument> out;
+ if (payload.isEmpty())
+ return out;
+
+ const QString text = QString::fromUtf8(payload);
+ const QList<QStringView> lines = QStringView(text).split(u'\n');
+
+ QString group;
+ QHash<QString, int> idx;
+ bool want_header = false;
+ for (const QStringView lv : lines) {
+ const QString line = lv.trimmed().toString();
+ if (line.isEmpty())
+ continue;
+ if (line.startsWith(kMarker)) {
+ group = line.mid(kMarker.size());
+ want_header = true;
+ continue;
+ }
+ if (want_header) {
+ idx = csv::header_index(line);
+ want_header = false;
+ continue;
+ }
+ const QStringList row = csv::split_csv_line(line);
+ const QString id = csv::field(row, idx, "id");
+ if (id.isEmpty() || id.contains("spot", Qt::CaseInsensitive))
+ continue;
+ const QStringList p = id.split('_');
+
+ // Classify by group.
+ InstrumentType t;
+ if (group == "Securities")
+ t = InstrumentType::EQ;
+ else if (group == "Index")
+ t = InstrumentType::INDEX;
+ else if (group.endsWith("Options"))
+ t = InstrumentType::CE; // refined below from id optType
+ else if (group.endsWith("Future") || group == "FutureContracts")
+ t = InstrumentType::FUT;
+ else
+ continue;
+
+ QString raw_exch;
+ QString base;
+ QString expiry_raw;
+ double strike = 0.0;
+ if (t == InstrumentType::EQ || t == InstrumentType::INDEX) {
+ raw_exch = p.isEmpty() ? QString() : p.last(); // …_<EXCH>
+ base = csv::field(row, idx, "dispName");
+ } else if (t == InstrumentType::FUT) {
+ if (p.size() < 4)
+ continue;
+ base = p[1];
+ raw_exch = p[2];
+ expiry_raw = p[3];
+ } else { // option
+ if (p.size() < 6)
+ continue;
+ base = p[1];
+ raw_exch = p[2];
+ expiry_raw = p[3];
+ strike = p[4].toDouble();
+ t = (p[5].toUpper() == "PE") ? InstrumentType::PE : InstrumentType::CE;
+ }
+ if (raw_exch.isEmpty())
+ continue;
+
+ const QString exch_up = raw_exch.toUpper();
+ Instrument inst;
+ inst.broker_id = "tradejini";
+ inst.brsymbol = id; // the order symId
+ inst.instrument_token = csv::field(row, idx, "excToken").toLongLong();
+ if (inst.instrument_token == 0)
+ inst.instrument_token = norm::stable_token(id);
+ inst.exchange_token = inst.instrument_token;
+ inst.lot_size = qMax(1, csv::field(row, idx, "lot").toInt());
+ const double tick = csv::field(row, idx, "tick").toDouble();
+ inst.tick_size = tick > 0.0 ? tick : 0.05;
+ inst.strike = strike;
+
+ const QString disp = csv::field(row, idx, "dispName");
+ const QString desc = csv::field(row, idx, "desc");
+ inst.instrument_type = t;
+
+ const QString exp_nd = norm::expiry_to_nodash(expiry_raw);
+ inst.expiry = norm::nodash_to_display(exp_nd);
+
+ if (t == InstrumentType::EQ) {
+ inst.name = disp.toUpper();
+ inst.brexchange = exch_up;
+ inst.exchange = norm::normalise_exchange(exch_up, t);
+ inst.symbol = norm::synthesize_symbol(inst.name, t, exp_nd, 0.0, disp);
+ } else if (t == InstrumentType::INDEX) {
+ inst.name = norm::normalise_index_symbol(disp.isEmpty() ? csv::field(row, idx, "symbol") : disp);
+ inst.symbol = inst.name;
+ inst.brexchange = exch_up;
+ inst.exchange = norm::normalise_exchange(exch_up, t);
+ } else {
+ inst.name = base.toUpper();
+ inst.brexchange = exch_up;
+ inst.exchange = norm::normalise_exchange(exch_up, t);
+ inst.symbol = norm::synthesize_symbol(inst.name, t, exp_nd, strike, base);
+ }
+ if (inst.symbol.isEmpty())
+ continue;
+ out.append(inst);
+ }
+
+ LOG_INFO("TradejiniSource", QString("Parsed %1 Tradejini instruments").arg(out.size()));
+ return out;
+}
+
+} // namespace
+
+void register_tradejini_source() {
+ SymbolResolver::instance().register_source({QStringLiteral("tradejini"),
+ [](const BrokerCredentials& c) { return download_tradejini(c); },
+ [](const QByteArray& p) { return parse_tradejini(p); }});
+}
+
+} // namespace fincept::trading
diff --git a/fincept-qt/src/trading/instruments/parsers/TradejiniInstrumentParser.h b/fincept-qt/src/trading/instruments/parsers/TradejiniInstrumentParser.h
new file mode 100644
index 000000000..e8ff0b63f
--- /dev/null
+++ b/fincept-qt/src/trading/instruments/parsers/TradejiniInstrumentParser.h
@@ -0,0 +1,7 @@
+#pragma once
+// Tradejini instrument source. Public symbol-store REST API: a JSON group list,
+// then one CSV per group whose underscore-delimited `id` encodes instrument /
+// exchange / expiry / strike. `id` is stored as brsymbol (the order symId).
+namespace fincept::trading {
+void register_tradejini_source();
+}
diff --git a/fincept-qt/src/trading/instruments/parsers/UpstoxInstrumentParser.cpp b/fincept-qt/src/trading/instruments/parsers/UpstoxInstrumentParser.cpp
new file mode 100644
index 000000000..02fbc0394
--- /dev/null
+++ b/fincept-qt/src/trading/instruments/parsers/UpstoxInstrumentParser.cpp
@@ -0,0 +1,121 @@
+#include "trading/instruments/parsers/UpstoxInstrumentParser.h"
+
+#include "core/logging/Logger.h"
+#include "trading/TradingTypes.h"
+#include "trading/instruments/InstrumentDecompress.h"
+#include "trading/instruments/InstrumentDownload.h"
+#include "trading/instruments/InstrumentNormalize.h"
+#include "trading/instruments/InstrumentSource.h"
+#include "trading/instruments/SymbolResolver.h"
+
+#include <QDateTime>
+#include <QHash>
+#include <QJsonArray>
+#include <QJsonDocument>
+#include <QJsonObject>
+
+namespace fincept::trading {
+namespace {
+
+QByteArray download_upstox(const BrokerCredentials&) {
+ const QByteArray gz =
+ http_get_blocking("https://assets.upstox.com/market-quote/instruments/exchange/complete.json.gz");
+ if (gz.isEmpty())
+ return {};
+ return decompress::gunzip(gz);
+}
+
+// Upstox segment → canonical exchange. Empty result = drop the row (e.g. NSE_COM).
+QString seg_to_exchange(const QString& seg) {
+ static const QHash<QString, QString> m = {
+ {"NSE_EQ", "NSE"}, {"NSE_FO", "NFO"}, {"NCD_FO", "CDS"},
+ {"NSE_INDEX", "NSE_INDEX"}, {"BSE_INDEX", "BSE_INDEX"}, {"BSE_EQ", "BSE"},
+ {"BSE_FO", "BFO"}, {"BCD_FO", "BCD"}, {"MCX_FO", "MCX"},
+ };
+ return m.value(seg.trimmed().toUpper(), QString());
+}
+
+QVector<Instrument> parse_upstox(const QByteArray& json) {
+ QVector<Instrument> out;
+ if (json.isEmpty())
+ return out;
+
+ QJsonParseError err;
+ const QJsonDocument doc = QJsonDocument::fromJson(json, &err);
+ if (err.error != QJsonParseError::NoError || !doc.isArray()) {
+ LOG_ERROR("UpstoxSource", "Upstox master JSON parse failed: " + err.errorString());
+ return out;
+ }
+
+ const QJsonArray arr = doc.array();
+ out.reserve(arr.size());
+ for (const QJsonValue& v : arr) {
+ if (!v.isObject())
+ continue;
+ const QJsonObject o = v.toObject();
+
+ const QString seg = o.value("segment").toString();
+ const QString exch = seg_to_exchange(seg);
+ if (exch.isEmpty())
+ continue; // unsupported segment (commodities spot etc.)
+
+ const QString key = o.value("instrument_key").toString();
+ if (key.isEmpty())
+ continue;
+
+ const QString it_raw = o.value("instrument_type").toString().toUpper();
+ InstrumentType t;
+ if (seg.endsWith("_INDEX", Qt::CaseInsensitive) || it_raw == "INDEX")
+ t = InstrumentType::INDEX;
+ else if (it_raw == "FUT")
+ t = InstrumentType::FUT;
+ else if (it_raw == "CE")
+ t = InstrumentType::CE;
+ else if (it_raw == "PE")
+ t = InstrumentType::PE;
+ else
+ t = InstrumentType::EQ;
+
+ Instrument inst;
+ inst.broker_id = "upstox";
+ inst.broker_token = key;
+ inst.instrument_token = norm::stable_token(key);
+ inst.exchange_token = static_cast<qint64>(o.value("exchange_token").toString().toLongLong());
+ inst.brsymbol = o.value("trading_symbol").toString().trimmed();
+ inst.name = o.value("name").toString().trimmed().toUpper();
+ inst.brexchange = seg.trimmed().toUpper();
+ inst.instrument_type = t;
+ inst.exchange = norm::normalise_exchange(exch, t);
+ inst.strike = o.value("strike_price").toDouble();
+ inst.lot_size = qMax(1, o.value("lot_size").toInt());
+ const double tick = o.value("tick_size").toDouble();
+ inst.tick_size = tick > 0.0 ? tick : 0.05;
+
+ QString exp_nd;
+ const qint64 exp_ms = static_cast<qint64>(o.value("expiry").toDouble());
+ if (exp_ms > 0) {
+ const QDate d = QDateTime::fromMSecsSinceEpoch(exp_ms, Qt::UTC).date();
+ exp_nd = norm::expiry_to_nodash(d.toString("yyyy-MM-dd"));
+ inst.expiry = norm::nodash_to_display(exp_nd);
+ }
+
+ const QString fallback = (t == InstrumentType::EQ) ? inst.brsymbol : inst.name;
+ inst.symbol = norm::synthesize_symbol(inst.name, t, exp_nd, inst.strike, fallback);
+ if (inst.symbol.isEmpty())
+ continue;
+ out.append(inst);
+ }
+
+ LOG_INFO("UpstoxSource", QString("Parsed %1 Upstox instruments").arg(out.size()));
+ return out;
+}
+
+} // namespace
+
+void register_upstox_source() {
+ SymbolResolver::instance().register_source({QStringLiteral("upstox"),
+ [](const BrokerCredentials& c) { return download_upstox(c); },
+ [](const QByteArray& p) { return parse_upstox(p); }});
+}
+
+} // namespace fincept::trading
diff --git a/fincept-qt/src/trading/instruments/parsers/UpstoxInstrumentParser.h b/fincept-qt/src/trading/instruments/parsers/UpstoxInstrumentParser.h
new file mode 100644
index 000000000..6043719a8
--- /dev/null
+++ b/fincept-qt/src/trading/instruments/parsers/UpstoxInstrumentParser.h
@@ -0,0 +1,6 @@
+#pragma once
+// Upstox instrument source. Public gzip-compressed JSON master (all exchanges).
+// Token is the alphanumeric instrument_key (kept in broker_token).
+namespace fincept::trading {
+void register_upstox_source();
+}
diff --git a/fincept-qt/src/trading/instruments/parsers/XtsInstrumentParser.cpp b/fincept-qt/src/trading/instruments/parsers/XtsInstrumentParser.cpp
new file mode 100644
index 000000000..fd6e96703
--- /dev/null
+++ b/fincept-qt/src/trading/instruments/parsers/XtsInstrumentParser.cpp
@@ -0,0 +1,224 @@
+#include "trading/instruments/parsers/XtsInstrumentParser.h"
+
+#include "core/logging/Logger.h"
+#include "trading/TradingTypes.h"
+#include "trading/instruments/InstrumentDownload.h"
+#include "trading/instruments/InstrumentNormalize.h"
+#include "trading/instruments/InstrumentSource.h"
+#include "trading/instruments/SymbolResolver.h"
+
+#include <QJsonArray>
+#include <QJsonDocument>
+#include <QJsonObject>
+#include <QStringList>
+#include <QStringView>
+
+namespace fincept::trading {
+namespace {
+
+const QString kMd = QStringLiteral("https://ttblaze.iifl.com/apimarketdata");
+const QString kSegMarker = QStringLiteral("#SEG:");
+const QString kIdxMarker = QStringLiteral("#IDX:");
+
+const QStringList kSegments = {"NSECM", "NSECD", "NSEFO", "BSECM", "BSEFO", "MCXFO"};
+
+QByteArray download_iifl(const BrokerCredentials& creds) {
+ // access_token packed: trade_token:::feed_token
+ const QStringList parts = creds.access_token.split(":::");
+ const QString feed = parts.size() > 1 ? parts[1] : QString();
+ if (feed.isEmpty()) {
+ LOG_WARN("XtsSource", "IIFL feed token unavailable — cannot fetch master");
+ return {};
+ }
+ const QMap<QString, QString> headers = {{"authorization", feed}, {"Accept", "application/json"}};
+
+ QByteArray combined;
+ for (const QString& seg : kSegments) {
+ QJsonObject body;
+ body["exchangeSegmentList"] = QJsonArray{seg};
+ const QByteArray resp = http_post_blocking(kMd + "/instruments/master",
+ QJsonDocument(body).toJson(QJsonDocument::Compact),
+ "application/json", headers, 60000);
+ if (resp.isEmpty())
+ continue;
+ const QJsonObject o = QJsonDocument::fromJson(resp).object();
+ if (o.value("type").toString() != "success")
+ continue;
+ const QString result = o.value("result").toString();
+ if (result.isEmpty())
+ continue;
+ combined += (kSegMarker + seg + "\n").toUtf8();
+ combined += result.toUtf8();
+ combined += '\n';
+ }
+
+ // Index lists (NSE=1, BSE=11).
+ for (const QString& xseg : {QStringLiteral("1"), QStringLiteral("11")}) {
+ const QByteArray resp =
+ http_get_blocking(kMd + "/instruments/indexlist?exchangeSegment=" + xseg, headers, 30000);
+ if (resp.isEmpty())
+ continue;
+ const QJsonArray list =
+ QJsonDocument::fromJson(resp).object().value("result").toObject().value("indexList").toArray();
+ if (list.isEmpty())
+ continue;
+ combined += (kIdxMarker + xseg + "\n").toUtf8();
+ for (const QJsonValue& v : list) {
+ combined += v.toString().toUtf8();
+ combined += '\n';
+ }
+ }
+ return combined;
+}
+
+QString seg_exchange(const QString& seg) {
+ if (seg == "NSECM")
+ return "NSE";
+ if (seg == "BSECM")
+ return "BSE";
+ if (seg == "NSEFO")
+ return "NFO";
+ if (seg == "NSECD")
+ return "CDS";
+ if (seg == "BSEFO")
+ return "BFO";
+ if (seg == "MCXFO")
+ return "MCX";
+ return {};
+}
+
+QVector<Instrument> parse_iifl(const QByteArray& payload) {
+ QVector<Instrument> out;
+ if (payload.isEmpty())
+ return out;
+
+ const QString text = QString::fromUtf8(payload);
+ const QList<QStringView> lines = QStringView(text).split(u'\n');
+
+ QString seg; // current market-data segment
+ QString idx_seg; // current index-list segment ("1"/"11")
+ for (const QStringView lv : lines) {
+ const QString line = lv.trimmed().toString();
+ if (line.isEmpty())
+ continue;
+ if (line.startsWith(kSegMarker)) {
+ seg = line.mid(kSegMarker.size());
+ idx_seg.clear();
+ continue;
+ }
+ if (line.startsWith(kIdxMarker)) {
+ idx_seg = line.mid(kIdxMarker.size());
+ seg.clear();
+ continue;
+ }
+
+ if (!idx_seg.isEmpty()) {
+ // Index list line: "NIFTY 50_26000" → name + token (split on last '_').
+ const int us = line.lastIndexOf('_');
+ if (us <= 0)
+ continue;
+ const QString name = line.left(us);
+ const QString token = line.mid(us + 1);
+ Instrument inst;
+ inst.broker_id = "iifl";
+ inst.instrument_token = token.toLongLong();
+ if (inst.instrument_token == 0)
+ inst.instrument_token = norm::stable_token(name);
+ inst.exchange_token = inst.instrument_token;
+ inst.instrument_type = InstrumentType::INDEX;
+ inst.name = norm::normalise_index_symbol(name);
+ inst.symbol = inst.name;
+ inst.brsymbol = name;
+ inst.brexchange = (idx_seg == "11") ? "BSE" : "NSE";
+ inst.exchange = (idx_seg == "11") ? "BSE_INDEX" : "NSE_INDEX";
+ inst.lot_size = 1;
+ inst.tick_size = 0.05;
+ out.append(inst);
+ continue;
+ }
+
+ if (seg.isEmpty())
+ continue;
+ const QStringList c = line.split('|');
+ if (c.size() < 13)
+ continue;
+
+ const QString exch = seg_exchange(seg);
+ const bool is_fo = (seg == "NSEFO" || seg == "NSECD" || seg == "BSEFO" || seg == "MCXFO");
+
+ Instrument inst;
+ inst.broker_id = "iifl";
+ inst.instrument_token = c[1].toLongLong();
+ inst.exchange_token = inst.instrument_token;
+ inst.name = c[3].trimmed().toUpper();
+ inst.lot_size = qMax(1, c[12].toInt());
+ const double tick = c[11].toDouble();
+ inst.tick_size = tick > 0.0 ? tick : 0.05;
+ inst.brexchange = seg;
+
+ if (!is_fo) {
+ const QString series = c.value(5).trimmed().toUpper();
+ if (series == "EQ" || series == "BE") {
+ inst.instrument_type = InstrumentType::EQ;
+ inst.brsymbol = c.value(14, c[3]);
+ inst.exchange = exch;
+ inst.symbol = norm::strip_eq_suffix(inst.name);
+ } else if (series == "SPOT") {
+ inst.instrument_type = InstrumentType::INDEX;
+ inst.brsymbol = c.value(14, c[3]);
+ inst.exchange = norm::normalise_exchange(exch, InstrumentType::INDEX);
+ inst.symbol = norm::normalise_index_symbol(inst.name);
+ } else {
+ continue;
+ }
+ if (inst.symbol.isEmpty())
+ continue;
+ out.append(inst);
+ continue;
+ }
+
+ // F&O: need the extended columns.
+ if (c.size() < 20)
+ continue;
+ const QString expiry_raw = c[16];
+ if (expiry_raw == "1") // MCXFO junk/spot rows
+ continue;
+ const double strike = c[17].toDouble();
+ const QString opt = c[18].trimmed();
+ InstrumentType t;
+ if (opt == "3")
+ t = InstrumentType::CE;
+ else if (opt == "4")
+ t = InstrumentType::PE;
+ else if (opt == "1")
+ t = InstrumentType::FUT;
+ else { // CDS inconsistency → infer from description suffix
+ const QString d = c[4].trimmed().toUpper();
+ t = d.endsWith("CE") ? InstrumentType::CE : d.endsWith("PE") ? InstrumentType::PE : InstrumentType::FUT;
+ }
+
+ inst.instrument_type = t;
+ inst.strike = (t == InstrumentType::FUT) ? 0.0 : strike;
+ inst.brsymbol = c.value(19, c[4]); // DisplayName, fallback Description
+ const QString exp_nd = norm::expiry_to_nodash(expiry_raw);
+ inst.expiry = norm::nodash_to_display(exp_nd);
+ inst.exchange = norm::normalise_exchange(exch, t);
+ inst.symbol = norm::synthesize_symbol(inst.name, t, exp_nd, inst.strike, inst.name);
+ if (inst.symbol.isEmpty())
+ continue;
+ out.append(inst);
+ }
+
+ LOG_INFO("XtsSource", QString("Parsed %1 IIFL instruments").arg(out.size()));
+ return out;
+}
+
+} // namespace
+
+void register_iifl_source() {
+ SymbolResolver::instance().register_source({QStringLiteral("iifl"),
+ [](const BrokerCredentials& c) { return download_iifl(c); },
+ [](const QByteArray& p) { return parse_iifl(p); }});
+}
+
+} // namespace fincept::trading
diff --git a/fincept-qt/src/trading/instruments/parsers/XtsInstrumentParser.h b/fincept-qt/src/trading/instruments/parsers/XtsInstrumentParser.h
new file mode 100644
index 000000000..776584987
--- /dev/null
+++ b/fincept-qt/src/trading/instruments/parsers/XtsInstrumentParser.h
@@ -0,0 +1,8 @@
+#pragma once
+// IIFL (XTS / Symphony Fintech) instrument source. Authenticated market-data
+// API: POST /instruments/master per exchange segment (pipe-delimited text) plus
+// /indexlist. The market-data feed token is unpacked from the account's
+// :::-packed access_token (trade_token:::feed_token).
+namespace fincept::trading {
+void register_iifl_source();
+}
diff --git a/fincept-qt/src/trading/websocket/DhanWebSocket.cpp b/fincept-qt/src/trading/websocket/DhanWebSocket.cpp
index 206280c3f..cb28c87be 100644
--- a/fincept-qt/src/trading/websocket/DhanWebSocket.cpp
+++ b/fincept-qt/src/trading/websocket/DhanWebSocket.cpp
@@ -100,7 +100,11 @@ void DhanWebSocket::open() {
// 5-depth endpoint. authType=2 + token + clientId in the query string.
QString url = QString("%1?version=2&token=%2&clientId=%3&authType=2")
.arg(QString(kFiveDepthUrl), access_token_, client_id_);
- LOG_INFO(TAG_DHAN_WS, "Connecting to Dhan 5-depth feed");
+ // Log the connection params with the token redacted — never log the JWT.
+ const QString tok_tail = access_token_.size() > 6 ? access_token_.right(6) : QStringLiteral("??????");
+ LOG_INFO(TAG_DHAN_WS, QString("Connecting to Dhan 5-depth feed (clientId=%1, token=…%2, len=%3)")
+ .arg(client_id_, tok_tail)
+ .arg(access_token_.size()));
ws_->connect_to(url);
start_health_check();
}
@@ -474,16 +478,62 @@ BrokerQuote DhanWebSocket::parse_full(const uchar* payload, int len, int segment
return q;
}
-void DhanWebSocket::handle_disconnect(const uchar* payload, int len) const {
+void DhanWebSocket::handle_disconnect(const uchar* payload, int len) {
if (len < 2) {
LOG_WARN(TAG_DHAN_WS, "Received disconnect packet (no code)");
return;
}
const quint16 code = read_u16(payload);
- QString reason = QStringLiteral("Unknown reason");
- if (code == 805)
- reason = QStringLiteral("Maximum websocket connections exceeded");
+
+ // Disconnect codes per DhanHQ v2 live-market-feed docs.
+ QString reason;
+ bool fatal = false; // retrying won't help → stop the reconnect timer
+ bool token_problem = false; // genuine token/auth failure → surface as TOKEN_EXPIRED
+ switch (code) {
+ case 805:
+ reason = QStringLiteral("Connection limit exceeded (max 5 connections per Client ID)");
+ break;
+ case 806:
+ // Entitlement gap, NOT a token problem: the account is valid for
+ // trading but the market-data (Data API) feed isn't subscribed.
+ // Reconnecting won't help, but the account must stay Connected and
+ // must NOT be reported as an expired token.
+ reason = QStringLiteral("Market data feed not subscribed (Dhan Data API) — quotes unavailable; "
+ "trading is unaffected. Enable the Data API subscription on dhan.co.");
+ fatal = true;
+ break;
+ case 807:
+ reason = QStringLiteral("Access token expired");
+ fatal = true;
+ token_problem = true;
+ break;
+ case 808:
+ reason = QStringLiteral("Authentication failed — invalid Client ID or token");
+ fatal = true;
+ token_problem = true;
+ break;
+ case 809:
+ reason = QStringLiteral("Access token invalid");
+ fatal = true;
+ token_problem = true;
+ break;
+ default:
+ reason = QStringLiteral("Unknown reason");
+ break;
+ }
LOG_WARN(TAG_DHAN_WS, QString("Disconnect packet code=%1 (%2)").arg(code).arg(reason));
+
+ if (fatal)
+ ws_->stop_reconnect(); // no point storming reconnects on any fatal code
+
+ if (token_problem) {
+ // The [TOKEN_EXPIRED] sentinel routes through AccountDataStream's
+ // check_token_expiry() to mark the account TokenExpired and prompt re-auth.
+ emit error_occurred(QString("[TOKEN_EXPIRED] Dhan feed disconnect %1: %2").arg(code).arg(reason));
+ } else if (fatal) {
+ // Surfaced as a plain (non-expiry) error so the account stays Connected.
+ emit error_occurred(QString("Dhan feed disconnect %1: %2").arg(code).arg(reason));
+ }
}
} // namespace fincept::trading
diff --git a/fincept-qt/src/trading/websocket/DhanWebSocket.h b/fincept-qt/src/trading/websocket/DhanWebSocket.h
index 3be88950f..2fa46d27a 100644
--- a/fincept-qt/src/trading/websocket/DhanWebSocket.h
+++ b/fincept-qt/src/trading/websocket/DhanWebSocket.h
@@ -112,7 +112,7 @@ class DhanWebSocket : public BrokerWebSocketBase {
BrokerQuote parse_quote(const uchar* payload, int len, int segment, quint32 security_id) const;
BrokerQuote parse_full(const uchar* payload, int len, int segment, quint32 security_id,
MarketDepth& depth_out, bool& has_depth) const;
- void handle_disconnect(const uchar* payload, int len) const;
+ void handle_disconnect(const uchar* payload, int len);
// Enrich symbol/exchange for a security id via InstrumentService.
QString symbol_for_security(quint32 security_id, const QString& fallback) const;
diff --git a/fincept-qt/src/trading/websocket/IciciDirectWebSocket.cpp b/fincept-qt/src/trading/websocket/IciciDirectWebSocket.cpp
new file mode 100644
index 000000000..21db6316b
--- /dev/null
+++ b/fincept-qt/src/trading/websocket/IciciDirectWebSocket.cpp
@@ -0,0 +1,319 @@
+// IciciDirectWebSocket — ICICI Direct (Breeze) Socket.IO market-data adapter.
+//
+// Breeze SDK references (python-socketio): the live feed connects to
+// wss://livestream.icicidirect.com/socket.io/?EIO=4&transport=websocket
+// with auth={"user":user_id,"token":session_key} sent in the Socket.IO CONNECT
+// packet, subscribes via emit('join', "<exch>.1!<token>"), and receives ticks on
+// the 'stock' event as a positional list (parse_data field order replicated below).
+
+#include "trading/websocket/IciciDirectWebSocket.h"
+
+#include "core/logging/Logger.h"
+#include "network/websocket/WebSocketClient.h"
+#include "trading/instruments/InstrumentService.h"
+
+#include <QByteArray>
+#include <QDateTime>
+#include <QJsonDocument>
+#include <QJsonObject>
+#include <QJsonValue>
+
+namespace fincept::trading {
+
+static constexpr const char* TAG_ICICI_WS = "IciciWS";
+
+namespace {
+
+// Breeze stock-token exchange prefix. The same number appears in inbound ticks'
+// data[0] ("<exch>.<type>!<token>").
+int breeze_exch_code(const QString& exchange) {
+ const QString ex = exchange.toUpper();
+ if (ex == "BSE")
+ return 1;
+ if (ex == "BFO")
+ return 8;
+ if (ex == "MCX")
+ return 13;
+ if (ex == "NDX")
+ return 6;
+ // NSE cash + NFO derivatives share segment 4.
+ return 4;
+}
+
+// Breeze tick list values arrive as JSON numbers OR numeric strings.
+double jval(const QJsonValue& v) {
+ if (v.isDouble())
+ return v.toDouble();
+ return v.toString().toDouble();
+}
+
+} // namespace
+
+IciciDirectWebSocket::IciciDirectWebSocket(const QString& session_token_b64, const QString& user_id, QObject* parent)
+ : BrokerWebSocketBase(parent), user_(user_id) {
+ // The stored access_token is base64("user_id:session_key"); recover the raw
+ // session_key (and user id, if not supplied) for the Socket.IO auth payload.
+ const QString decoded = QString::fromUtf8(QByteArray::fromBase64(session_token_b64.toUtf8()));
+ if (decoded.contains(':')) {
+ if (user_.isEmpty())
+ user_ = decoded.section(':', 0, 0);
+ session_key_ = decoded.section(':', 1);
+ } else {
+ session_key_ = session_token_b64; // fallback: already a raw key
+ }
+
+ ws_ = new WebSocketClient(this);
+ connect(ws_, &WebSocketClient::connected, this, &IciciDirectWebSocket::on_ws_connected);
+ connect(ws_, &WebSocketClient::disconnected, this, &IciciDirectWebSocket::on_ws_disconnected);
+ connect(ws_, &WebSocketClient::message_received, this, &IciciDirectWebSocket::on_ws_message);
+ connect(ws_, &WebSocketClient::error_occurred, this, &IciciDirectWebSocket::error_occurred);
+}
+
+IciciDirectWebSocket::~IciciDirectWebSocket() = default;
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Lifecycle
+// ─────────────────────────────────────────────────────────────────────────────
+
+void IciciDirectWebSocket::open() {
+ sio_connected_ = false;
+ // Engine.IO v4 over WebSocket; auth is sent later in the SIO CONNECT packet.
+ const QString url =
+ QStringLiteral("wss://livestream.icicidirect.com/socket.io/?EIO=4&transport=websocket");
+ LOG_INFO(TAG_ICICI_WS, "Connecting to ICICI Breeze Socket.IO");
+ ws_->connect_to(url);
+ start_health_check();
+}
+
+void IciciDirectWebSocket::close() {
+ stop_health_check();
+ sio_connected_ = false;
+ if (ws_->is_connected()) {
+ if (!subscribed_tokens_.isEmpty())
+ send_leave(QVector<qint64>(subscribed_tokens_.begin(), subscribed_tokens_.end()));
+ ws_->send(QStringLiteral("41")); // Socket.IO disconnect
+ }
+ ws_->disconnect();
+}
+
+bool IciciDirectWebSocket::is_connected() const {
+ return ws_->is_connected() && sio_connected_;
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Subscription
+// ─────────────────────────────────────────────────────────────────────────────
+
+void IciciDirectWebSocket::subscribe(const QVector<qint64>& tokens) {
+ QVector<qint64> new_tokens;
+ for (qint64 t : tokens) {
+ if (!subscribed_tokens_.contains(t)) {
+ subscribed_tokens_.insert(t);
+ new_tokens.append(t);
+ }
+ }
+ if (!new_tokens.isEmpty() && sio_connected_)
+ send_join(new_tokens);
+}
+
+void IciciDirectWebSocket::unsubscribe() {
+ if (subscribed_tokens_.isEmpty())
+ return;
+ if (sio_connected_)
+ send_leave(QVector<qint64>(subscribed_tokens_.begin(), subscribed_tokens_.end()));
+ subscribed_tokens_.clear();
+ clear_tick_cache();
+}
+
+void IciciDirectWebSocket::unsubscribe(const QVector<qint64>& tokens) {
+ QVector<qint64> to_remove;
+ for (qint64 t : tokens) {
+ if (subscribed_tokens_.remove(t))
+ to_remove.append(t);
+ }
+ if (!to_remove.isEmpty() && sio_connected_)
+ send_leave(to_remove);
+}
+
+void IciciDirectWebSocket::on_data_stall() {
+ LOG_WARN(TAG_ICICI_WS, "Data stall — forcing reconnect");
+ sio_connected_ = false;
+ ws_->disconnect();
+ open();
+}
+
+QString IciciDirectWebSocket::stock_token_for(qint64 token) const {
+ QString exchange = QStringLiteral("NSE");
+ auto inst = InstrumentService::instance().find_by_token(static_cast<quint32>(token), "icicidirect");
+ if (inst.has_value()) {
+ const QString& ex = inst->brexchange.isEmpty() ? inst->exchange : inst->brexchange;
+ if (!ex.isEmpty())
+ exchange = ex;
+ }
+ // ".1" selects the quotes feed (".2" would be market depth).
+ return QStringLiteral("%1.1!%2").arg(breeze_exch_code(exchange)).arg(token);
+}
+
+void IciciDirectWebSocket::send_join(const QVector<qint64>& tokens) {
+ if (tokens.isEmpty())
+ return;
+ QJsonArray toks;
+ for (qint64 t : tokens)
+ toks.append(stock_token_for(t));
+ const QJsonArray event{QStringLiteral("join"), toks};
+ ws_->send(QStringLiteral("42") + QString::fromUtf8(QJsonDocument(event).toJson(QJsonDocument::Compact)));
+ LOG_INFO(TAG_ICICI_WS, QString("Subscribed %1 tokens").arg(tokens.size()));
+}
+
+void IciciDirectWebSocket::send_leave(const QVector<qint64>& tokens) {
+ if (tokens.isEmpty())
+ return;
+ QJsonArray toks;
+ for (qint64 t : tokens)
+ toks.append(stock_token_for(t));
+ const QJsonArray event{QStringLiteral("leave"), toks};
+ ws_->send(QStringLiteral("42") + QString::fromUtf8(QJsonDocument(event).toJson(QJsonDocument::Compact)));
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Engine.IO / Socket.IO framing
+// ─────────────────────────────────────────────────────────────────────────────
+
+void IciciDirectWebSocket::on_ws_connected() {
+ LOG_INFO(TAG_ICICI_WS, "WebSocket transport open — awaiting Engine.IO handshake");
+}
+
+void IciciDirectWebSocket::on_ws_disconnected() {
+ LOG_WARN(TAG_ICICI_WS, "Disconnected");
+ sio_connected_ = false;
+ emit disconnected();
+}
+
+void IciciDirectWebSocket::on_ws_message(const QString& message) {
+ if (!message.isEmpty())
+ handle_engineio(message);
+}
+
+void IciciDirectWebSocket::handle_engineio(const QString& packet) {
+ const QChar type = packet.at(0);
+ const QString rest = packet.mid(1);
+
+ switch (type.toLatin1()) {
+ case '0': { // Engine.IO open → Socket.IO CONNECT with auth payload.
+ QJsonObject auth{{"user", user_}, {"token", session_key_}};
+ ws_->send(QStringLiteral("40") +
+ QString::fromUtf8(QJsonDocument(auth).toJson(QJsonDocument::Compact)));
+ break;
+ }
+ case '2': // ping → pong
+ ws_->send(QStringLiteral("3"));
+ break;
+ case '3': // pong — ignore
+ break;
+ case '4': { // Socket.IO message; second char is the SIO packet type.
+ if (rest.isEmpty())
+ break;
+ const QChar sio_type = rest.at(0);
+ const QString sio_rest = rest.mid(1);
+ switch (sio_type.toLatin1()) {
+ case '0': // CONNECT ack — namespace joined.
+ LOG_INFO(TAG_ICICI_WS, "Socket.IO connected");
+ sio_connected_ = true;
+ emit connected();
+ if (!subscribed_tokens_.isEmpty())
+ send_join(QVector<qint64>(subscribed_tokens_.begin(), subscribed_tokens_.end()));
+ break;
+ case '1': // DISCONNECT
+ LOG_WARN(TAG_ICICI_WS, "Socket.IO disconnected");
+ sio_connected_ = false;
+ break;
+ case '2': // EVENT — ["event", data]
+ handle_socketio_event(sio_rest);
+ break;
+ case '4': // CONNECT_ERROR
+ LOG_ERROR(TAG_ICICI_WS, QString("Socket.IO connect error: %1").arg(sio_rest.left(200)));
+ emit error_occurred(QStringLiteral("ICICI Socket.IO connect error"));
+ break;
+ default:
+ break;
+ }
+ break;
+ }
+ default:
+ break;
+ }
+}
+
+void IciciDirectWebSocket::handle_socketio_event(const QString& payload) {
+ // Optional leading ack-id digits before the JSON array — skip them.
+ int start = 0;
+ while (start < payload.size() && payload.at(start).isDigit())
+ ++start;
+
+ QJsonParseError err;
+ const QJsonDocument doc = QJsonDocument::fromJson(payload.mid(start).toUtf8(), &err);
+ if (err.error != QJsonParseError::NoError || !doc.isArray())
+ return;
+
+ const QJsonArray arr = doc.array();
+ if (arr.isEmpty())
+ return;
+
+ const QString event = arr.at(0).toString();
+ if (event == QStringLiteral("stock")) // tick feed; "order" notifications ignored for now
+ handle_tick(arr.size() > 1 ? arr.at(1).toArray() : QJsonArray());
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Tick parsing — Breeze 'stock' positional list (parse_data field order)
+// ─────────────────────────────────────────────────────────────────────────────
+
+void IciciDirectWebSocket::handle_tick(const QJsonArray& data) {
+ if (data.isEmpty())
+ return;
+ note_tick();
+
+ // data[0] = "<exch>.<type>!<token>"
+ const QString tok_str = data.at(0).toString();
+ const int bang = tok_str.indexOf('!');
+ const qint64 token = bang >= 0 ? tok_str.mid(bang + 1).toLongLong() : 0;
+
+ QString symbol = tok_str;
+ auto inst = InstrumentService::instance().find_by_token(static_cast<quint32>(token), "icicidirect");
+ if (inst.has_value())
+ symbol = inst->symbol;
+
+ const int n = data.size();
+ BrokerQuote q;
+ q.symbol = symbol;
+ q.open = jval(data.at(1));
+ q.ltp = jval(data.at(2));
+ q.high = jval(data.at(3));
+ q.low = jval(data.at(4));
+ q.bid = jval(data.at(6));
+ q.bid_size = jval(data.at(7));
+ q.ask = jval(data.at(8));
+ q.ask_size = jval(data.at(9));
+
+ // NSE/BSE cash = 21 fields (ttq@12, close@20); F&O = 23 fields (OI@12,
+ // CHNGOI@13, ttq@14, close@22).
+ if (n >= 23) {
+ q.oi = static_cast<qint64>(jval(data.at(12)));
+ q.volume = jval(data.at(14));
+ q.close = jval(data.at(22));
+ } else if (n >= 21) {
+ q.volume = jval(data.at(12));
+ q.close = jval(data.at(20));
+ }
+
+ if (q.close > 0) {
+ q.change = q.ltp - q.close;
+ q.change_pct = (q.ltp - q.close) / q.close * 100.0;
+ }
+ q.timestamp = QDateTime::currentMSecsSinceEpoch();
+
+ // Partial frames omit unchanged fields → preserve via merge_tick.
+ emit tick_received(merge_tick(QString::number(token), q));
+}
+
+} // namespace fincept::trading
diff --git a/fincept-qt/src/trading/websocket/IciciDirectWebSocket.h b/fincept-qt/src/trading/websocket/IciciDirectWebSocket.h
new file mode 100644
index 000000000..ced31adb8
--- /dev/null
+++ b/fincept-qt/src/trading/websocket/IciciDirectWebSocket.h
@@ -0,0 +1,67 @@
+#pragma once
+// IciciDirectWebSocket — ICICI Direct (Breeze) live market-data adapter.
+//
+// Breeze streams over Socket.IO (Engine.IO v4) on WebSocket transport, unlike
+// the raw-WebSocket brokers. The handshake/framing mirrors IIFLWebSocket; the
+// differences are:
+// • auth travels in the Socket.IO CONNECT packet as {"user":id,"token":key}
+// (not the URL query string),
+// • subscribe/unsubscribe are Socket.IO emits — 42["join", <tokens>] /
+// 42["leave", <tokens>] — where each token is "<exch>.1!<instrument_token>",
+// • ticks arrive on the "stock" event as a POSITIONAL list (not an object).
+//
+// Tokens come from AccountDataStream as numeric ICICI instrument tokens; we map
+// token↔symbol/exchange via InstrumentService ("icicidirect").
+
+#include "trading/websocket/BrokerWebSocketBase.h"
+
+#include <QJsonArray>
+#include <QSet>
+#include <QString>
+
+namespace fincept {
+class WebSocketClient;
+}
+
+namespace fincept::trading {
+
+class IciciDirectWebSocket : public BrokerWebSocketBase {
+ Q_OBJECT
+ public:
+ /// `session_token_b64` is the base64 "user_id:session_key" stored as the
+ /// broker access_token; `user_id` is the ICICI user id (either may seed the
+ /// other — we decode the base64 to recover the raw session_key for auth).
+ IciciDirectWebSocket(const QString& session_token_b64, const QString& user_id, QObject* parent = nullptr);
+ ~IciciDirectWebSocket() override;
+
+ void open() override;
+ void close() override;
+ bool is_connected() const override;
+ void subscribe(const QVector<qint64>& tokens) override;
+ void unsubscribe() override;
+ void unsubscribe(const QVector<qint64>& tokens);
+
+ protected:
+ void on_data_stall() override;
+
+ private slots:
+ void on_ws_connected();
+ void on_ws_disconnected();
+ void on_ws_message(const QString& message);
+
+ private:
+ void handle_engineio(const QString& packet);
+ void handle_socketio_event(const QString& payload);
+ void handle_tick(const QJsonArray& data);
+ void send_join(const QVector<qint64>& tokens);
+ void send_leave(const QVector<qint64>& tokens);
+ QString stock_token_for(qint64 token) const;
+
+ fincept::WebSocketClient* ws_ = nullptr;
+ QString user_;
+ QString session_key_;
+ bool sio_connected_ = false;
+ QSet<qint64> subscribed_tokens_;
+};
+
+} // namespace fincept::trading
diff --git a/fincept-qt/src/ui/widgets/algo/BacktestReportPanel.cpp b/fincept-qt/src/ui/widgets/algo/BacktestReportPanel.cpp
new file mode 100644
index 000000000..a06f05835
--- /dev/null
+++ b/fincept-qt/src/ui/widgets/algo/BacktestReportPanel.cpp
@@ -0,0 +1,374 @@
+// src/ui/widgets/algo/BacktestReportPanel.cpp
+#include "ui/widgets/algo/BacktestReportPanel.h"
+
+#include <QChart>
+#include <QChartView>
+#include <QColor>
+#include <QFont>
+#include <QGridLayout>
+#include <QHeaderView>
+#include <QJsonArray>
+#include <QLabel>
+#include <QLegend>
+#include <QLineSeries>
+#include <QMap>
+#include <QMargins>
+#include <QPainter>
+#include <QPen>
+#include <QTableWidget>
+#include <QTableWidgetItem>
+#include <QValueAxis>
+#include <QVBoxLayout>
+
+#include <algorithm>
+#include <cmath>
+#include <limits>
+
+namespace fincept::ui::algo {
+
+namespace {
+constexpr char kPos[] = "#16A34A";
+constexpr char kNeg[] = "#DC2626";
+
+QChartView* make_chart_view(QChart* chart) {
+ chart->legend()->hide();
+ chart->setBackgroundBrush(QColor("#0E0E0E"));
+ chart->setMargins(QMargins(4, 4, 4, 4));
+ auto* view = new QChartView(chart);
+ view->setRenderHint(QPainter::Antialiasing);
+ view->setMinimumHeight(150);
+ return view;
+}
+
+void style_axis(QValueAxis* ax) {
+ ax->setLabelsColor(QColor("#9CA3AF"));
+ ax->setGridLineColor(QColor("#1F2937"));
+ ax->setLinePenColor(QColor("#374151"));
+ ax->setLabelsFont(QFont(QStringLiteral("monospace"), 7));
+}
+} // namespace
+
+BacktestReportPanel::BacktestReportPanel(QWidget* parent) : QWidget(parent) {
+ setObjectName(QStringLiteral("backtestReportPanel"));
+ auto* root = new QVBoxLayout(this);
+ root->setContentsMargins(0, 0, 0, 0);
+ root->setSpacing(8);
+
+ placeholder_ = new QLabel(tr("Run a backtest to see performance, equity curve and trades."), this);
+ placeholder_->setObjectName(QStringLiteral("builderChartLabel"));
+ placeholder_->setAlignment(Qt::AlignCenter);
+ placeholder_->setWordWrap(true);
+ placeholder_->setMinimumHeight(120);
+ root->addWidget(placeholder_);
+
+ body_ = new QWidget(this);
+ auto* body_layout = new QVBoxLayout(body_);
+ body_layout->setContentsMargins(0, 0, 0, 0);
+ body_layout->setSpacing(8);
+ body_layout->addWidget(build_kpis());
+ body_layout->addWidget(build_charts());
+ body_layout->addWidget(build_heatmap());
+ body_layout->addWidget(build_trades(), 1);
+ body_->setVisible(false);
+ root->addWidget(body_, 1);
+}
+
+void BacktestReportPanel::add_kpi(QGridLayout* grid, int row, int col,
+ const QString& key, const QString& title) {
+ auto* card = new QWidget(this);
+ card->setObjectName(QStringLiteral("kpiCard"));
+ auto* l = new QVBoxLayout(card);
+ l->setContentsMargins(8, 6, 8, 6);
+ l->setSpacing(2);
+ auto* t = new QLabel(title, card);
+ t->setObjectName(QStringLiteral("kpiTitle"));
+ auto* v = new QLabel(QStringLiteral("--"), card);
+ v->setObjectName(QStringLiteral("kpiValue"));
+ auto* s = new QLabel(card);
+ s->setObjectName(QStringLiteral("kpiSub"));
+ l->addWidget(t);
+ l->addWidget(v);
+ l->addWidget(s);
+ grid->addWidget(card, row, col);
+ kpi_val_[key] = v;
+ kpi_sub_[key] = s;
+}
+
+QWidget* BacktestReportPanel::build_kpis() {
+ auto* w = new QWidget(this);
+ auto* grid = new QGridLayout(w);
+ grid->setSpacing(8);
+ add_kpi(grid, 0, 0, "total_return", tr("TOTAL RETURN"));
+ add_kpi(grid, 0, 1, "sharpe", tr("SHARPE"));
+ add_kpi(grid, 0, 2, "sortino", tr("SORTINO"));
+ add_kpi(grid, 0, 3, "max_dd", tr("MAX DRAWDOWN"));
+ add_kpi(grid, 1, 0, "calmar", tr("CALMAR"));
+ add_kpi(grid, 1, 1, "win_rate", tr("WIN RATE"));
+ add_kpi(grid, 1, 2, "profit_factor", tr("PROFIT FACTOR"));
+ add_kpi(grid, 1, 3, "trades", tr("TRADES"));
+ add_kpi(grid, 2, 0, "expectancy", tr("EXPECTANCY"));
+ add_kpi(grid, 2, 1, "avg_bars", tr("AVG BARS HELD"));
+ return w;
+}
+
+QWidget* BacktestReportPanel::build_charts() {
+ auto* w = new QWidget(this);
+ auto* l = new QVBoxLayout(w);
+ l->setContentsMargins(0, 0, 0, 0);
+ l->setSpacing(6);
+
+ // Equity curve
+ equity_chart_ = new QChart();
+ equity_chart_->setTitle(tr("Equity Curve"));
+ equity_chart_->setTitleBrush(QColor("#E5E7EB"));
+ equity_series_ = new QLineSeries();
+ equity_series_->setName(tr("Strategy"));
+ equity_series_->setColor(QColor("#3B82F6"));
+ equity_chart_->addSeries(equity_series_);
+ benchmark_series_ = new QLineSeries();
+ benchmark_series_->setName(tr("Buy & Hold"));
+ QPen bpen(QColor("#9CA3AF"));
+ bpen.setStyle(Qt::DashLine);
+ benchmark_series_->setPen(bpen);
+ equity_chart_->addSeries(benchmark_series_);
+ eq_x_ = new QValueAxis();
+ eq_y_ = new QValueAxis();
+ style_axis(eq_x_);
+ style_axis(eq_y_);
+ eq_x_->setLabelFormat("%d");
+ eq_y_->setLabelFormat("%.0f");
+ equity_chart_->addAxis(eq_x_, Qt::AlignBottom);
+ equity_chart_->addAxis(eq_y_, Qt::AlignLeft);
+ equity_series_->attachAxis(eq_x_);
+ equity_series_->attachAxis(eq_y_);
+ benchmark_series_->attachAxis(eq_x_);
+ benchmark_series_->attachAxis(eq_y_);
+ auto* eq_view = make_chart_view(equity_chart_);
+ equity_chart_->legend()->setVisible(true);
+ equity_chart_->legend()->setLabelColor(QColor("#9CA3AF"));
+ l->addWidget(eq_view);
+
+ // Drawdown / underwater
+ dd_chart_ = new QChart();
+ dd_chart_->setTitle(tr("Drawdown %"));
+ dd_chart_->setTitleBrush(QColor("#E5E7EB"));
+ dd_series_ = new QLineSeries();
+ dd_series_->setColor(QColor(kNeg));
+ dd_chart_->addSeries(dd_series_);
+ dd_x_ = new QValueAxis();
+ dd_y_ = new QValueAxis();
+ style_axis(dd_x_);
+ style_axis(dd_y_);
+ dd_x_->setLabelFormat("%d");
+ dd_y_->setLabelFormat("%.1f");
+ dd_chart_->addAxis(dd_x_, Qt::AlignBottom);
+ dd_chart_->addAxis(dd_y_, Qt::AlignLeft);
+ dd_series_->attachAxis(dd_x_);
+ dd_series_->attachAxis(dd_y_);
+ l->addWidget(make_chart_view(dd_chart_));
+
+ return w;
+}
+
+QWidget* BacktestReportPanel::build_heatmap() {
+ auto* w = new QWidget(this);
+ auto* l = new QVBoxLayout(w);
+ l->setContentsMargins(0, 0, 0, 0);
+ l->setSpacing(4);
+ auto* title = new QLabel(tr("MONTHLY RETURNS %"), w);
+ title->setObjectName(QStringLiteral("kpiTitle"));
+ l->addWidget(title);
+ auto* host = new QWidget(w);
+ heatmap_grid_ = new QGridLayout(host);
+ heatmap_grid_->setSpacing(2);
+ heatmap_grid_->setContentsMargins(0, 0, 0, 0);
+ l->addWidget(host);
+ return w;
+}
+
+void BacktestReportPanel::populate_heatmap(const QJsonObject& payload) {
+ while (QLayoutItem* it = heatmap_grid_->takeAt(0)) {
+ if (it->widget())
+ it->widget()->deleteLater();
+ delete it;
+ }
+
+ QMap<int, QMap<int, double>> by_year; // year -> month(1-12) -> return%
+ for (const auto& v : payload.value("monthly_returns").toArray()) {
+ const QString ym = v.toObject().value("month").toString(); // "yyyy-MM"
+ const int y = ym.left(4).toInt();
+ const int m = ym.mid(5, 2).toInt();
+ if (y > 0 && m >= 1 && m <= 12)
+ by_year[y][m] = v.toObject().value("return").toDouble();
+ }
+
+ static const char* mlabels[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
+ "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
+ for (int m = 0; m < 12; ++m) {
+ auto* h = new QLabel(QString::fromLatin1(mlabels[m]));
+ h->setAlignment(Qt::AlignCenter);
+ h->setStyleSheet(QStringLiteral("color:#9CA3AF;font-size:8px;"));
+ heatmap_grid_->addWidget(h, 0, m + 1);
+ }
+
+ int row = 1;
+ for (auto y = by_year.constBegin(); y != by_year.constEnd(); ++y, ++row) {
+ auto* yl = new QLabel(QString::number(y.key()));
+ yl->setStyleSheet(QStringLiteral("color:#9CA3AF;font-size:8px;"));
+ heatmap_grid_->addWidget(yl, row, 0);
+ for (int m = 1; m <= 12; ++m) {
+ auto* cell = new QLabel();
+ cell->setAlignment(Qt::AlignCenter);
+ cell->setFixedHeight(18);
+ cell->setMinimumWidth(32);
+ if (y.value().contains(m)) {
+ const double r = y.value().value(m);
+ cell->setText(QString::number(r, 'f', 1));
+ QColor c(r >= 0 ? "#16A34A" : "#DC2626");
+ c.setAlphaF(std::min(0.85, 0.15 + std::abs(r) / 20.0));
+ cell->setStyleSheet(
+ QStringLiteral("background:%1;color:#E5E7EB;font-size:8px;border-radius:2px;")
+ .arg(c.name(QColor::HexArgb)));
+ } else {
+ cell->setStyleSheet(QStringLiteral("background:#161616;border-radius:2px;"));
+ }
+ heatmap_grid_->addWidget(cell, row, m);
+ }
+ }
+}
+
+QWidget* BacktestReportPanel::build_trades() {
+ trades_ = new QTableWidget(this);
+ trades_->setObjectName(QStringLiteral("backtestTradeTable"));
+ const QStringList headers = {tr("#"), tr("Entry"), tr("Exit"), tr("Entry $"),
+ tr("Exit $"), tr("Qty"), tr("P&L"), tr("P&L %"),
+ tr("Bars"), tr("Reason")};
+ trades_->setColumnCount(headers.size());
+ trades_->setHorizontalHeaderLabels(headers);
+ trades_->verticalHeader()->setVisible(false);
+ trades_->setEditTriggers(QAbstractItemView::NoEditTriggers);
+ trades_->setSelectionBehavior(QAbstractItemView::SelectRows);
+ trades_->horizontalHeader()->setStretchLastSection(true);
+ trades_->setMinimumHeight(160);
+ return trades_;
+}
+
+void BacktestReportPanel::set_result(const QJsonObject& payload) {
+ placeholder_->setVisible(false);
+ body_->setVisible(true);
+
+ auto d = [&](const char* k) { return payload.value(QLatin1String(k)).toDouble(); };
+
+ const double tr_pct = d("total_return");
+ kpi_val_["total_return"]->setText(QStringLiteral("%1%2%")
+ .arg(tr_pct >= 0 ? "+" : "").arg(tr_pct, 0, 'f', 2));
+ kpi_val_["total_return"]->setStyleSheet(QStringLiteral("color:%1;").arg(tr_pct >= 0 ? kPos : kNeg));
+ kpi_sub_["total_return"]->setText(tr("Final $%1").arg(d("final_value"), 0, 'f', 0));
+
+ const double sharpe = d("sharpe_ratio");
+ kpi_val_["sharpe"]->setText(QString::number(sharpe, 'f', 2));
+ kpi_sub_["sharpe"]->setText(sharpe >= 1.0 ? tr("Excellent") : sharpe >= 0.5 ? tr("Good") : tr("Weak"));
+
+ kpi_val_["sortino"]->setText(QString::number(d("sortino"), 'f', 2));
+ kpi_sub_["sortino"]->setText(tr("Downside-adj."));
+
+ const double mdd = d("max_drawdown");
+ kpi_val_["max_dd"]->setText(QStringLiteral("-%1%").arg(qAbs(mdd), 0, 'f', 2));
+ kpi_sub_["max_dd"]->setText(tr("Peak-to-trough"));
+
+ kpi_val_["calmar"]->setText(QString::number(d("calmar"), 'f', 2));
+ kpi_sub_["calmar"]->setText(tr("Return / MaxDD"));
+
+ const double wr = d("win_rate");
+ kpi_val_["win_rate"]->setText(QStringLiteral("%1%").arg(wr, 0, 'f', 1));
+ kpi_sub_["win_rate"]->setText(wr >= 50.0 ? tr("Above average") : tr("Below average"));
+
+ const double pf = d("profit_factor");
+ kpi_val_["profit_factor"]->setText(QString::number(pf, 'f', 2));
+ kpi_sub_["profit_factor"]->setText(pf >= 1.5 ? tr("Strong") : pf >= 1.0 ? tr("Profitable") : tr("Losing"));
+
+ kpi_val_["trades"]->setText(QString::number(payload.value("total_trades").toInt()));
+ kpi_sub_["trades"]->setText(tr("%1W / %2L")
+ .arg(payload.value("winning_trades").toInt())
+ .arg(payload.value("losing_trades").toInt()));
+
+ const double exp = d("expectancy");
+ kpi_val_["expectancy"]->setText(QStringLiteral("%1%2").arg(exp >= 0 ? "+" : "").arg(exp, 0, 'f', 2));
+ kpi_sub_["expectancy"]->setText(tr("Avg P&L / trade"));
+
+ kpi_val_["avg_bars"]->setText(QString::number(d("avg_bars_held"), 'f', 1));
+ kpi_sub_["avg_bars"]->setText(tr("Holding period"));
+
+ // ── Equity curve + benchmark + drawdown ─────────────────────────────────
+ equity_series_->clear();
+ benchmark_series_->clear();
+ dd_series_->clear();
+ const QJsonArray eq = payload.value("equity_curve").toArray();
+ const QJsonArray bench = payload.value("benchmark_curve").toArray();
+ double ymin = std::numeric_limits<double>::max();
+ double ymax = std::numeric_limits<double>::lowest();
+ double peak = 0.0, dd_min = 0.0;
+ for (int i = 0; i < eq.size(); ++i) {
+ const double v = eq[i].toDouble();
+ equity_series_->append(i, v);
+ ymin = std::min(ymin, v);
+ ymax = std::max(ymax, v);
+ if (i < bench.size()) {
+ const double b = bench[i].toDouble();
+ benchmark_series_->append(i, b);
+ ymin = std::min(ymin, b);
+ ymax = std::max(ymax, b);
+ }
+ peak = std::max(peak, v);
+ const double dd = peak > 0.0 ? (v - peak) / peak * 100.0 : 0.0;
+ dd_series_->append(i, dd);
+ dd_min = std::min(dd_min, dd);
+ }
+ const int last = std::max<int>(1, static_cast<int>(eq.size()) - 1);
+ eq_x_->setRange(0, last);
+ dd_x_->setRange(0, last);
+ if (eq.isEmpty()) {
+ eq_y_->setRange(0, 1);
+ dd_y_->setRange(-1, 0);
+ } else {
+ const double pad = std::max(1.0, (ymax - ymin) * 0.05);
+ eq_y_->setRange(ymin - pad, ymax + pad);
+ dd_y_->setRange(dd_min * 1.1 - 0.1, 0.5);
+ }
+
+ // ── Trade table ─────────────────────────────────────────────────────────
+ const QJsonArray trades = payload.value("trades").toArray();
+ trades_->setRowCount(trades.size());
+ for (int i = 0; i < trades.size(); ++i) {
+ const QJsonObject t = trades[i].toObject();
+ const double pnl = t.value("pnl").toDouble();
+ const double pnl_pct = t.value("pnl_pct").toDouble();
+ auto cell = [&](int col, const QString& text, bool color_pnl = false) {
+ auto* item = new QTableWidgetItem(text);
+ item->setTextAlignment(col >= 3 ? Qt::AlignRight | Qt::AlignVCenter
+ : Qt::AlignLeft | Qt::AlignVCenter);
+ if (color_pnl)
+ item->setForeground(QColor(pnl >= 0 ? kPos : kNeg));
+ trades_->setItem(i, col, item);
+ };
+ cell(0, QString::number(i + 1));
+ cell(1, QString::number(t.value("entry_bar").toInt()));
+ cell(2, QString::number(t.value("exit_bar").toInt()));
+ cell(3, QString::number(t.value("entry_price").toDouble(), 'f', 2));
+ cell(4, QString::number(t.value("exit_price").toDouble(), 'f', 2));
+ cell(5, QString::number(t.value("shares").toDouble(), 'f', 0));
+ cell(6, QStringLiteral("%1%2").arg(pnl >= 0 ? "+" : "").arg(pnl, 0, 'f', 2), true);
+ cell(7, QStringLiteral("%1%2%").arg(pnl_pct >= 0 ? "+" : "").arg(pnl_pct, 0, 'f', 2), true);
+ cell(8, QString::number(t.value("bars_held").toInt()));
+ cell(9, t.value("reason").toString());
+ }
+
+ populate_heatmap(payload);
+}
+
+void BacktestReportPanel::clear() {
+ placeholder_->setVisible(true);
+ body_->setVisible(false);
+}
+
+} // namespace fincept::ui::algo
diff --git a/fincept-qt/src/ui/widgets/algo/BacktestReportPanel.h b/fincept-qt/src/ui/widgets/algo/BacktestReportPanel.h
new file mode 100644
index 000000000..eb230f74f
--- /dev/null
+++ b/fincept-qt/src/ui/widgets/algo/BacktestReportPanel.h
@@ -0,0 +1,59 @@
+// src/ui/widgets/algo/BacktestReportPanel.h
+#pragma once
+#include <QHash>
+#include <QJsonObject>
+#include <QWidget>
+
+class QLabel;
+class QTableWidget;
+class QGridLayout;
+class QChart;
+class QLineSeries;
+class QValueAxis;
+
+namespace fincept::ui::algo {
+
+/// Renders a BacktestEngine result payload as a professional report: an expanded
+/// KPI grid (return, Sharpe, Sortino, max-DD, Calmar, win-rate, profit-factor,
+/// trades, expectancy, avg-bars), an equity curve, an underwater/drawdown chart,
+/// and a trade-by-trade table. Reads the fields BacktestEngine already emits
+/// (equity_curve, trades, sortino, calmar, expectancy, …).
+class BacktestReportPanel : public QWidget {
+ Q_OBJECT
+public:
+ explicit BacktestReportPanel(QWidget* parent = nullptr);
+
+ void set_result(const QJsonObject& payload);
+ void clear();
+
+private:
+ QWidget* build_kpis();
+ QWidget* build_charts();
+ QWidget* build_heatmap();
+ QWidget* build_trades();
+ void add_kpi(QGridLayout* grid, int row, int col, const QString& key, const QString& title);
+ void populate_heatmap(const QJsonObject& payload);
+
+ QHash<QString, QLabel*> kpi_val_;
+ QHash<QString, QLabel*> kpi_sub_;
+
+ QChart* equity_chart_ = nullptr;
+ QLineSeries* equity_series_ = nullptr;
+ QLineSeries* benchmark_series_ = nullptr;
+ QValueAxis* eq_x_ = nullptr;
+ QValueAxis* eq_y_ = nullptr;
+
+ QGridLayout* heatmap_grid_ = nullptr;
+
+ QChart* dd_chart_ = nullptr;
+ QLineSeries* dd_series_ = nullptr;
+ QValueAxis* dd_x_ = nullptr;
+ QValueAxis* dd_y_ = nullptr;
+
+ QTableWidget* trades_ = nullptr;
+
+ QLabel* placeholder_ = nullptr;
+ QWidget* body_ = nullptr;
+};
+
+} // namespace fincept::ui::algo
diff --git a/fincept-qt/src/ui/widgets/algo/ConditionBlock.cpp b/fincept-qt/src/ui/widgets/algo/ConditionBlock.cpp
index 192c6b2f4..ac0e74855 100644
--- a/fincept-qt/src/ui/widgets/algo/ConditionBlock.cpp
+++ b/fincept-qt/src/ui/widgets/algo/ConditionBlock.cpp
@@ -1,11 +1,11 @@
// src/ui/widgets/algo/ConditionBlock.cpp
#include "ui/widgets/algo/ConditionBlock.h"
+
#include "services/algo_trading/AlgoTradingTypes.h"
#include <QHBoxLayout>
#include <QVBoxLayout>
-using fincept::services::algo::algo_indicators;
using fincept::services::algo::algo_operators;
namespace fincept::ui::algo {
@@ -22,259 +22,122 @@ void ConditionBlock::build_ui() {
main_layout->setContentsMargins(8, 6, 8, 6);
main_layout->setSpacing(4);
- // Row 1: indicator, operator, value
- auto* row1 = new QHBoxLayout();
- row1->setSpacing(6);
+ // ── Line 1: left operand ────────────────────────────────────────────────
+ auto* line1 = new QHBoxLayout();
+ line1->setSpacing(6);
+ lhs_ = new OperandEditor(/*allow_value=*/false, this);
+ line1->addWidget(lhs_, 1);
- indicator_combo_ = new QComboBox(this);
- indicator_combo_->setObjectName(QStringLiteral("condBlockIndicator"));
- indicator_combo_->setMinimumWidth(120);
- populate_indicators();
+ remove_btn_ = new QPushButton(QStringLiteral("✕"), this);
+ remove_btn_->setObjectName(QStringLiteral("condBlockRemove"));
+ remove_btn_->setFixedSize(24, 24);
+ remove_btn_->setToolTip(tr("Remove condition"));
+ line1->addWidget(remove_btn_);
+ main_layout->addLayout(line1);
- field_combo_ = new QComboBox(this);
- field_combo_->setObjectName(QStringLiteral("condBlockField"));
- field_combo_->setMinimumWidth(80);
+ // ── Line 2: operator + right operand ────────────────────────────────────
+ auto* line2 = new QHBoxLayout();
+ line2->setSpacing(6);
+ line2->setContentsMargins(16, 0, 0, 0); // indent to read as "…compared to…"
operator_combo_ = new QComboBox(this);
operator_combo_->setObjectName(QStringLiteral("condBlockOperator"));
- operator_combo_->setMinimumWidth(100);
+ operator_combo_->setMinimumWidth(120);
populate_operators();
-
- compare_mode_combo_ = new QComboBox(this);
- compare_mode_combo_->setObjectName(QStringLiteral("condBlockCompareMode"));
- compare_mode_combo_->addItem(tr("Value"), QStringLiteral("value"));
- compare_mode_combo_->addItem(tr("Indicator"), QStringLiteral("indicator"));
-
- value_spin_ = new QDoubleSpinBox(this);
- value_spin_->setObjectName(QStringLiteral("condBlockValue"));
- value_spin_->setRange(-999999, 999999);
- value_spin_->setDecimals(4);
-
- compare_indicator_combo_ = new QComboBox(this);
- compare_indicator_combo_->setObjectName(QStringLiteral("condBlockCompareInd"));
- compare_indicator_combo_->setMinimumWidth(120);
- populate_indicators();
- for (int i = 0; i < compare_indicator_combo_->count(); ++i) {
- if (compare_indicator_combo_->itemData(i).toString().isEmpty())
- compare_indicator_combo_->model()->setData(
- compare_indicator_combo_->model()->index(i, 0), false, Qt::UserRole - 1);
- }
- compare_indicator_combo_->hide();
-
- compare_field_combo_ = new QComboBox(this);
- compare_field_combo_->setObjectName(QStringLiteral("condBlockCompareField"));
- compare_field_combo_->setMinimumWidth(80);
- compare_field_combo_->hide();
-
- remove_btn_ = new QPushButton(this);
- remove_btn_->setObjectName(QStringLiteral("condBlockRemove"));
- remove_btn_->setText(QStringLiteral("X"));
- remove_btn_->setFixedSize(24, 24);
-
- row1->addWidget(indicator_combo_);
- row1->addWidget(field_combo_);
- row1->addWidget(operator_combo_);
- row1->addWidget(compare_mode_combo_);
- row1->addWidget(value_spin_);
- row1->addWidget(compare_indicator_combo_);
- row1->addWidget(compare_field_combo_);
- row1->addStretch();
- row1->addWidget(remove_btn_);
- main_layout->addLayout(row1);
-
- // Row 2: parameters (hidden by default for stock attributes)
- params_container_ = new QWidget(this);
- params_container_->setObjectName(QStringLiteral("condBlockParams"));
- auto* params_layout = new QHBoxLayout(params_container_);
- params_layout->setContentsMargins(0, 0, 0, 0);
- params_layout->setSpacing(6);
-
- param1_label_ = new QLabel(this);
- param1_spin_ = new QDoubleSpinBox(this);
- param1_spin_->setRange(1, 500);
- param1_spin_->setDecimals(0);
- param1_spin_->setValue(14);
-
- param2_label_ = new QLabel(this);
- param2_spin_ = new QDoubleSpinBox(this);
- param2_spin_->setRange(1, 500);
- param2_spin_->setDecimals(1);
- param2_spin_->setValue(26);
-
- param3_label_ = new QLabel(this);
- param3_spin_ = new QDoubleSpinBox(this);
- param3_spin_->setRange(0.1, 100);
- param3_spin_->setDecimals(1);
- param3_spin_->setValue(9);
-
- params_layout->addWidget(param1_label_);
- params_layout->addWidget(param1_spin_);
- params_layout->addWidget(param2_label_);
- params_layout->addWidget(param2_spin_);
- params_layout->addWidget(param3_label_);
- params_layout->addWidget(param3_spin_);
- params_layout->addStretch();
- main_layout->addWidget(params_container_);
-
- // Connections
- connect(indicator_combo_, QOverload<int>::of(&QComboBox::currentIndexChanged),
- this, &ConditionBlock::on_indicator_changed);
- connect(compare_mode_combo_, QOverload<int>::of(&QComboBox::currentIndexChanged),
- this, &ConditionBlock::on_compare_mode_changed);
- connect(compare_indicator_combo_, QOverload<int>::of(&QComboBox::currentIndexChanged),
- this, [this](int) {
- populate_fields(compare_field_combo_,
- compare_indicator_combo_->currentData().toString());
- emit changed();
- });
+ line2->addWidget(operator_combo_);
+
+ rhs_ = new OperandEditor(/*allow_value=*/true, this);
+ rhs_->set_value_mode(true); // default to a constant on the right
+ line2->addWidget(rhs_, 1);
+
+ // `between` bounds (hidden unless the operator is "between").
+ between_low_ = new QDoubleSpinBox(this);
+ between_low_->setObjectName(QStringLiteral("condBlockBetweenLow"));
+ between_low_->setRange(-1e9, 1e9);
+ between_low_->setDecimals(4);
+ between_and_ = new QLabel(tr("and"), this);
+ between_high_ = new QDoubleSpinBox(this);
+ between_high_->setObjectName(QStringLiteral("condBlockBetweenHigh"));
+ between_high_->setRange(-1e9, 1e9);
+ between_high_->setDecimals(4);
+ between_high_->setValue(100);
+ line2->addWidget(between_low_);
+ line2->addWidget(between_and_);
+ line2->addWidget(between_high_);
+ main_layout->addLayout(line2);
+
+ connect(between_low_, QOverload<double>::of(&QDoubleSpinBox::valueChanged), this,
+ [this](double) { emit changed(); });
+ connect(between_high_, QOverload<double>::of(&QDoubleSpinBox::valueChanged), this,
+ [this](double) { emit changed(); });
+ connect(lhs_, &OperandEditor::changed, this, &ConditionBlock::changed);
+ connect(rhs_, &OperandEditor::changed, this, &ConditionBlock::changed);
+ connect(operator_combo_, QOverload<int>::of(&QComboBox::currentIndexChanged), this,
+ [this](int) { on_operator_changed(); });
connect(remove_btn_, &QPushButton::clicked, this, &ConditionBlock::remove_requested);
- connect(value_spin_, QOverload<double>::of(&QDoubleSpinBox::valueChanged),
- this, [this]() { emit changed(); });
- connect(operator_combo_, QOverload<int>::of(&QComboBox::currentIndexChanged),
- this, [this]() { emit changed(); });
-
- on_indicator_changed(0);
- on_compare_mode_changed(0);
-}
-
-void ConditionBlock::populate_indicators() {
- QComboBox* combo = (sender() == nullptr) ? indicator_combo_ : compare_indicator_combo_;
- if (!combo) combo = indicator_combo_;
- auto inds = algo_indicators();
- QString last_cat;
- for (const auto& ind : inds) {
- if (ind.category != last_cat) {
- last_cat = ind.category;
- QString label = ind.category.toUpper();
- combo->addItem(QStringLiteral("-- %1 --").arg(label), QString());
- }
- combo->addItem(ind.label, ind.id);
- }
- // Also populate compare_indicator_combo_ on init
- if (combo == indicator_combo_ && compare_indicator_combo_) {
- compare_indicator_combo_->clear();
- for (const auto& ind : inds) {
- if (ind.category != last_cat) {
- last_cat = ind.category;
- }
- compare_indicator_combo_->addItem(ind.label, ind.id);
- }
- }
-}
-
-void ConditionBlock::populate_fields(QComboBox* combo, const QString& indicator_id) {
- combo->clear();
- auto inds = algo_indicators();
- for (const auto& ind : inds) {
- if (ind.id == indicator_id) {
- for (const auto& f : ind.fields)
- combo->addItem(f);
- break;
- }
- }
- if (combo->count() == 0)
- combo->addItem(QStringLiteral("value"));
+ on_operator_changed();
}
void ConditionBlock::populate_operators() {
- auto ops = algo_operators();
- QStringList labels = {">", "<", ">=", "<=", "==",
- "Crosses Above", "Crosses Below", "Rising", "Falling"};
+ const auto ops = algo_operators();
+ const QStringList labels = {">", "<", ">=", "<=", "==",
+ tr("Crosses Above"), tr("Crosses Below"),
+ tr("Rising"), tr("Falling")};
for (int i = 0; i < ops.size() && i < labels.size(); ++i)
operator_combo_->addItem(labels[i], ops[i]);
}
-void ConditionBlock::on_indicator_changed(int /*index*/) {
- QString ind_id = indicator_combo_->currentData().toString();
- if (ind_id.isEmpty()) {
- indicator_combo_->setCurrentIndex(indicator_combo_->currentIndex() + 1);
- return;
- }
- populate_fields(field_combo_, ind_id);
- update_param_visibility();
- emit changed();
-}
-
-void ConditionBlock::on_compare_mode_changed(int index) {
- bool is_indicator = (index == 1);
- value_spin_->setVisible(!is_indicator);
- compare_indicator_combo_->setVisible(is_indicator);
- compare_field_combo_->setVisible(is_indicator);
+void ConditionBlock::on_operator_changed() {
+ const QString op = operator_combo_->currentData().toString();
+ const bool unary = (op == "rising" || op == "falling");
+ const bool is_between = (op == "between");
+ // Rising/Falling describe the LHS series alone; Between uses two constants.
+ rhs_->setVisible(!unary && !is_between);
+ between_low_->setVisible(is_between);
+ between_and_->setVisible(is_between);
+ between_high_->setVisible(is_between);
emit changed();
}
-void ConditionBlock::update_param_visibility() {
- QString ind_id = indicator_combo_->currentData().toString();
- auto inds = algo_indicators();
-
- QStringList param_names;
- for (const auto& ind : inds) {
- if (ind.id == ind_id) {
- param_names = ind.params;
- break;
- }
- }
-
- param1_label_->setVisible(!param_names.isEmpty());
- param1_spin_->setVisible(!param_names.isEmpty());
- param2_label_->setVisible(param_names.size() > 1);
- param2_spin_->setVisible(param_names.size() > 1);
- param3_label_->setVisible(param_names.size() > 2);
- param3_spin_->setVisible(param_names.size() > 2);
-
- if (param_names.size() > 0) param1_label_->setText(param_names[0] + ":");
- if (param_names.size() > 1) param2_label_->setText(param_names[1] + ":");
- if (param_names.size() > 2) param3_label_->setText(param_names[2] + ":");
-
- params_container_->setVisible(!param_names.isEmpty());
-}
-
QJsonObject ConditionBlock::to_json() const {
QJsonObject obj;
- obj["indicator"] = indicator_combo_->currentData().toString();
- obj["field"] = field_combo_->currentText();
- obj["operator"] = operator_combo_->currentData().toString();
- obj["compare_mode"] = compare_mode_combo_->currentData().toString();
- obj["value"] = value_spin_->value();
-
- // Build params
- QString ind_id = indicator_combo_->currentData().toString();
- auto inds = algo_indicators();
- QJsonObject params;
- for (const auto& ind : inds) {
- if (ind.id == ind_id) {
- if (ind.params.size() > 0) params[ind.params[0]] = static_cast<int>(param1_spin_->value());
- if (ind.params.size() > 1) params[ind.params[1]] = param2_spin_->value();
- if (ind.params.size() > 2) params[ind.params[2]] = param3_spin_->value();
- break;
- }
- }
- obj["params"] = params;
-
- if (compare_mode_combo_->currentData().toString() == "indicator") {
- obj["compare_indicator"] = compare_indicator_combo_->currentData().toString();
- obj["compare_field"] = compare_field_combo_->currentText();
- obj["compare_params"] = QJsonObject();
+ obj["indicator"] = lhs_->indicator_id();
+ obj["params"] = lhs_->params();
+ obj["field"] = lhs_->field();
+ obj["offset"] = lhs_->offset();
+
+ const QString op = operator_combo_->currentData().toString();
+ obj["operator"] = op;
+
+ const bool unary = (op == "rising" || op == "falling");
+ if (op == "between") {
+ obj["compare_mode"] = QStringLiteral("value");
+ obj["value"] = between_low_->value();
+ obj["value2"] = between_high_->value();
+ } else if (unary) {
+ obj["compare_mode"] = QStringLiteral("value");
+ obj["value"] = 0;
+ } else if (rhs_->is_value_mode()) {
+ obj["compare_mode"] = QStringLiteral("value");
+ obj["value"] = rhs_->value();
+ } else {
+ obj["compare_mode"] = QStringLiteral("indicator");
+ obj["compare_indicator"] = rhs_->indicator_id();
+ obj["compare_params"] = rhs_->params();
+ obj["compare_field"] = rhs_->field();
+ obj["compare_offset"] = rhs_->offset();
}
-
return obj;
}
void ConditionBlock::from_json(const QJsonObject& obj) {
- QString ind = obj.value("indicator").toString();
- for (int i = 0; i < indicator_combo_->count(); ++i) {
- if (indicator_combo_->itemData(i).toString() == ind) {
- indicator_combo_->setCurrentIndex(i);
- break;
- }
- }
+ lhs_->set_indicator(obj.value("indicator").toString());
+ lhs_->set_params(obj.value("params").toObject());
+ lhs_->set_field(obj.value("field").toString("value"));
+ lhs_->set_offset(obj.value("offset").toInt(0));
- QString field = obj.value("field").toString();
- int fi = field_combo_->findText(field);
- if (fi >= 0) field_combo_->setCurrentIndex(fi);
-
- QString op = obj.value("operator").toString();
+ const QString op = obj.value("operator").toString(">");
for (int i = 0; i < operator_combo_->count(); ++i) {
if (operator_combo_->itemData(i).toString() == op) {
operator_combo_->setCurrentIndex(i);
@@ -282,38 +145,23 @@ void ConditionBlock::from_json(const QJsonObject& obj) {
}
}
- value_spin_->setValue(obj.value("value").toDouble());
-
- QString cmp = obj.value("compare_mode").toString("value");
- compare_mode_combo_->setCurrentIndex(cmp == "indicator" ? 1 : 0);
-
- if (cmp == "indicator") {
- QString ci = obj.value("compare_indicator").toString();
- for (int i = 0; i < compare_indicator_combo_->count(); ++i) {
- if (compare_indicator_combo_->itemData(i).toString() == ci) {
- compare_indicator_combo_->setCurrentIndex(i);
- break;
- }
- }
- QString cf = obj.value("compare_field").toString();
- int cfi = compare_field_combo_->findText(cf);
- if (cfi >= 0) compare_field_combo_->setCurrentIndex(cfi);
- }
-
- // Restore params
- auto params = obj.value("params").toObject();
- auto inds = algo_indicators();
- for (const auto& indef : inds) {
- if (indef.id == ind) {
- if (indef.params.size() > 0 && params.contains(indef.params[0]))
- param1_spin_->setValue(params.value(indef.params[0]).toDouble());
- if (indef.params.size() > 1 && params.contains(indef.params[1]))
- param2_spin_->setValue(params.value(indef.params[1]).toDouble());
- if (indef.params.size() > 2 && params.contains(indef.params[2]))
- param3_spin_->setValue(params.value(indef.params[2]).toDouble());
- break;
+ if (op == "between") {
+ between_low_->setValue(obj.value("value").toDouble(0));
+ between_high_->setValue(obj.value("value2").toDouble(0));
+ } else {
+ const QString cmp = obj.value("compare_mode").toString("value");
+ if (cmp == "indicator") {
+ rhs_->set_value_mode(false);
+ rhs_->set_indicator(obj.value("compare_indicator").toString());
+ rhs_->set_params(obj.value("compare_params").toObject());
+ rhs_->set_field(obj.value("compare_field").toString("value"));
+ rhs_->set_offset(obj.value("compare_offset").toInt(0));
+ } else {
+ rhs_->set_value_mode(true);
+ rhs_->set_value(obj.value("value").toDouble(0));
}
}
+ on_operator_changed();
}
} // namespace fincept::ui::algo
diff --git a/fincept-qt/src/ui/widgets/algo/ConditionBlock.h b/fincept-qt/src/ui/widgets/algo/ConditionBlock.h
index c73128bbd..220ecfcda 100644
--- a/fincept-qt/src/ui/widgets/algo/ConditionBlock.h
+++ b/fincept-qt/src/ui/widgets/algo/ConditionBlock.h
@@ -1,6 +1,7 @@
// src/ui/widgets/algo/ConditionBlock.h
#pragma once
#include "services/algo_trading/AlgoTradingTypes.h"
+#include "ui/widgets/algo/OperandEditor.h"
#include <QComboBox>
#include <QDoubleSpinBox>
@@ -8,10 +9,14 @@
#include <QJsonObject>
#include <QLabel>
#include <QPushButton>
-#include <QWidget>
namespace fincept::ui::algo {
+/// A single comparison leaf: `LHS <operator> RHS`.
+/// LHS is always an indicator operand; RHS is an indicator-or-value operand,
+/// and is hidden for the unary `rising` / `falling` operators. Serializes to the
+/// flat comparison schema the ConditionEvaluator understands (indicator/params/
+/// field/offset on the left; compare_* / value on the right).
class ConditionBlock : public QFrame {
Q_OBJECT
public:
@@ -26,32 +31,18 @@ signals:
private:
void build_ui();
- void on_indicator_changed(int index);
- void on_compare_mode_changed(int index);
- void populate_indicators();
- void populate_fields(QComboBox* combo, const QString& indicator);
void populate_operators();
- void update_param_visibility();
+ void on_operator_changed();
bool is_entry_;
- QComboBox* indicator_combo_ = nullptr;
- QComboBox* field_combo_ = nullptr;
+ OperandEditor* lhs_ = nullptr;
QComboBox* operator_combo_ = nullptr;
- QComboBox* compare_mode_combo_ = nullptr;
- QDoubleSpinBox* value_spin_ = nullptr;
- QComboBox* compare_indicator_combo_ = nullptr;
- QComboBox* compare_field_combo_ = nullptr;
-
- // Indicator parameters
- QWidget* params_container_ = nullptr;
- QDoubleSpinBox* param1_spin_ = nullptr;
- QDoubleSpinBox* param2_spin_ = nullptr;
- QDoubleSpinBox* param3_spin_ = nullptr;
- QLabel* param1_label_ = nullptr;
- QLabel* param2_label_ = nullptr;
- QLabel* param3_label_ = nullptr;
-
+ OperandEditor* rhs_ = nullptr;
+ // `between` uses two constants (low..high) instead of the RHS operand.
+ QDoubleSpinBox* between_low_ = nullptr;
+ QLabel* between_and_ = nullptr;
+ QDoubleSpinBox* between_high_ = nullptr;
QPushButton* remove_btn_ = nullptr;
};
diff --git a/fincept-qt/src/ui/widgets/algo/ConditionSection.cpp b/fincept-qt/src/ui/widgets/algo/ConditionSection.cpp
index 497d23016..4b3eeec4f 100644
--- a/fincept-qt/src/ui/widgets/algo/ConditionSection.cpp
+++ b/fincept-qt/src/ui/widgets/algo/ConditionSection.cpp
@@ -1,8 +1,9 @@
// src/ui/widgets/algo/ConditionSection.cpp
#include "ui/widgets/algo/ConditionSection.h"
+#include <QHBoxLayout>
#include <QLabel>
-#include <QVBoxLayout>
+#include <QStyle>
namespace fincept::ui::algo {
@@ -15,108 +16,169 @@ ConditionSection::ConditionSection(Type type, QWidget* parent)
main_layout->setContentsMargins(0, 0, 0, 0);
main_layout->setSpacing(4);
- // Section header
- auto* header = new QLabel(
+ // ── Header: title + section AND/OR toggle ───────────────────────────────
+ auto* header = new QHBoxLayout();
+ header->setSpacing(6);
+ auto* title = new QLabel(
type == Type::Entry ? tr("ENTRY CONDITIONS") : tr("EXIT CONDITIONS"), this);
- header->setObjectName(type == Type::Entry ? QStringLiteral("condSectionHeaderEntry")
- : QStringLiteral("condSectionHeaderExit"));
- main_layout->addWidget(header);
-
- // Condition blocks container
- blocks_layout_ = new QVBoxLayout();
- blocks_layout_->setSpacing(0);
- blocks_layout_->setContentsMargins(0, 0, 0, 0);
- main_layout->addLayout(blocks_layout_);
-
- // Add button
- add_btn_ = new QPushButton(tr("+ Add Condition"), this);
- add_btn_->setObjectName(QStringLiteral("condSectionAddBtn"));
- connect(add_btn_, &QPushButton::clicked, this, &ConditionSection::add_condition);
- main_layout->addWidget(add_btn_);
+ title->setObjectName(type == Type::Entry ? QStringLiteral("condSectionHeaderEntry")
+ : QStringLiteral("condSectionHeaderExit"));
+ header->addWidget(title);
+ header->addStretch();
+
+ auto* match = new QLabel(tr("Match:"), this);
+ match->setObjectName(QStringLiteral("condSectionMatchLabel"));
+ header->addWidget(match);
+ and_btn_ = new QPushButton(tr("ALL (AND)"), this);
+ and_btn_->setObjectName(QStringLiteral("logicBtnAnd"));
+ and_btn_->setCheckable(true);
+ and_btn_->setFixedHeight(22);
+ or_btn_ = new QPushButton(tr("ANY (OR)"), this);
+ or_btn_->setObjectName(QStringLiteral("logicBtnOr"));
+ or_btn_->setCheckable(true);
+ or_btn_->setFixedHeight(22);
+ header->addWidget(and_btn_);
+ header->addWidget(or_btn_);
+ main_layout->addLayout(header);
+
+ // ── Children ────────────────────────────────────────────────────────────
+ nodes_layout_ = new QVBoxLayout();
+ nodes_layout_->setSpacing(2);
+ nodes_layout_->setContentsMargins(0, 0, 0, 0);
+ main_layout->addLayout(nodes_layout_);
+
+ // ── Add buttons ─────────────────────────────────────────────────────────
+ auto* add_row = new QHBoxLayout();
+ add_row->setSpacing(6);
+ auto* add_cond = new QPushButton(tr("+ Add Condition"), this);
+ add_cond->setObjectName(QStringLiteral("condSectionAddBtn"));
+ auto* add_grp = new QPushButton(tr("+ Add Group"), this);
+ add_grp->setObjectName(QStringLiteral("condSectionAddGroupBtn"));
+ add_row->addWidget(add_cond);
+ add_row->addWidget(add_grp);
+ add_row->addStretch();
+ main_layout->addLayout(add_row);
main_layout->addStretch();
+ connect(and_btn_, &QPushButton::clicked, this, [this]() { set_logic(QStringLiteral("AND")); emit conditions_changed(); });
+ connect(or_btn_, &QPushButton::clicked, this, [this]() { set_logic(QStringLiteral("OR")); emit conditions_changed(); });
+ connect(add_cond, &QPushButton::clicked, this, &ConditionSection::add_condition);
+ connect(add_grp, &QPushButton::clicked, this, &ConditionSection::add_group);
+
+ update_logic_buttons();
add_condition();
}
+void ConditionSection::set_logic(const QString& logic) {
+ logic_ = (logic.toUpper() == "OR") ? QStringLiteral("OR") : QStringLiteral("AND");
+ update_logic_buttons();
+ rebuild_layout();
+}
+
+void ConditionSection::update_logic_buttons() {
+ const bool is_and = (logic_ == "AND");
+ and_btn_->setChecked(is_and);
+ or_btn_->setChecked(!is_and);
+ for (QPushButton* b : {and_btn_, or_btn_}) {
+ b->setProperty("active", b->isChecked());
+ b->style()->unpolish(b);
+ b->style()->polish(b);
+ }
+}
+
+void ConditionSection::attach_node(QWidget* node) {
+ if (auto* c = qobject_cast<ConditionBlock*>(node)) {
+ connect(c, &ConditionBlock::remove_requested, this, [this, node]() { remove_node(node); });
+ connect(c, &ConditionBlock::changed, this, &ConditionSection::conditions_changed);
+ } else if (auto* g = qobject_cast<GroupBlock*>(node)) {
+ connect(g, &GroupBlock::remove_requested, this, [this, node]() { remove_node(node); });
+ connect(g, &GroupBlock::changed, this, &ConditionSection::conditions_changed);
+ }
+ nodes_.append(node);
+}
+
void ConditionSection::add_condition() {
- auto* block = new ConditionBlock(type_ == Type::Entry, this);
- connect(block, &ConditionBlock::remove_requested, this, [this, block]() {
- on_block_removed(block);
- });
- connect(block, &ConditionBlock::changed, this, &ConditionSection::conditions_changed);
+ attach_node(new ConditionBlock(type_ == Type::Entry, this));
+ rebuild_layout();
+ emit conditions_changed();
+}
- blocks_.append(block);
+void ConditionSection::add_group() {
+ attach_node(new GroupBlock(type_ == Type::Entry, this));
rebuild_layout();
emit conditions_changed();
}
-void ConditionSection::on_block_removed(ConditionBlock* block) {
- int idx = blocks_.indexOf(block);
+void ConditionSection::remove_node(QWidget* node) {
+ const int idx = nodes_.indexOf(node);
if (idx < 0) return;
- if (blocks_.size() <= 1) return;
-
- blocks_.removeAt(idx);
- block->deleteLater();
+ if (nodes_.size() <= 1) return; // keep at least one row
+ nodes_.removeAt(idx);
+ node->deleteLater();
rebuild_layout();
emit conditions_changed();
}
void ConditionSection::rebuild_layout() {
- // Clear layout
- while (blocks_layout_->count() > 0) {
- auto* item = blocks_layout_->takeAt(0);
- if (item->widget() && qobject_cast<LogicConnectorWidget*>(item->widget())) {
+ while (nodes_layout_->count() > 0) {
+ QLayoutItem* item = nodes_layout_->takeAt(0);
+ if (item->widget() && item->widget()->objectName() == "sectionConnectorLabel")
item->widget()->deleteLater();
- }
delete item;
}
- connectors_.clear();
-
- for (int i = 0; i < blocks_.size(); ++i) {
+ const QString conn = (logic_ == "OR") ? tr("OR") : tr("AND");
+ for (int i = 0; i < nodes_.size(); ++i) {
if (i > 0) {
- auto* connector = new LogicConnectorWidget(this);
- connectors_.append(connector);
- connect(connector, &LogicConnectorWidget::logic_changed,
- this, &ConditionSection::conditions_changed);
- blocks_layout_->addWidget(connector);
+ auto* lbl = new QLabel(conn, this);
+ lbl->setObjectName(QStringLiteral("sectionConnectorLabel"));
+ nodes_layout_->addWidget(lbl);
}
- blocks_layout_->addWidget(blocks_[i]);
+ nodes_layout_->addWidget(nodes_[i]);
}
}
QJsonArray ConditionSection::conditions() const {
QJsonArray arr;
- for (const auto* block : blocks_)
- arr.append(block->to_json());
+ for (QWidget* n : nodes_) {
+ if (auto* c = qobject_cast<ConditionBlock*>(n))
+ arr.append(c->to_json());
+ else if (auto* g = qobject_cast<GroupBlock*>(n))
+ arr.append(g->to_json());
+ }
return arr;
}
-QString ConditionSection::combined_logic() const {
- if (connectors_.isEmpty()) return QStringLiteral("AND");
- return connectors_.first()->logic();
-}
+QString ConditionSection::combined_logic() const { return logic_; }
void ConditionSection::set_conditions(const QJsonArray& conditions, const QString& logic) {
- clear_all();
+ set_logic(logic);
+
+ for (QWidget* n : nodes_)
+ n->deleteLater();
+ nodes_.clear();
+
for (const auto& val : conditions) {
- auto* block = new ConditionBlock(type_ == Type::Entry, this);
- block->from_json(val.toObject());
- connect(block, &ConditionBlock::remove_requested, this, [this, block]() {
- on_block_removed(block);
- });
- connect(block, &ConditionBlock::changed, this, &ConditionSection::conditions_changed);
- blocks_.append(block);
+ const QJsonObject node = val.toObject();
+ if (node.contains("children")) {
+ auto* g = new GroupBlock(type_ == Type::Entry, this);
+ attach_node(g);
+ g->from_json(node);
+ } else {
+ auto* c = new ConditionBlock(type_ == Type::Entry, this);
+ attach_node(c);
+ c->from_json(node);
+ }
}
+ if (nodes_.isEmpty())
+ attach_node(new ConditionBlock(type_ == Type::Entry, this));
rebuild_layout();
- for (auto* c : connectors_)
- c->set_logic(logic);
}
void ConditionSection::clear_all() {
- for (auto* b : blocks_)
- b->deleteLater();
- blocks_.clear();
+ for (QWidget* n : nodes_)
+ n->deleteLater();
+ nodes_.clear();
rebuild_layout();
}
diff --git a/fincept-qt/src/ui/widgets/algo/ConditionSection.h b/fincept-qt/src/ui/widgets/algo/ConditionSection.h
index f0a63fa6d..b104fa82a 100644
--- a/fincept-qt/src/ui/widgets/algo/ConditionSection.h
+++ b/fincept-qt/src/ui/widgets/algo/ConditionSection.h
@@ -1,7 +1,7 @@
// src/ui/widgets/algo/ConditionSection.h
#pragma once
#include "ui/widgets/algo/ConditionBlock.h"
-#include "ui/widgets/algo/LogicConnectorWidget.h"
+#include "ui/widgets/algo/GroupBlock.h"
#include <QJsonArray>
#include <QPushButton>
@@ -10,6 +10,12 @@
namespace fincept::ui::algo {
+/// Root of an entry/exit rule: a single AND/OR combinator over a list of
+/// children, each a ConditionBlock (leaf) or a GroupBlock (nested group). The
+/// section-level toggle is the real combinator — `combined_logic()` returns it
+/// (no more "only the first connector counts"). Serializes its children to the
+/// array the ConditionEvaluator consumes, with nested groups expressed as
+/// `{type:"group", ...}` elements.
class ConditionSection : public QWidget {
Q_OBJECT
public:
@@ -29,14 +35,20 @@ public slots:
void add_condition();
private:
+ void add_group();
+ void attach_node(QWidget* node);
+ void remove_node(QWidget* node);
void rebuild_layout();
- void on_block_removed(ConditionBlock* block);
+ void set_logic(const QString& logic);
+ void update_logic_buttons();
Type type_;
- QVector<ConditionBlock*> blocks_;
- QVector<LogicConnectorWidget*> connectors_;
- QVBoxLayout* blocks_layout_ = nullptr;
- QPushButton* add_btn_ = nullptr;
+ QString logic_ = QStringLiteral("AND");
+
+ QPushButton* and_btn_ = nullptr;
+ QPushButton* or_btn_ = nullptr;
+ QVBoxLayout* nodes_layout_ = nullptr;
+ QVector<QWidget*> nodes_; // ConditionBlock* or GroupBlock*
};
} // namespace fincept::ui::algo
diff --git a/fincept-qt/src/ui/widgets/algo/GroupBlock.cpp b/fincept-qt/src/ui/widgets/algo/GroupBlock.cpp
new file mode 100644
index 000000000..feb40046b
--- /dev/null
+++ b/fincept-qt/src/ui/widgets/algo/GroupBlock.cpp
@@ -0,0 +1,174 @@
+// src/ui/widgets/algo/GroupBlock.cpp
+#include "ui/widgets/algo/GroupBlock.h"
+
+#include <QHBoxLayout>
+#include <QJsonArray>
+#include <QLabel>
+#include <QStyle>
+
+namespace fincept::ui::algo {
+
+GroupBlock::GroupBlock(bool is_entry, QWidget* parent)
+ : QFrame(parent), is_entry_(is_entry) {
+ setObjectName(QStringLiteral("conditionGroupBlock"));
+ setFrameShape(QFrame::StyledPanel);
+ build_ui();
+}
+
+void GroupBlock::build_ui() {
+ auto* main = new QVBoxLayout(this);
+ main->setContentsMargins(8, 6, 8, 8);
+ main->setSpacing(4);
+
+ // ── Header: GROUP · AND/OR · +Condition · +Group · remove ───────────────
+ auto* header = new QHBoxLayout();
+ header->setSpacing(6);
+
+ auto* tag = new QLabel(tr("GROUP"), this);
+ tag->setObjectName(QStringLiteral("groupTag"));
+ header->addWidget(tag);
+
+ and_btn_ = new QPushButton(tr("AND"), this);
+ and_btn_->setObjectName(QStringLiteral("logicBtnAnd"));
+ and_btn_->setCheckable(true);
+ and_btn_->setFixedHeight(22);
+ or_btn_ = new QPushButton(tr("OR"), this);
+ or_btn_->setObjectName(QStringLiteral("logicBtnOr"));
+ or_btn_->setCheckable(true);
+ or_btn_->setFixedHeight(22);
+ header->addWidget(and_btn_);
+ header->addWidget(or_btn_);
+ header->addStretch();
+
+ auto* add_cond = new QPushButton(tr("+ Condition"), this);
+ add_cond->setObjectName(QStringLiteral("condSectionAddBtn"));
+ auto* add_grp = new QPushButton(tr("+ Group"), this);
+ add_grp->setObjectName(QStringLiteral("condSectionAddGroupBtn"));
+ auto* remove = new QPushButton(QStringLiteral("✕"), this);
+ remove->setObjectName(QStringLiteral("condBlockRemove"));
+ remove->setFixedSize(24, 22);
+ remove->setToolTip(tr("Remove group"));
+ header->addWidget(add_cond);
+ header->addWidget(add_grp);
+ header->addWidget(remove);
+ main->addLayout(header);
+
+ nodes_layout_ = new QVBoxLayout();
+ nodes_layout_->setContentsMargins(8, 0, 0, 0);
+ nodes_layout_->setSpacing(2);
+ main->addLayout(nodes_layout_);
+
+ connect(and_btn_, &QPushButton::clicked, this, [this]() { set_logic(QStringLiteral("AND")); emit changed(); });
+ connect(or_btn_, &QPushButton::clicked, this, [this]() { set_logic(QStringLiteral("OR")); emit changed(); });
+ connect(add_cond, &QPushButton::clicked, this, &GroupBlock::add_condition);
+ connect(add_grp, &QPushButton::clicked, this, &GroupBlock::add_group);
+ connect(remove, &QPushButton::clicked, this, &GroupBlock::remove_requested);
+
+ update_logic_buttons();
+ add_condition(); // a fresh group starts with one condition
+}
+
+void GroupBlock::set_logic(const QString& logic) {
+ logic_ = (logic.toUpper() == "OR") ? QStringLiteral("OR") : QStringLiteral("AND");
+ update_logic_buttons();
+}
+
+void GroupBlock::update_logic_buttons() {
+ const bool is_and = (logic_ == "AND");
+ and_btn_->setChecked(is_and);
+ or_btn_->setChecked(!is_and);
+ for (QPushButton* b : {and_btn_, or_btn_}) {
+ b->setProperty("active", b->isChecked());
+ b->style()->unpolish(b);
+ b->style()->polish(b);
+ }
+}
+
+void GroupBlock::attach_node(QWidget* node) {
+ if (auto* c = qobject_cast<ConditionBlock*>(node)) {
+ connect(c, &ConditionBlock::remove_requested, this, [this, node]() { remove_node(node); });
+ connect(c, &ConditionBlock::changed, this, &GroupBlock::changed);
+ } else if (auto* g = qobject_cast<GroupBlock*>(node)) {
+ connect(g, &GroupBlock::remove_requested, this, [this, node]() { remove_node(node); });
+ connect(g, &GroupBlock::changed, this, &GroupBlock::changed);
+ }
+ nodes_.append(node);
+}
+
+void GroupBlock::add_condition() {
+ attach_node(new ConditionBlock(is_entry_, this));
+ rebuild_layout();
+ emit changed();
+}
+
+void GroupBlock::add_group() {
+ attach_node(new GroupBlock(is_entry_, this));
+ rebuild_layout();
+ emit changed();
+}
+
+void GroupBlock::remove_node(QWidget* node) {
+ const int idx = nodes_.indexOf(node);
+ if (idx < 0) return;
+ nodes_.removeAt(idx);
+ node->deleteLater();
+ rebuild_layout();
+ emit changed();
+}
+
+void GroupBlock::rebuild_layout() {
+ // Detach connector labels but keep node widgets alive.
+ while (nodes_layout_->count() > 0) {
+ QLayoutItem* item = nodes_layout_->takeAt(0);
+ if (item->widget() && item->widget()->objectName() == "groupConnectorLabel")
+ item->widget()->deleteLater();
+ delete item;
+ }
+ for (int i = 0; i < nodes_.size(); ++i) {
+ if (i > 0) {
+ auto* lbl = new QLabel(logic_, this);
+ lbl->setObjectName(QStringLiteral("groupConnectorLabel"));
+ nodes_layout_->addWidget(lbl);
+ }
+ nodes_layout_->addWidget(nodes_[i]);
+ }
+}
+
+QJsonObject GroupBlock::to_json() const {
+ QJsonObject obj;
+ obj["type"] = QStringLiteral("group");
+ obj["logic"] = logic_;
+ QJsonArray children;
+ for (QWidget* n : nodes_) {
+ if (auto* c = qobject_cast<ConditionBlock*>(n))
+ children.append(c->to_json());
+ else if (auto* g = qobject_cast<GroupBlock*>(n))
+ children.append(g->to_json());
+ }
+ obj["children"] = children;
+ return obj;
+}
+
+void GroupBlock::from_json(const QJsonObject& obj) {
+ set_logic(obj.value("logic").toString(obj.value("op").toString("AND")));
+
+ for (QWidget* n : nodes_)
+ n->deleteLater();
+ nodes_.clear();
+
+ for (const auto& v : obj.value("children").toArray()) {
+ const QJsonObject node = v.toObject();
+ if (node.contains("children")) {
+ auto* g = new GroupBlock(is_entry_, this);
+ attach_node(g);
+ g->from_json(node);
+ } else {
+ auto* c = new ConditionBlock(is_entry_, this);
+ attach_node(c);
+ c->from_json(node);
+ }
+ }
+ rebuild_layout();
+}
+
+} // namespace fincept::ui::algo
diff --git a/fincept-qt/src/ui/widgets/algo/GroupBlock.h b/fincept-qt/src/ui/widgets/algo/GroupBlock.h
new file mode 100644
index 000000000..a87be7fc4
--- /dev/null
+++ b/fincept-qt/src/ui/widgets/algo/GroupBlock.h
@@ -0,0 +1,47 @@
+// src/ui/widgets/algo/GroupBlock.h
+#pragma once
+#include "ui/widgets/algo/ConditionBlock.h"
+
+#include <QFrame>
+#include <QJsonObject>
+#include <QPushButton>
+#include <QVBoxLayout>
+#include <QVector>
+
+namespace fincept::ui::algo {
+
+/// A nested condition group: its own AND/OR combinator over a list of children,
+/// where each child is a ConditionBlock (leaf) or another GroupBlock. Enables
+/// `(A AND B) OR C`. Serializes to `{type:"group", logic, children:[...]}`.
+class GroupBlock : public QFrame {
+ Q_OBJECT
+public:
+ explicit GroupBlock(bool is_entry, QWidget* parent = nullptr);
+
+ QJsonObject to_json() const;
+ void from_json(const QJsonObject& obj);
+
+signals:
+ void remove_requested();
+ void changed();
+
+private:
+ void build_ui();
+ void add_condition();
+ void add_group();
+ void attach_node(QWidget* node); // wire signals + append to nodes_
+ void remove_node(QWidget* node);
+ void rebuild_layout();
+ void set_logic(const QString& logic);
+ void update_logic_buttons();
+
+ bool is_entry_;
+ QString logic_ = QStringLiteral("AND");
+
+ QPushButton* and_btn_ = nullptr;
+ QPushButton* or_btn_ = nullptr;
+ QVBoxLayout* nodes_layout_ = nullptr;
+ QVector<QWidget*> nodes_; // ConditionBlock* or GroupBlock*
+};
+
+} // namespace fincept::ui::algo
diff --git a/fincept-qt/src/ui/widgets/algo/LogicConnectorWidget.cpp b/fincept-qt/src/ui/widgets/algo/LogicConnectorWidget.cpp
deleted file mode 100644
index 6aa52a7bf..000000000
--- a/fincept-qt/src/ui/widgets/algo/LogicConnectorWidget.cpp
+++ /dev/null
@@ -1,79 +0,0 @@
-// src/ui/widgets/algo/LogicConnectorWidget.cpp
-#include "ui/widgets/algo/LogicConnectorWidget.h"
-
-#include <QHBoxLayout>
-#include <QFrame>
-
-namespace fincept::ui::algo {
-
-LogicConnectorWidget::LogicConnectorWidget(QWidget* parent)
- : QWidget(parent) {
- setObjectName(QStringLiteral("logicConnector"));
- setFixedHeight(28);
-
- auto* layout = new QHBoxLayout(this);
- layout->setContentsMargins(20, 0, 20, 0);
- layout->setSpacing(0);
-
- auto* left_line = new QFrame(this);
- left_line->setObjectName(QStringLiteral("logicLine"));
- left_line->setFrameShape(QFrame::HLine);
- left_line->setFixedHeight(1);
-
- and_btn_ = new QPushButton(tr("AND"), this);
- and_btn_->setObjectName(QStringLiteral("logicBtnAnd"));
- and_btn_->setCheckable(true);
- and_btn_->setChecked(true);
- and_btn_->setFixedSize(48, 22);
-
- or_btn_ = new QPushButton(tr("OR"), this);
- or_btn_->setObjectName(QStringLiteral("logicBtnOr"));
- or_btn_->setCheckable(true);
- or_btn_->setFixedSize(36, 22);
-
- auto* right_line = new QFrame(this);
- right_line->setObjectName(QStringLiteral("logicLine"));
- right_line->setFrameShape(QFrame::HLine);
- right_line->setFixedHeight(1);
-
- layout->addWidget(left_line, 1);
- layout->addWidget(and_btn_);
- layout->addWidget(or_btn_);
- layout->addWidget(right_line, 1);
-
- connect(and_btn_, &QPushButton::clicked, this, [this]() {
- and_btn_->setChecked(true);
- or_btn_->setChecked(false);
- update_style();
- emit logic_changed(QStringLiteral("AND"));
- });
- connect(or_btn_, &QPushButton::clicked, this, [this]() {
- or_btn_->setChecked(true);
- and_btn_->setChecked(false);
- update_style();
- emit logic_changed(QStringLiteral("OR"));
- });
- update_style();
-}
-
-QString LogicConnectorWidget::logic() const {
- return and_btn_->isChecked() ? QStringLiteral("AND") : QStringLiteral("OR");
-}
-
-void LogicConnectorWidget::set_logic(const QString& logic) {
- bool is_and = (logic.toUpper() == "AND");
- and_btn_->setChecked(is_and);
- or_btn_->setChecked(!is_and);
- update_style();
-}
-
-void LogicConnectorWidget::update_style() {
- and_btn_->setProperty("active", and_btn_->isChecked());
- or_btn_->setProperty("active", or_btn_->isChecked());
- and_btn_->style()->unpolish(and_btn_);
- and_btn_->style()->polish(and_btn_);
- or_btn_->style()->unpolish(or_btn_);
- or_btn_->style()->polish(or_btn_);
-}
-
-} // namespace fincept::ui::algo
diff --git a/fincept-qt/src/ui/widgets/algo/LogicConnectorWidget.h b/fincept-qt/src/ui/widgets/algo/LogicConnectorWidget.h
deleted file mode 100644
index efef6d044..000000000
--- a/fincept-qt/src/ui/widgets/algo/LogicConnectorWidget.h
+++ /dev/null
@@ -1,25 +0,0 @@
-// src/ui/widgets/algo/LogicConnectorWidget.h
-#pragma once
-#include <QPushButton>
-#include <QWidget>
-
-namespace fincept::ui::algo {
-
-class LogicConnectorWidget : public QWidget {
- Q_OBJECT
-public:
- explicit LogicConnectorWidget(QWidget* parent = nullptr);
-
- QString logic() const;
- void set_logic(const QString& logic);
-
-signals:
- void logic_changed(const QString& logic);
-
-private:
- QPushButton* and_btn_ = nullptr;
- QPushButton* or_btn_ = nullptr;
- void update_style();
-};
-
-} // namespace fincept::ui::algo
diff --git a/fincept-qt/src/ui/widgets/algo/OperandEditor.cpp b/fincept-qt/src/ui/widgets/algo/OperandEditor.cpp
new file mode 100644
index 000000000..e1dc111c4
--- /dev/null
+++ b/fincept-qt/src/ui/widgets/algo/OperandEditor.cpp
@@ -0,0 +1,278 @@
+// src/ui/widgets/algo/OperandEditor.cpp
+#include "ui/widgets/algo/OperandEditor.h"
+
+#include <QCompleter>
+#include <QLineEdit>
+#include <QVBoxLayout>
+
+using fincept::services::algo::algo_indicators;
+using fincept::services::algo::IndicatorDef;
+using fincept::services::algo::ParamSpec;
+
+namespace fincept::ui::algo {
+
+OperandEditor::OperandEditor(bool allow_value, QWidget* parent)
+ : QWidget(parent), allow_value_(allow_value) {
+ setObjectName(QStringLiteral("operandEditor"));
+ build_ui();
+}
+
+void OperandEditor::build_ui() {
+ auto* row = new QHBoxLayout(this);
+ row->setContentsMargins(0, 0, 0, 0);
+ row->setSpacing(6);
+
+ if (allow_value_) {
+ mode_combo_ = new QComboBox(this);
+ mode_combo_->setObjectName(QStringLiteral("operandMode"));
+ mode_combo_->addItem(tr("Indicator"), QStringLiteral("indicator"));
+ mode_combo_->addItem(tr("Value"), QStringLiteral("value"));
+ row->addWidget(mode_combo_);
+ }
+
+ indicator_combo_ = new QComboBox(this);
+ indicator_combo_->setObjectName(QStringLiteral("operandIndicator"));
+ indicator_combo_->setMinimumWidth(130);
+ populate_indicators();
+ // Type-to-search across the indicator catalog (contains match, case-insensitive).
+ indicator_combo_->setEditable(true);
+ indicator_combo_->setInsertPolicy(QComboBox::NoInsert);
+ indicator_combo_->lineEdit()->setPlaceholderText(tr("Search indicator…"));
+ if (auto* c = indicator_combo_->completer()) {
+ c->setCompletionMode(QCompleter::PopupCompletion);
+ c->setFilterMode(Qt::MatchContains);
+ c->setCaseSensitivity(Qt::CaseInsensitive);
+ }
+ row->addWidget(indicator_combo_);
+
+ params_container_ = new QWidget(this);
+ params_layout_ = new QHBoxLayout(params_container_);
+ params_layout_->setContentsMargins(0, 0, 0, 0);
+ params_layout_->setSpacing(4);
+ row->addWidget(params_container_);
+
+ field_combo_ = new QComboBox(this);
+ field_combo_->setObjectName(QStringLiteral("operandField"));
+ field_combo_->setMinimumWidth(80);
+ row->addWidget(field_combo_);
+
+ // Advanced (opt-in): compare against an earlier bar. Hidden behind a toggle so
+ // the common case (current bar) stays clutter-free.
+ offset_btn_ = new QPushButton(tr("⋯ bar"), this);
+ offset_btn_->setObjectName(QStringLiteral("operandOffsetToggle"));
+ offset_btn_->setCheckable(true);
+ offset_btn_->setFixedHeight(22);
+ offset_btn_->setToolTip(tr("Advanced: compare this against an earlier bar (e.g. 1 bar ago)"));
+ offset_combo_ = new QComboBox(this);
+ offset_combo_->setObjectName(QStringLiteral("operandOffset"));
+ offset_combo_->addItem(tr("Current bar"), 0);
+ offset_combo_->addItem(tr("1 bar ago"), 1);
+ offset_combo_->addItem(tr("2 bars ago"), 2);
+ offset_combo_->addItem(tr("3 bars ago"), 3);
+ offset_combo_->addItem(tr("5 bars ago"), 5);
+ offset_combo_->addItem(tr("10 bars ago"), 10);
+ offset_combo_->addItem(tr("20 bars ago"), 20);
+ offset_combo_->setVisible(false);
+ row->addWidget(offset_btn_);
+ row->addWidget(offset_combo_);
+
+ value_spin_ = new QDoubleSpinBox(this);
+ value_spin_->setObjectName(QStringLiteral("operandValue"));
+ value_spin_->setRange(-1e9, 1e9);
+ value_spin_->setDecimals(4);
+ row->addWidget(value_spin_);
+
+ if (mode_combo_)
+ connect(mode_combo_, QOverload<int>::of(&QComboBox::currentIndexChanged),
+ this, &OperandEditor::on_mode_changed);
+ connect(indicator_combo_, QOverload<int>::of(&QComboBox::currentIndexChanged),
+ this, &OperandEditor::on_indicator_changed);
+ connect(field_combo_, QOverload<int>::of(&QComboBox::currentIndexChanged),
+ this, [this](int) { emit changed(); });
+ connect(offset_btn_, &QPushButton::toggled, this, [this](bool on) {
+ offset_combo_->setVisible(on && !is_value_mode());
+ if (!on)
+ offset_combo_->setCurrentIndex(0); // collapse back to "Current bar"
+ emit changed();
+ });
+ connect(offset_combo_, QOverload<int>::of(&QComboBox::currentIndexChanged),
+ this, [this](int) { emit changed(); });
+ connect(value_spin_, QOverload<double>::of(&QDoubleSpinBox::valueChanged),
+ this, [this](double) { emit changed(); });
+
+ // Land on the first real indicator (skip the leading category header).
+ if (indicator_combo_->count() > 1)
+ indicator_combo_->setCurrentIndex(1);
+ on_indicator_changed();
+ apply_mode_visibility();
+}
+
+void OperandEditor::populate_indicators() {
+ QString last_cat;
+ const auto inds = algo_indicators();
+ for (const auto& ind : inds) {
+ if (ind.category != last_cat) {
+ last_cat = ind.category;
+ indicator_combo_->addItem(QStringLiteral("-- %1 --").arg(ind.category.toUpper()), QString());
+ // Make the header row non-selectable.
+ const int hidx = indicator_combo_->count() - 1;
+ indicator_combo_->model()->setData(
+ indicator_combo_->model()->index(hidx, 0), false, Qt::UserRole - 1);
+ }
+ indicator_combo_->addItem(ind.label, ind.id);
+ }
+}
+
+IndicatorDef OperandEditor::current_def() const {
+ const QString id = indicator_combo_->currentData().toString();
+ for (const auto& ind : algo_indicators())
+ if (ind.id == id)
+ return ind;
+ return {};
+}
+
+void OperandEditor::rebuild_params() {
+ // Tear down existing param spins.
+ QLayoutItem* item;
+ while ((item = params_layout_->takeAt(0)) != nullptr) {
+ if (item->widget())
+ item->widget()->deleteLater();
+ delete item;
+ }
+ param_spins_.clear();
+ param_names_.clear();
+
+ const auto def = current_def();
+ for (const auto& p : def.params) {
+ auto* lbl = new QLabel(p.name + ":", params_container_);
+ lbl->setObjectName(QStringLiteral("operandParamLabel"));
+ auto* spin = new QDoubleSpinBox(params_container_);
+ spin->setObjectName(QStringLiteral("operandParam"));
+ spin->setRange(p.min, p.max);
+ spin->setDecimals(p.decimals);
+ spin->setSingleStep(p.step);
+ spin->setValue(p.def);
+ spin->setMaximumWidth(70);
+ connect(spin, QOverload<double>::of(&QDoubleSpinBox::valueChanged),
+ this, [this](double) { emit changed(); });
+ params_layout_->addWidget(lbl);
+ params_layout_->addWidget(spin);
+ param_spins_.append(spin);
+ param_names_.append(p.name);
+ }
+ params_container_->setVisible(!def.params.isEmpty());
+}
+
+void OperandEditor::on_indicator_changed() {
+ const QString id = indicator_combo_->currentData().toString();
+ if (id.isEmpty()) { // landed on a category header — skip forward
+ const int next = indicator_combo_->currentIndex() + 1;
+ if (next < indicator_combo_->count())
+ indicator_combo_->setCurrentIndex(next);
+ return;
+ }
+
+ rebuild_params();
+
+ const auto def = current_def();
+ field_combo_->clear();
+ field_combo_->addItems(def.fields.isEmpty() ? QStringList{"value"} : def.fields);
+ // Output/field selector only matters for multi-output indicators.
+ field_combo_->setVisible(field_combo_->count() > 1);
+
+ emit changed();
+}
+
+void OperandEditor::on_mode_changed() {
+ apply_mode_visibility();
+ emit changed();
+}
+
+void OperandEditor::apply_mode_visibility() {
+ const bool value_mode = is_value_mode();
+ indicator_combo_->setVisible(!value_mode);
+ params_container_->setVisible(!value_mode && !current_def().params.isEmpty());
+ field_combo_->setVisible(!value_mode && field_combo_->count() > 1);
+ offset_btn_->setVisible(!value_mode);
+ offset_combo_->setVisible(!value_mode && offset_btn_->isChecked());
+ value_spin_->setVisible(value_mode);
+}
+
+// ── State accessors ─────────────────────────────────────────────────────────
+
+bool OperandEditor::is_value_mode() const {
+ return mode_combo_ && mode_combo_->currentData().toString() == "value";
+}
+
+double OperandEditor::value() const { return value_spin_->value(); }
+
+QString OperandEditor::indicator_id() const { return indicator_combo_->currentData().toString(); }
+
+QJsonObject OperandEditor::params() const {
+ QJsonObject obj;
+ for (int i = 0; i < param_spins_.size(); ++i) {
+ const double v = param_spins_[i]->value();
+ // Integer-valued params serialize as ints; fractional (multiplier/std_dev) stay double.
+ if (param_spins_[i]->decimals() == 0)
+ obj[param_names_[i]] = static_cast<int>(v);
+ else
+ obj[param_names_[i]] = v;
+ }
+ return obj;
+}
+
+QString OperandEditor::field() const {
+ return field_combo_->count() > 0 ? field_combo_->currentText() : QStringLiteral("value");
+}
+
+int OperandEditor::offset() const {
+ return (offset_btn_ && offset_btn_->isChecked()) ? offset_combo_->currentData().toInt() : 0;
+}
+
+// ── State setters ───────────────────────────────────────────────────────────
+
+void OperandEditor::set_value_mode(bool on) {
+ if (mode_combo_)
+ mode_combo_->setCurrentIndex(on ? 1 : 0);
+ apply_mode_visibility();
+}
+
+void OperandEditor::set_value(double v) { value_spin_->setValue(v); }
+
+void OperandEditor::set_indicator(const QString& id) {
+ for (int i = 0; i < indicator_combo_->count(); ++i) {
+ if (indicator_combo_->itemData(i).toString() == id) {
+ indicator_combo_->setCurrentIndex(i);
+ return;
+ }
+ }
+}
+
+void OperandEditor::set_params(const QJsonObject& p) {
+ for (int i = 0; i < param_spins_.size(); ++i)
+ if (p.contains(param_names_[i]))
+ param_spins_[i]->setValue(p.value(param_names_[i]).toDouble());
+}
+
+void OperandEditor::set_field(const QString& f) {
+ const int idx = field_combo_->findText(f);
+ if (idx >= 0)
+ field_combo_->setCurrentIndex(idx);
+}
+
+void OperandEditor::set_offset(int o) {
+ if (o <= 0) {
+ offset_btn_->setChecked(false);
+ offset_combo_->setCurrentIndex(0);
+ return;
+ }
+ int idx = offset_combo_->findData(o);
+ if (idx < 0) { // a saved offset not in the preset list — add it
+ offset_combo_->addItem(tr("%1 bars ago").arg(o), o);
+ idx = offset_combo_->count() - 1;
+ }
+ offset_combo_->setCurrentIndex(idx);
+ offset_btn_->setChecked(true); // reveals the picker (and emits changed)
+}
+
+} // namespace fincept::ui::algo
diff --git a/fincept-qt/src/ui/widgets/algo/OperandEditor.h b/fincept-qt/src/ui/widgets/algo/OperandEditor.h
new file mode 100644
index 000000000..7077da7ee
--- /dev/null
+++ b/fincept-qt/src/ui/widgets/algo/OperandEditor.h
@@ -0,0 +1,71 @@
+// src/ui/widgets/algo/OperandEditor.h
+#pragma once
+#include "services/algo_trading/AlgoTradingTypes.h"
+
+#include <QComboBox>
+#include <QDoubleSpinBox>
+#include <QHBoxLayout>
+#include <QJsonObject>
+#include <QLabel>
+#include <QPushButton>
+#include <QVector>
+#include <QWidget>
+
+namespace fincept::ui::algo {
+
+/// One side of a comparison. Symmetric: the same widget builds the left operand
+/// and the right operand of a condition. An operand is either an indicator
+/// reference (id + per-indicator params + named output field + bar offset) or,
+/// when `allow_value` is set and the user picks "Value", a plain constant.
+///
+/// Parameter spin-boxes and the output/field dropdown are built dynamically from
+/// the selected indicator's catalog entry (algo_indicators()); the field combo
+/// is shown only for multi-output indicators.
+class OperandEditor : public QWidget {
+ Q_OBJECT
+public:
+ explicit OperandEditor(bool allow_value, QWidget* parent = nullptr);
+
+ bool is_value_mode() const;
+ double value() const;
+ QString indicator_id() const;
+ QJsonObject params() const;
+ QString field() const;
+ int offset() const;
+
+ void set_value_mode(bool on);
+ void set_value(double v);
+ void set_indicator(const QString& id);
+ void set_params(const QJsonObject& p);
+ void set_field(const QString& f);
+ void set_offset(int o);
+
+signals:
+ void changed();
+
+private:
+ void build_ui();
+ void populate_indicators();
+ void on_mode_changed();
+ void on_indicator_changed();
+ void rebuild_params();
+ services::algo::IndicatorDef current_def() const;
+ void apply_mode_visibility();
+
+ bool allow_value_;
+
+ QComboBox* mode_combo_ = nullptr; // only present when allow_value_
+ QComboBox* indicator_combo_ = nullptr;
+ QWidget* params_container_ = nullptr;
+ QHBoxLayout* params_layout_ = nullptr;
+ QVector<QDoubleSpinBox*> param_spins_;
+ QVector<QString> param_names_;
+ QComboBox* field_combo_ = nullptr;
+ // Bar-offset is an advanced, opt-in control: hidden until the user clicks the
+ // small "⋯ bar" toggle, then a plain-language picker ("Current bar / 1 bar ago").
+ QPushButton* offset_btn_ = nullptr;
+ QComboBox* offset_combo_ = nullptr;
+ QDoubleSpinBox* value_spin_ = nullptr;
+};
+
+} // namespace fincept::ui::algo
diff --git a/fincept-qt/src/ui/widgets/algo/RiskManagementPanel.cpp b/fincept-qt/src/ui/widgets/algo/RiskManagementPanel.cpp
index 76a2cb437..2fcc47e0a 100644
--- a/fincept-qt/src/ui/widgets/algo/RiskManagementPanel.cpp
+++ b/fincept-qt/src/ui/widgets/algo/RiskManagementPanel.cpp
@@ -25,6 +25,7 @@ RiskManagementPanel::RiskManagementPanel(QWidget* parent)
stop_loss_ = create_row(tr("Stop Loss %"), 0, 50, 2.0, 1, this);
take_profit_ = create_row(tr("Take Profit %"), 0, 100, 5.0, 1, this);
trailing_stop_ = create_row(tr("Trailing Stop %"), 0, 50, 0, 1, this);
+ capital_pct_ = create_row(tr("Capital Alloc %"), 1, 100, 100, 0, this);
grid->addWidget(stop_loss_.label, 0, 0);
grid->addWidget(stop_loss_.slider, 0, 1);
@@ -35,6 +36,9 @@ RiskManagementPanel::RiskManagementPanel(QWidget* parent)
grid->addWidget(trailing_stop_.label, 2, 0);
grid->addWidget(trailing_stop_.slider, 2, 1);
grid->addWidget(trailing_stop_.spin, 2, 2);
+ grid->addWidget(capital_pct_.label, 3, 0);
+ grid->addWidget(capital_pct_.slider, 3, 1);
+ grid->addWidget(capital_pct_.spin, 3, 2);
// Quantity
auto* qty_label = new QLabel(tr("Quantity"), this);
@@ -43,8 +47,8 @@ RiskManagementPanel::RiskManagementPanel(QWidget* parent)
quantity_spin_->setRange(1, 100000);
quantity_spin_->setDecimals(0);
quantity_spin_->setValue(1);
- grid->addWidget(qty_label, 3, 0);
- grid->addWidget(quantity_spin_, 3, 1, 1, 2);
+ grid->addWidget(qty_label, 4, 0);
+ grid->addWidget(quantity_spin_, 4, 1, 1, 2);
// Max order value
auto* mov_label = new QLabel(tr("Max Order Value"), this);
@@ -54,8 +58,8 @@ RiskManagementPanel::RiskManagementPanel(QWidget* parent)
max_order_spin_->setDecimals(0);
max_order_spin_->setValue(0);
max_order_spin_->setSpecialValueText(tr("No Limit"));
- grid->addWidget(mov_label, 4, 0);
- grid->addWidget(max_order_spin_, 4, 1, 1, 2);
+ grid->addWidget(mov_label, 5, 0);
+ grid->addWidget(max_order_spin_, 5, 1, 1, 2);
layout->addLayout(grid);
@@ -96,13 +100,15 @@ double RiskManagementPanel::take_profit() const { return take_profit_.spin->valu
double RiskManagementPanel::trailing_stop() const { return trailing_stop_.spin->value(); }
double RiskManagementPanel::quantity() const { return quantity_spin_->value(); }
double RiskManagementPanel::max_order_value() const { return max_order_spin_->value(); }
+double RiskManagementPanel::capital_pct() const { return capital_pct_.spin->value(); }
-void RiskManagementPanel::set_values(double sl, double tp, double ts, double qty, double mov) {
+void RiskManagementPanel::set_values(double sl, double tp, double ts, double qty, double mov, double capital_pct) {
stop_loss_.spin->setValue(sl);
take_profit_.spin->setValue(tp);
trailing_stop_.spin->setValue(ts);
quantity_spin_->setValue(qty);
max_order_spin_->setValue(mov);
+ capital_pct_.spin->setValue(capital_pct);
}
} // namespace fincept::ui::algo
diff --git a/fincept-qt/src/ui/widgets/algo/RiskManagementPanel.h b/fincept-qt/src/ui/widgets/algo/RiskManagementPanel.h
index 71814a171..04048802e 100644
--- a/fincept-qt/src/ui/widgets/algo/RiskManagementPanel.h
+++ b/fincept-qt/src/ui/widgets/algo/RiskManagementPanel.h
@@ -17,8 +17,9 @@ public:
double trailing_stop() const;
double quantity() const;
double max_order_value() const;
+ double capital_pct() const; // % of capital allocated per backtest entry
- void set_values(double sl, double tp, double ts, double qty, double mov);
+ void set_values(double sl, double tp, double ts, double qty, double mov, double capital_pct = 100.0);
signals:
void values_changed();
@@ -36,6 +37,7 @@ private:
SliderRow stop_loss_;
SliderRow take_profit_;
SliderRow trailing_stop_;
+ SliderRow capital_pct_;
QDoubleSpinBox* quantity_spin_ = nullptr;
QDoubleSpinBox* max_order_spin_ = nullptr;
};
diff --git a/fincept-qt/v2.txt b/fincept-qt/v2.txt
new file mode 100644
index 000000000..fc08631de
--- /dev/null
+++ b/fincept-qt/v2.txt
@@ -0,0 +1,2 @@
+### files defining connectBroker / calling exchange_token ###
+(eval):3: no matches found: --include=*.cpp