Phương pháp này sử dụng API trao đổi được cung cấp bởi nền tảng FMZ để giao dịch. Trong vòng tròn chính, trước tiên lấy dữ liệu đường K, sau đó lấy giá hiện tại. Nếu giá hiện tại thấp hơn một tỷ lệ nhất định so với giá mua trước, lệnh dừng lỗ được thực hiện; nếu giá hiện tại cao hơn một tỷ lệ nhất định so với giá mua trước, lệnh dừng giữ được thực hiện; nếu hiện tại không có cổ phần, lệnh mua vị trí ban đầu được thực hiện; nếu số lượng cổ phần hiện tại nhỏ hơn số lượng cổ phần tối đa được thiết lập, lệnh tăng giá được thực hiện. Cuối cùng, chờ cho vòng tiếp theo.
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)