この戦略は,FMZプラットフォームが提供するExchange APIを使用して取引を行う. 主ループでは,まずK線データを取得し,次に現在の価格を取得する. 現在の価格が前回の購入価格の一定比以下であれば,停止損失操作を行います. 現在の価格が前回の購入価格の一定比以上であれば,停止停止停止操作を行います. 現在保有していない場合は,購入初期ポジション操作を行います. 現在の保有数が設定された最大保有量よりも少ない場合は,加仓操作を行います. 最後に,次のサイクルを待機します. 注意すべきは,マーティン戦略には一定のリスクがあり,慎重に操作する必要があります.
import time # 初始化策略参数 symbol = 'huobip/btc_usdt' period = '1m' amount = 0.01 martingale_factor = 2 max_martingale_times = 5 stop_loss = 0.05 stop_profit = 0.1 last_buy_price = 0 martingale_times = 0 # 连接API exchange = Exchange() exchange.SetContractType(symbol) exchange.SetPeriod(period) # 主循环 while True: # 获取K线数据 klines = exchange.GetRecords() if not klines: continue # 获取当前价格 current_price = float(klines[-1]['Close']) # 判断是否需要加仓 if last_buy_price != 0 and current_price < last_buy_price * (1 - stop_loss): # 止损,卖出所有持仓 sell_price = current_price sell_amount = exchange.GetPosition()['Amount'] exchange.Sell(sell_price, sell_amount) last_buy_price = 0 martingale_times = 0 print('止损,卖出所有持仓,价格', sell_price) elif last_buy_price != 0 and current_price > last_buy_price * (1 + stop_profit): # 止盈,卖出所有持仓 sell_price = current_price sell_amount = exchange.GetPosition()['Amount'] exchange.Sell(sell_price, sell_amount) last_buy_price = 0 martingale_times = 0 print('止盈,卖出所有持仓,价格', sell_price) elif last_buy_price == 0: # 买入一份初始仓位 buy_price = current_price buy_amount = amount / buy_price exchange.Buy(buy_price, buy_amount) last_buy_price = buy_price martingale_times = 0 print('买入初始仓位,价格', buy_price) elif martingale_times < max_martingale_times: # 加仓 buy_price = current_price * martingale_factor buy_amount = amount / buy_price exchange.Buy(buy_price, buy_amount) last_buy_price = (last_buy_price * martingale_times + buy_price) / (martingale_times + 1) martingale_times += 1 print('加仓,价格', buy_price) # 等待下一次循环 time.sleep(60)