### Initialize Main Engine and Webhook Server Source: https://github.com/51bitquant/howtrader/blob/main/docs/howtrader项目下面的配置文件讲解.md The main_window.py script initializes the event engine, configures gateways and applications, and starts a Flask-based webhook server for TradingView signals. ```python from howtrader.event import EventEngine, Event from howtrader.trader.event import EVENT_TV_SIGNAL from howtrader.trader.engine import MainEngine from howtrader.trader.ui import MainWindow, create_qapp from howtrader.trader.setting import SETTINGS from howtrader.gateway.binance import BinanceUsdtGateway, BinanceSpotGateway, BinanceInverseGateway from howtrader.app.cta_strategy import CtaStrategyApp # from howtrader.app.data_manager import DataManagerApp # from howtrader.app.data_recorder import DataRecorderApp # from howtrader.app.algo_trading import AlgoTradingApp # from howtrader.app.risk_manager import RiskManagerApp # from howtrader.app.spread_trading import SpreadTradingApp from howtrader.app.tradingview import TradingViewApp from threading import Thread import json from flask import Flask, request # create global event_engine event_engine: EventEngine = EventEngine() passphrase = SETTINGS.get("passphrase", "") port = SETTINGS.get("port", 9999) app = Flask(__name__) @app.route('/', methods=['GET']) def welcome(): return "Hi, this is tv server!" @app.route('/webhook', methods=['POST']) def webhook(): try: data = json.loads(request.data) if data.get('passphrase', None) != passphrase: return {"status": "failure", "msg": "passphrase is incorrect"} del data['passphrase'] # del it for safety. event: Event = Event(type=EVENT_TV_SIGNAL, data=data) event_engine.put(event) return {"status": "success", "msg": ""} except Exception as error: return {"status": "error", "msg": str(error)} def start_tv_server(): app.run(host="127.0.0.1", port=port) def main(): """""" qapp = create_qapp() main_engine = MainEngine(event_engine) main_engine.add_gateway(BinanceSpotGateway) main_engine.add_gateway(BinanceUsdtGateway) main_engine.add_gateway(BinanceInverseGateway) main_engine.add_app(CtaStrategyApp) main_engine.add_app(TradingViewApp) # if you don't use # main_engine.add_app(DataManagerApp) # main_engine.add_app(AlgoTradingApp) # main_engine.add_app(DataRecorderApp) # main_engine.add_app(RiskManagerApp) # main_engine.add_app(SpreadTradingApp) main_window = MainWindow(main_engine, event_engine) main_window.showMaximized() t1 = Thread(target=start_tv_server) t1.daemon = True t1.start() qapp.exec() if __name__ == "__main__": main() ``` -------------------------------- ### Execute Anaconda Installer Source: https://github.com/51bitquant/howtrader/blob/main/docs/linux下安装anaconda.md Run the downloaded shell script with root privileges to begin the installation process. ```bash sudo bash Anaconda3-2022.05-Linux-x86_64.sh ``` -------------------------------- ### Install TA-Lib on macOS Source: https://github.com/51bitquant/howtrader/blob/main/README-CN.md Use Homebrew to install the TA-Lib system dependency followed by the Python library. ```bash brew install ta-lib pip install TA-Lib ``` -------------------------------- ### Troubleshoot TA-Lib Installation Source: https://github.com/51bitquant/howtrader/blob/main/README-CN.md Commands to clean up existing TA-Lib installations and reinstall using conda-forge. ```bash brew uninstall ta-lib pip uninstall ta-lib conda install -y -c conda-forge ta-lib ``` -------------------------------- ### Check HowTrader Version Source: https://github.com/51bitquant/howtrader/blob/main/README-CN.md Verify the installed version of the HowTrader library. ```python import howtrader print(howtrader.__version__) ``` -------------------------------- ### Configure Proxy and Execute Download Source: https://github.com/51bitquant/howtrader/blob/main/README-CN.md Main entry point to configure network proxies and trigger the download functions for spot and futures data. ```python if __name__ == '__main__': """ read the code before run it. the software crawl the binance data then save into the sqlite database. you may need to change the start date and end date. """ # proxy_host , if you can directly connect to the binance exchange, then set it to None or empty string "",如果没有你就设置为 None 或者空的字符串 "", # you can use the command ping api.binance.com to check whether your network work well: 你可以在终端运行 ping api.binance.com 查看你的网络是否正常。 proxy_host = "127.0.0.1" # set it to your proxy_host 如果没有就设置为"", 如果有就设置为你的代理主机如:127.0.0.1 proxy_port = 1087 # set it to your proxy_port 设置你的代理端口号如: 1087, 没有你修改为0,但是要保证你能访问api.binance.com这个主机。 proxies = None if proxy_host and proxy_port: proxy = f'http://{proxy_host}:{proxy_port}' proxies = {'http': proxy, 'https': proxy} download_future(symbol="BTCUSDT") # crawl usdt_future data. 下载合约的数据 download_spot(symbol="BTCUSDT") # crawl binance spot data. ``` -------------------------------- ### Initialize HowTrader Main Engine Source: https://github.com/51bitquant/howtrader/blob/main/README-CN.md A template for setting up the main engine, gateways, and a Flask webhook server for TradingView signals. ```python from howtrader.event import EventEngine, Event from howtrader.trader.event import EVENT_TV_SIGNAL from howtrader.trader.engine import MainEngine from howtrader.trader.ui import MainWindow, create_qapp from howtrader.trader.setting import SETTINGS from howtrader.gateway.binance import BinanceUsdtGateway, BinanceSpotGateway, BinanceInverseGateway from howtrader.app.cta_strategy import CtaStrategyApp # from howtrader.app.data_manager import DataManagerApp # from howtrader.app.data_recorder import DataRecorderApp # from howtrader.app.algo_trading import AlgoTradingApp # from howtrader.app.risk_manager import RiskManagerApp # from howtrader.app.spread_trading import SpreadTradingApp from howtrader.app.tradingview import TradingViewApp from threading import Thread import json from flask import Flask, request # create global event_engine event_engine: EventEngine = EventEngine() passphrase = SETTINGS.get("passphrase", "") port = SETTINGS.get("port", 9999) app = Flask(__name__) @app.route('/', methods=['GET']) def welcome(): return "Hi, this is tv server!" @app.route('/webhook', methods=['POST']) def webhook(): try: data = json.loads(request.data) if data.get('passphrase', None) != passphrase: return {"status": "failure", "msg": "passphrase is incorrect"} del data['passphrase'] # del it for safety. event:Event = Event(type=EVENT_TV_SIGNAL, data=data) event_engine.put(event) return {"status": "success", "msg": ""} except Exception as error: return {"status": "error", "msg": str(error)} def start_tv_server(): app.run(host="127.0.0.1", port=port) def main(): """""" qapp = create_qapp() main_engine = MainEngine(event_engine) main_engine.add_gateway(BinanceSpotGateway) main_engine.add_gateway(BinanceUsdtGateway) main_engine.add_gateway(BinanceInverseGateway) main_engine.add_app(CtaStrategyApp) main_engine.add_app(TradingViewApp) # if you don't use # main_engine.add_app(DataManagerApp) # main_engine.add_app(AlgoTradingApp) # main_engine.add_app(DataRecorderApp) # main_engine.add_app(RiskManagerApp) # main_engine.add_app(SpreadTradingApp) main_window = MainWindow(main_engine, event_engine) main_window.showMaximized() t1 = Thread(target=start_tv_server) t1.daemon = True t1.start() qapp.exec() if __name__ == "__main__": main() ``` -------------------------------- ### Ubuntu Nginx 安装与管理命令 Source: https://github.com/51bitquant/howtrader/blob/main/README-CN.md 在 Ubuntu 系统上通过 apt 安装 Nginx 并进行服务管理。 ```bash sudo apt update ``` ```bash sudo apt upgrade ``` ```bash sudo apt install build-essential ``` ```bash sudo apt install nginx ``` ```bash sudo service nginx start # 启动 ``` ```bash sudo service nginx reload # 重新加载 ``` ```bash sudo service nginx stop # 停止 ``` -------------------------------- ### 策略初始化与数据恢复逻辑 Source: https://github.com/51bitquant/howtrader/blob/main/docs/策略重启时如何获取策略保存中的数据.md 展示了策略引擎如何从缓存中恢复变量值并调用on_init回调函数。 ```python def init_strategy(self, strategy_name: str) -> Future: """ Init a strategy. """ return self.init_executor.submit(self._init_strategy, strategy_name) def _init_strategy(self, strategy_name: str) -> None: """ Init strategies in queue. """ strategy: TVTemplate = self.strategies[strategy_name] if strategy.inited: self.write_log(f"{strategy_name} already initialized") return self.write_log(f"start initializing {strategy_name}") # Restore strategy data(variables) data: Optional[dict] = self.strategy_data.get(strategy_name, None) if data: for name in strategy.variables: value = data.get(name, None) if value is not None: if name == 'pos': setattr(strategy, name, Decimal(str(value))) else: setattr(strategy, name, value) # Call on_init function of strategy self.call_strategy_func(strategy, strategy.on_init) # Subscribe market data contract: Optional[ContractData] = self.main_engine.get_contract(strategy.vt_symbol) if contract: req: SubscribeRequest = SubscribeRequest( symbol=contract.symbol, exchange=contract.exchange) self.main_engine.subscribe(req, contract.gateway_name) else: self.write_log(f"failed to subscribe market data, symbol not found: {strategy.vt_symbol}", strategy) # Put event to update init completed status. strategy.inited = True self.put_strategy_event(strategy) self.write_log(f"finish initializing {strategy_name}") ``` -------------------------------- ### Nginx 进程与配置检查 Source: https://github.com/51bitquant/howtrader/blob/main/README-CN.md 用于查看 Nginx 进程状态及验证配置文件正确性的命令。 ```bash ps -ef | grep nginx # 查看nginx 的进程 ``` ```bash ./nginx -t ``` -------------------------------- ### Perform Backtesting and Parameter Optimization Source: https://github.com/51bitquant/howtrader/blob/main/README-CN.md Initializes the BacktestingEngine with specific market parameters and runs a genetic algorithm optimization for strategy variables. ```python from howtrader.app.cta_strategy.backtesting import BacktestingEngine, OptimizationSetting from howtrader.trader.object import Interval from datetime import datetime from strategies.atr_rsi_strategy import AtrRsiStrategy # 要导入你回测的策略,你自己开发的。 engine = BacktestingEngine() engine.set_parameters( vt_symbol="BTCUSDT.BINANCE", interval=Interval.MINUTE, start=datetime(2020, 1, 1), end=datetime(2020, 5, 1), rate=4/10000, slippage=0, size=1, pricetick=0.01, capital=1000000, ) engine.add_strategy(AtrRsiStrategy, {}) engine.load_data() engine.run_backtesting() df = engine.calculate_result() engine.calculate_statistics() engine.show_chart() setting = OptimizationSetting() setting.set_target("sharpe_ratio") setting.add_parameter("atr_length", 3, 39, 1) setting.add_parameter("atr_ma_length", 10, 30, 1) result = engine.run_ga_optimization(setting) # 优化策略参数 print(result) # 打印回测的结果,结果中会有比较好的结果值。 ``` -------------------------------- ### 管理 Conda 虚拟环境 Source: https://github.com/51bitquant/howtrader/blob/main/README-CN.md 创建、卸载及激活 Conda 虚拟环境的操作命令。 ```bash conda create -n mytrader python==3.9 ``` ```bash conda remove -n mytrader --all ``` ```bash conda deactivate ``` ```bash conda activate mytrader ``` -------------------------------- ### 安装Howtrader库 Source: https://github.com/51bitquant/howtrader/blob/main/docs/如何在window和MacOS上运行howtrader.md 通过pip从GitHub仓库安装Howtrader。 ```bash pip install git+https://github.com/51bitquant/howtrader.git ``` -------------------------------- ### Windows Nginx 操作命令 Source: https://github.com/51bitquant/howtrader/blob/main/README-CN.md 用于在 Windows 环境下启动、停止和重载 Nginx 服务。 ```bash start nginx.exe ``` ```bash nginx.exe -s stop ``` ```bash nginx.exe -s quit ``` ```bash nginx.exe -s reload (reload) ``` -------------------------------- ### 安装TA-Lib库 Source: https://github.com/51bitquant/howtrader/blob/main/docs/如何在window和MacOS上运行howtrader.md 通过下载的whl文件安装TA-Lib,需确保切换到文件所在目录。 ```bash pip install TA_Lib‑0.4.24‑cp39‑cp39‑win_amd64.whl ``` -------------------------------- ### 定义最优限价单策略类 Source: https://github.com/51bitquant/howtrader/blob/main/docs/如何定制tradingview下单信号.md 通过继承TVTemplate实现MyTVBestLimitStrategy,包含订单拆分、最优价格下单及信号解析逻辑。 ```python from howtrader.app.tradingview.template import TVTemplate from howtrader.app.tradingview.engine import TVEngine from howtrader.trader.object import TickData, TradeData, OrderData, ContractData, Product from typing import Optional from howtrader.event import Event, EVENT_TIMER from decimal import Decimal from howtrader.trader.utility import round_to from random import uniform from howtrader.trader.object import Direction class MyTVBestLimitStrategy(TVTemplate): """Place Best Limit order for TV strategy for multi signals split a large order to small order, and use best limit price to place order automatically until it filled. For more detail, read the codes below. 使用最优价格(买一/卖一)去下限价单,把大单拆成小单,不断去循环下单,直到下单完成。 """ author: str = "51bitquant" # the order volume you want to trade, if you trade BTCUSDT, the volume is BTC amount, if you set zero, will use from TV or other signal. # 订单的数量,如果你是交易BTCUSDT, 这个数量是BTC的数量, 如果设置为零,那么交易使用会使用来自tradingview或则其他第三方的信号 order_volume: float = 0.0 # place max order volume per order 单次最大的下单数量. min_volume_per_order: float = 0.0 max_volume_per_order: float = 0.0 parameters: list = ["order_volume","min_volume_per_order", "max_volume_per_order"] def __init__( self, tv_engine: TVEngine, strategy_name: str, tv_id:str, vt_symbol: str, setting: dict, ) -> None: """""" super().__init__(tv_engine, strategy_name, tv_id, vt_symbol, setting) self.last_tick: Optional[TickData] = None self.orders: list = [] self.order_price: float = 0 self.target_volume: Decimal = Decimal("0") # trade volume target 需要交易的数量. self.traded_volume: Decimal = Decimal("0") # have already traded volume 已经交易的数量 self.direction: Optional[Direction] = None # self.contract: Optional[ContractData] = tv_engine.main_engine.get_contract(vt_symbol) self.signals = [] # store the signals. def on_init(self) -> None: """ Callback when strategy is inited. """ self.write_log("strategy inited") def on_start(self) -> None: """ Callback when strategy is started. """ self.write_log("strategy started") def on_stop(self): """ Callback when strategy is stopped. """ self.write_log("strategy stop") def on_tick(self, tick: TickData): """""" self.last_tick = tick if self.direction == Direction.LONG: if len(self.orders) == 0: self.buy_best_limit() elif self.order_price != self.last_tick.bid_price_1: self.cancel_all() elif self.direction == Direction.SHORT: if len(self.orders) == 0: self.sell_best_limit() elif self.order_price != self.last_tick.ask_price_1: self.cancel_all() else: if len(self.signals) > 0: signal = self.signals.pop(0) self.resolve_signal(signal) def resolve_signal(self, signal: dict) -> None: action = signal.get('action', None) if action is None: self.write_log(f"current action is : {action}") return None action = action.lower() # 把信号转成小写了。 if self.contract is None: self.write_log('contract is None, did you connect to the exchange?') return None if self.order_volume > 0: v = str(self.order_volume) volume = round_to(Decimal(v), self.contract.min_volume) else: v = signal.get('volume', None) if v is None: self.write_log("missing volume from signal for placing order volume.") return None volume = round_to(Decimal(str(v)), self.contract.min_volume) volume = abs(volume) self.traded_volume = Decimal("0") if action == 'l_1': if self.pos < 0: self.target_volume = volume + abs(self.pos) else: self.target_volume = volume self.direction = Direction.LONG elif action == 'l_2': self.target_volume = volume self.direction = Direction.LONG ``` -------------------------------- ### Configure vt_setting.json Source: https://github.com/51bitquant/howtrader/blob/main/docs/howtrader项目下面的配置文件讲解.md The vt_setting.json file contains global application settings including logging, email notifications, database connection parameters, and webhook server configuration. ```json "font.family": "", "font.size": 12, "log.active": True, "log.level": CRITICAL, "log.console": True, "log.file": True, "email.server": "smtp.qq.com", "email.port": 465, "email.username": "", "email.password": "", "email.sender": "", "email.receiver": "", "update_interval": 600, "passphrase": "howtrader", # tv passphrase "port": 9999, # tv server port "datafeed.name": "", "datafeed.username": "", "datafeed.password": "", "database.timezone": get_localzone_name(), "database.name": "sqlite", "database.database": "database.db", "database.host": "", "database.port": 0, "database.user": "", "database.password": "" ``` -------------------------------- ### Nginx 端口转发配置 Source: https://github.com/51bitquant/howtrader/blob/main/README-CN.md 在 nginx.conf 中配置 server 块以实现端口转发。 ```nginx server { listen 80; server_name your.dormain.com; charset utf-8; location / { proxy_pass http://localhost:8888; } } ``` -------------------------------- ### Configure HowTrader Database and System Settings Source: https://github.com/51bitquant/howtrader/blob/main/README-CN.md The configuration dictionary used in howtrader/vt_setting.json to define database connections, logging, and email notification parameters. ```dict { "font.family": "", # 设置字体,如果显示不正确的话,设置为系统的一个字体 "font.size": 12, "log.active": True, "log.level": CRITICAL, "log.console": True, "log.file": True, "email.server": "smtp.qq.com", "email.port": 465, "email.username": "", "email.password": "", "email.sender": "", "email.receiver": "", "order_update_interval": 600, # securing correct orders' status by synchronizing/updating orders through rest api "update_server_time_interval": 300, # sync with server time "passphrase": "howtrader", # tv passphrase "port": 9999, # tv server port "datafeed.name": "", "datafeed.username": "", "datafeed.password": "", "database.timezone": get_localzone_name(), "database.name": "sqlite", "database.database": "database.db", "database.host": "", "database.port": 0, "database.user": "", "database.password": "" } ``` -------------------------------- ### 使用脚本运行HowTrader CTA策略 Source: https://github.com/51bitquant/howtrader/blob/main/docs/如何在linux上运行howtrader.md 通过创建main.py脚本,初始化主引擎、连接网关并启动CTA策略引擎。 ```python import sys from time import sleep from datetime import datetime, time from logging import INFO from howtrader.event import EventEngine from howtrader.trader.setting import SETTINGS from howtrader.trader.engine import MainEngine, LogEngine from howtrader.gateway.binance import BinanceSpotGateway, BinanceUsdtGateway from howtrader.app.cta_strategy import CtaStrategyApp, CtaEngine from howtrader.app.cta_strategy.base import EVENT_CTA_LOG SETTINGS["log.active"] = True SETTINGS["log.level"] = INFO SETTINGS["log.console"] = True usdt_gateway_setting = { "key": "", "secret": "", "proxy_host": "", "proxy_port": 0, } def run(): """ Running in the child process. """ SETTINGS["log.file"] = True event_engine = EventEngine() main_engine: MainEngine = MainEngine(event_engine) main_engine.add_gateway(BinanceUsdtGateway) cta_engine: CtaEngine = main_engine.add_app(CtaStrategyApp) main_engine.write_log("setup main engine") log_engine: LogEngine = main_engine.get_engine("log") event_engine.register(EVENT_CTA_LOG, log_engine.process_log_event) main_engine.write_log("register event listener") main_engine.connect(usdt_gateway_setting, "BINANCE_USDT") main_engine.write_log("connect binance usdt gate way") sleep(10) cta_engine.init_engine() main_engine.write_log("set up cta engine") cta_engine.init_all_strategies() sleep(60) # Leave enough time to complete strategy initialization main_engine.write_log("init cta strategies") cta_engine.start_all_strategies() main_engine.write_log("start cta strategies") while True: sleep(10) if __name__ == "__main__": run() ``` -------------------------------- ### macOS Nginx 安装与管理命令 Source: https://github.com/51bitquant/howtrader/blob/main/README-CN.md 使用 Homebrew 在 macOS 上安装及管理 Nginx 服务。 ```bash brew install nginx ``` ```bash brew services start nginx ``` ```bash brew services restart nginx ``` ```bash brew services reload nginx ``` -------------------------------- ### 处理交易信号与订单执行逻辑 Source: https://github.com/51bitquant/howtrader/blob/main/docs/如何定制tradingview下单信号.md 该代码段包含订单执行的检查逻辑、信号解析函数以及信号接收回调,用于根据接收到的信号调整目标仓位并执行交易。 ```python self.timer_count = 0 if len(self.orders) > 0: self.cancel_all() return None volume = self.target_volume - self.traded_volume if volume > self.contract.min_volume and volume * tick.bid_price_1 >= 10: # 下单的价值要大于10USDT if self.direction == Direction.LONG: price = Decimal(tick.ask_price_1 * (1 + self.max_slippage_percent / 100)) price = round_to(price, self.contract.pricetick) orderids = self.buy(price, volume) self.orders.extend(orderids) elif self.direction == Direction.SHORT: price = Decimal(tick.bid_price_1 * (1 - self.max_slippage_percent / 100)) price = round_to(price, self.contract.pricetick) if self.contract.product == Product.FUTURES: # for futures market orderids = self.short(price, volume) self.orders.extend(orderids) elif self.contract.product == Product.SPOT: # for spot market orderids = self.sell(price, volume) self.orders.extend(orderids) else: self.traded_volume = Decimal("0") self.target_volume = Decimal("0") self.direction = None if len(self.signals) > 0: signal = self.signals.pop(0) self.resolve_signal(signal) def resolve_signal(self, signal: dict) -> None: action = signal.get('action', None) if action is None: self.write_log(f"current action is : {action}") return None action = action.lower() # 把信号转成小写了。 if self.contract is None: self.write_log('contract is None, did you connect to the exchange?') return None if self.order_volume > 0: v = str(self.order_volume) volume = round_to(Decimal(v), self.contract.min_volume) else: v = signal.get('volume', None) if v is None: self.write_log("missing volume from signal for placing order volume.") return None volume = round_to(Decimal(str(v)), self.contract.min_volume) volume = abs(volume) self.traded_volume = Decimal("0") if action == 'l_1': if self.pos < 0: self.target_volume = volume + abs(self.pos) else: self.target_volume = volume self.direction = Direction.LONG elif action == 'l_2': self.target_volume = volume self.direction = Direction.LONG elif action == 's_1': if self.pos > 0: self.target_volume = volume + self.pos else: self.target_volume = volume self.direction = Direction.SHORT elif action == 's_2': self.target_volume = volume self.direction = Direction.SHORT elif action == 'tp_1_l': if self.pos > 0: if self.pos >= volume: self.target_volume = volume self.direction = Direction.SHORT else: self.target_volume = self.pos self.direction = Direction.SHORT elif action == 'tp_2_l': if self.pos > 0: self.target_volume = self.pos self.direction = Direction.SHORT elif action == 'tp_1_s': if self.pos < 0: if abs(self.pos) >= volume: self.target_volume = volume self.direction = Direction.LONG else: self.target_volume = abs(self.pos) self.direction = Direction.LONG elif action == 'tp_2_s': if self.pos < 0: self.target_volume = abs(self.pos) self.direction = Direction.LONG elif action == 'exit': if abs(self.pos) < self.contract.min_volume: self.write_log(f"ignore exit signal, current pos: {self.pos}") return None self.target_volume = abs(self.pos) if self.pos > 0: self.direction = Direction.SHORT else: self.direction = Direction.LONG else: pass # extend your signal here. def on_signal(self, signal: dict) -> None: """ the signal contains """ self.write_log(f"received signal: {signal}") self.signals.append(signal) def on_order(self, order: OrderData) -> None: """ Callback of new order data update. """ if not order.is_active(): try: # if order is not active, then remove it from self.orders self.orders.remove(order.vt_orderid) except Exception: pass ``` -------------------------------- ### Implement Order and Trade Callback Logic Source: https://github.com/51bitquant/howtrader/blob/main/README.md Custom implementation of on_order and get_order to ensure on_trade is pushed before on_order, maintaining accurate position tracking. ```python def on_order(self, order: OrderData) -> None: """on order update""" order.update_time = generate_datetime(time.time() * 1000) last_order: OrderData = self.get_order(order.orderid) if not last_order: self.orders[order.orderid] = copy(order) super().on_order(copy(order)) else: traded: Decimal = order.traded - last_order.traded if traded < 0: # filter the order is not in sequence return None if traded > 0: trade: TradeData = TradeData( symbol=order.symbol, exchange=order.exchange, orderid=order.orderid, direction=order.direction, price=order.price, volume=traded, datetime=order.update_time, gateway_name=self.gateway_name, ) super().on_trade(trade) if traded == 0 and order.status == last_order.status: return None self.orders[order.orderid] = copy(order) super().on_order(copy(order)) def get_order(self, orderid: str) -> OrderData: """get order by order id""" return self.orders.get(orderid, None) ``` -------------------------------- ### 本地源码安装 HowTrader Source: https://github.com/51bitquant/howtrader/blob/main/README-CN.md 通过下载源码并在本地环境执行安装脚本。 ```bash pip install -r requirements.txt python setup.py install ``` -------------------------------- ### Implement Binance Data Crawler Source: https://github.com/51bitquant/howtrader/blob/main/README-CN.md A Python script template for fetching historical kline data from Binance and saving it to the configured database. ```python """ use the binance api to crawl data then save into the sqlite database. """ import pandas as pd import time from datetime import datetime import requests import pytz from howtrader.trader.database import get_database, BaseDatabase pd.set_option('expand_frame_repr', False) # from howtrader.trader.object import BarData, Interval, Exchange BINANCE_SPOT_LIMIT = 1000 BINANCE_FUTURE_LIMIT = 1500 from howtrader.trader.constant import LOCAL_TZ from threading import Thread database: BaseDatabase = get_database() def generate_datetime(timestamp: float) -> datetime: """ :param timestamp: :return: """ dt = datetime.fromtimestamp(timestamp / 1000) dt = LOCAL_TZ.localize(dt) return dt def get_binance_data(symbol: str, exchange: str, start_time: str, end_time: str): """ crawl binance exchange data :param symbol: BTCUSDT. :param exchange: spot、usdt_future, inverse_future. :param start_time: format :2020-1-1 or 2020-01-01 year-month-day :param end_time: format: 2020-1-1 or 2020-01-01 year-month-day :param gate_way the gateway name for binance is:BINANCE_SPOT, BINANCE_USDT, BINANCE_INVERSE :return: """ api_url = '' save_symbol = symbol gateway = "BINANCE_USDT" if exchange == 'spot': print("spot") limit = BINANCE_SPOT_LIMIT save_symbol = symbol.lower() gateway = 'BINANCE_SPOT' api_url = f'https://api.binance.com/api/v3/klines?symbol={symbol}&interval=1m&limit={limit}' elif exchange == 'usdt_future': print('usdt_future') limit = BINANCE_FUTURE_LIMIT gateway = "BINANCE_USDT" api_url = f'https://fapi.binance.com/fapi/v1/klines?symbol={symbol}&interval=1m&limit={limit}' elif exchange == 'inverse_future': print("inverse_future") limit = BINANCE_FUTURE_LIMIT gateway = "BINANCE_INVERSE" f'https://dapi.binance.com/dapi/v1/klines?symbol={symbol}&interval=1m&limit={limit}' else: raise Exception('the exchange name should be one of :spot, usdt_future, inverse_future') start_time = int(datetime.strptime(start_time, '%Y-%m-%d').timestamp() * 1000) end_time = int(datetime.strptime(end_time, '%Y-%m-%d').timestamp() * 1000) while True: try: print(start_time) url = f'{api_url}&startTime={start_time}' print(url) datas = requests.get(url=url, timeout=10, proxies=proxies).json() """ [ [ 1591258320000, // open time "9640.7", // open price "9642.4", // highest price "9640.6", // lowest price "9642.0", // close price(latest price if the kline is not close) "206", // volume 1591258379999, // close time "2.13660389", // turnover 48, // trade count "119", // buy volume "1.23424865", // buy turnover "0" // ignore ] """ buf = [] ``` -------------------------------- ### 处理订单与成交回调 Source: https://github.com/51bitquant/howtrader/blob/main/docs/如何定制tradingview下单信号.md 实现信号接收、订单状态更新及成交后的逻辑处理。 ```python def on_signal(self, signal: dict) -> None: """ the signal contains """ self.write_log(f"received signal: {signal}") self.signals.append(signal) def on_order(self, order: OrderData) -> None: """ Callback of new order data update. """ if not order.is_active(): try: # if order is not active, then remove it from self.orders self.orders.remove(order.vt_orderid) self.order_price = 0 except Exception: pass def on_trade(self, trade: TradeData): """""" self.traded_volume += trade.volume if self.traded_volume >= self.target_volume: self.write_log(f"algo trading finished: traded_volume:{self.traded_volume},target_volume:{self.target_volume}") self.traded_volume = Decimal("0") self.target_volume = Decimal("0") self.direction = None ``` -------------------------------- ### 执行限价下单与随机量计算 Source: https://github.com/51bitquant/howtrader/blob/main/docs/如何定制tradingview下单信号.md 根据目标量和随机量计算下单数量,并根据产品类型执行买入或卖出/做空操作。 ```python def buy_best_limit(self) -> None: """""" volume_left = self.target_volume - self.traded_volume rand_volume = self.generate_rand_volume() order_volume = min(rand_volume, volume_left) order_volume = round_to(order_volume, self.contract.min_volume) if order_volume < self.contract.min_volume or order_volume < 0: return None self.order_price = self.last_tick.bid_price_1 orderids = self.buy(Decimal(str(self.order_price)), order_volume) self.orders.extend(orderids) def sell_best_limit(self) -> None: """""" volume_left = self.target_volume - self.traded_volume rand_volume = self.generate_rand_volume() order_volume = min(rand_volume, volume_left) order_volume = round_to(order_volume, self.contract.min_volume) if order_volume < self.contract.min_volume or order_volume < 0: return None self.order_price = self.last_tick.ask_price_1 if self.contract.product == Product.SPOT: orderids = self.sell(Decimal(str(self.order_price)), Decimal(order_volume)) self.orders.extend(orderids) elif self.contract.product == Product.FUTURES: orderids = self.short(Decimal(str(self.order_price)), Decimal(order_volume)) self.orders.extend(orderids) def generate_rand_volume(self): """""" rand_volume = uniform(self.min_volume_per_order, self.max_volume_per_order) return Decimal(str(rand_volume)) ``` -------------------------------- ### 创建并激活Python虚拟环境 Source: https://github.com/51bitquant/howtrader/blob/main/docs/如何在window和MacOS上运行howtrader.md 使用Conda创建名为mytrader的Python 3.9环境并激活它。 ```bash conda create -n mytrader python==3.9 ``` ```bash conda activate mytrader ``` -------------------------------- ### Download Binance Spot and Future Data Source: https://github.com/51bitquant/howtrader/blob/main/README-CN.md Uses threading to concurrently download historical spot or futures data for specific date ranges. ```python def download_spot(symbol): """ download binance spot data, config your start date and end date(format: year-month-day) :return: """ t1 = Thread(target=get_binance_data, args=(symbol, 'spot', "2018-1-1", "2018-6-1")) t2 = Thread(target=get_binance_data, args=(symbol, 'spot', "2018-6-1", "2018-12-1")) t3 = Thread(target=get_binance_data, args=(symbol, 'spot', "2018-12-1", "2019-6-1")) t4 = Thread(target=get_binance_data, args=(symbol, 'spot', "2019-6-1", "2019-12-1")) t5 = Thread(target=get_binance_data, args=(symbol, 'spot', "2019-12-1", "2020-6-1")) t6 = Thread(target=get_binance_data, args=(symbol, 'spot', "2020-6-1", "2020-12-1")) t7 = Thread(target=get_binance_data, args=(symbol, 'spot', "2020-12-1", "2021-6-1")) t8 = Thread(target=get_binance_data, args=(symbol, 'spot', "2021-6-1", "2021-12-1")) t9 = Thread(target=get_binance_data, args=(symbol, 'spot', "2021-12-1", "2022-6-28")) t1.start() t2.start() t3.start() t4.start() t5.start() t6.start() t7.start() t8.start() t9.start() t1.join() t2.join() t3.join() t4.join() t5.join() t6.join() t7.join() t8.join() t9.join() ``` ```python def download_future(symbol): """ download binance future data, config your start date and end date(format: year-month-day) :return: """ t1 = Thread(target=get_binance_data, args=(symbol, 'usdt_future', "2020-1-1", "2020-6-1")) t2 = Thread(target=get_binance_data, args=(symbol, 'usdt_future', "2020-6-1", "2020-12-1")) t3 = Thread(target=get_binance_data, args=(symbol, 'usdt_future', "2020-12-1", "2021-6-1")) t4 = Thread(target=get_binance_data, args=(symbol, 'usdt_future', "2021-6-1", "2021-12-1")) t5 = Thread(target=get_binance_data, args=(symbol, 'usdt_future', "2021-12-1", "2022-6-28")) t1.start() t2.start() t3.start() t4.start() t5.start() t1.join() t2.join() t3.join() t4.join() t5.join() ``` -------------------------------- ### Importing Required Modules Source: https://github.com/51bitquant/howtrader/blob/main/examples/data_analysis/data_analysis.ipynb Initial imports for constants, the DataAnalysis class, datetime handling, and plotting. ```python from howtrader.trader.constant import Exchange,Interval from data_analysis import DataAnalysis from datetime import datetime import matplotlib.pyplot as plt ``` -------------------------------- ### 更新 Anaconda Source: https://github.com/51bitquant/howtrader/blob/main/README-CN.md 用于将已安装的 Anaconda 环境更新至最新版本。 ```bash conda update conda conda update anaconda ``` -------------------------------- ### Linux 下安装 Miniconda Source: https://github.com/51bitquant/howtrader/blob/main/README-CN.md 在 Linux 系统中下载并执行 Miniconda 安装脚本。 ```bash wget https://repo.anaconda.com/miniconda/Miniconda3-py39_23.3.1-0-Linux-x86_64.sh bash Miniconda3-py39_23.3.1-0-Linux-x86_64.sh # 执行安装 ``` -------------------------------- ### Howtrader启动脚本 Source: https://github.com/51bitquant/howtrader/blob/main/docs/如何在window和MacOS上运行howtrader.md 包含主引擎初始化、网关配置及Flask Webhook服务的完整启动代码。 ```python from howtrader.event import EventEngine, Event from howtrader.trader.event import EVENT_TV_SIGNAL from howtrader.trader.engine import MainEngine from howtrader.trader.ui import MainWindow, create_qapp from howtrader.trader.setting import SETTINGS from howtrader.gateway.binance import BinanceUsdtGateway, BinanceSpotGateway, BinanceInverseGateway from howtrader.app.cta_strategy import CtaStrategyApp # from howtrader.app.data_manager import DataManagerApp # from howtrader.app.data_recorder import DataRecorderApp # from howtrader.app.algo_trading import AlgoTradingApp # from howtrader.app.risk_manager import RiskManagerApp # from howtrader.app.spread_trading import SpreadTradingApp from howtrader.app.tradingview import TradingViewApp from threading import Thread import json from flask import Flask, request # create global event_engine event_engine: EventEngine = EventEngine() passphrase = SETTINGS.get("passphrase", "") port = SETTINGS.get("port", 9999) app = Flask(__name__) @app.route('/', methods=['GET']) def welcome(): return "Hi, this is tv server!" @app.route('/webhook', methods=['POST']) def webhook(): try: data = json.loads(request.data) if data.get('passphrase', None) != passphrase: return {"status": "failure", "msg": "passphrase is incorrect"} del data['passphrase'] # del it for safety. event:Event = Event(type=EVENT_TV_SIGNAL, data=data) event_engine.put(event) return {"status": "success", "msg": ""} except Exception as error: return {"status": "error", "msg": str(error)} def start_tv_server(): app.run(host="127.0.0.1", port=port) def main(): """""" qapp = create_qapp() main_engine = MainEngine(event_engine) main_engine.add_gateway(BinanceSpotGateway) main_engine.add_gateway(BinanceUsdtGateway) main_engine.add_gateway(BinanceInverseGateway) main_engine.add_app(CtaStrategyApp) main_engine.add_app(TradingViewApp) # if you don't use # main_engine.add_app(DataManagerApp) # main_engine.add_app(AlgoTradingApp) # main_engine.add_app(DataRecorderApp) # main_engine.add_app(RiskManagerApp) # main_engine.add_app(SpreadTradingApp) main_window = MainWindow(main_engine, event_engine) main_window.showMaximized() t1 = Thread(target=start_tv_server) t1.daemon = True t1.start() qapp.exec() if __name__ == "__main__": main() ``` -------------------------------- ### 实现交易完成后的状态重置 Source: https://github.com/51bitquant/howtrader/blob/main/docs/如何定制tradingview下单信号.md 在on_trade回调中更新已成交数量,并在达到目标数量后重置交易状态。 ```python def on_trade(self, trade: TradeData): """""" self.traded_volume += trade.volume if self.traded_volume >= self.target_volume: self.write_log( f"signal trading finished: traded_volume:{self.traded_volume},target_volume:{self.target_volume}") self.traded_volume = Decimal("0") self.target_volume = Decimal("0") self.direction = None ``` -------------------------------- ### Uninstall HowTrader Source: https://github.com/51bitquant/howtrader/blob/main/README-CN.md Use this command to remove the existing HowTrader package if updates fail or issues arise. ```bash pip uninstall howtrader ``` -------------------------------- ### Performing Base Analysis Source: https://github.com/51bitquant/howtrader/blob/main/examples/data_analysis/data_analysis.ipynb Executes the base analysis on the loaded data. ```python data = herramiento.base_analysis() ``` -------------------------------- ### 交易所接口配置示例 Source: https://github.com/51bitquant/howtrader/blob/main/docs/如何在linux上运行howtrader.md 定义连接交易所所需的API密钥及代理设置。 ```python usdt_gateway_setting = { "key": "", "secret": "", "proxy_host": "", "proxy_port": 0, } ``` -------------------------------- ### Configure System PATH for Conda Source: https://github.com/51bitquant/howtrader/blob/main/docs/linux下安装anaconda.md Edit the .bashrc file to add the Anaconda binary directory to the system PATH, then apply the changes. ```bash vi ~/.bashrc ``` ```bash PATH=/home/anaconda3/bin:$PATH ``` ```bash source ~/.bashrc ```