簡體   English   中英

實時算法交易專家的邏輯

[英]Logic for real-time Algo trading expert

我做了一個交易專家,通過燭台檢查是否找到信號然后執行買入、賣出訂單

for i in range (len(df['Open'])) : 
  if some logic :
     buy or sell

現在我希望這位專家處理實時數據,而不是歷史數據,我很難確定它是如何工作的邏輯

我想做的是:

尋找最后 30 根柱線,然后對它們進行一些計算,然后 go 循環檢查最后 2 個燭台,看看是否找到了一些信號。我希望循環每 4 小時工作一次,因為我正在工作 4 小時時間范圍,因此對於每個新燭台

我正在嘗試使用 MetaTrader5 庫

copy_rates_from_pos(
       symbol,       // symbol name
       timeframe,    // timeframe
       start_pos,    // initial bar index
       count         // number of bars
       )

這段代碼將幫助我找到最后 30 個小節,但我仍然無法理解如何制作 for 循環!

你可以使用這樣的東西

import pytz
import pandas as pd
import MetaTrader5 as mt5
import time
from datetime import datetime
from threading import Timer



server_name = "AMPGlobalUSA-Demo"
server_num = # your server num
password = # password



#------------------------------------------------------------------------------
def actualtime():
    # datetime object containing current date and time
    now = datetime.now()
    dt_string = now.strftime("%d/%m/%Y %H:%M:%S")
    #print("date and time =", dt_string)
    return str(dt_string)
#------------------------------------------------------------------------------
def sync_60sec(op):

    info_time_new = datetime.strptime(str(actualtime()), '%d/%m/%Y %H:%M:%S')
    waiting_time = 60 - info_time_new.second

    t = Timer(waiting_time, op)
    t.start()

    print(actualtime(), f'waiting till next minute and 00 sec...')
#------------------------------------------------------------------------------
def program(symbol):
    if not mt5.initialize(login=server_num, server=server_name, password=password):
        print("initialize() failed, error code =",mt5.last_error())
        quit()

    timezone = pytz.timezone("Etc/UTC")
    utc_from = datetime.now()

    ######### Change here the timeframe
    rates = mt5.copy_rates_from(symbol, mt5.TIMEFRAME_M1, utc_from, 70)

    mt5.shutdown()

    rates_frame = pd.DataFrame(rates)
    rates_frame['time']=pd.to_datetime(rates_frame['time'], unit='s')

    # If you want to work only with open, high, low, close you could use
    #rates_frame = rates_frame.drop(['tick_volume', 'real_volume'], axis=1)

    print(f"\n", actualtime(),f"|| waiting for signals {symbol} ||\n")

    if not mt5.initialize():
        print("initialize() failed, error code =",mt5.last_error())
        quit()

    point = mt5.symbol_info(symbol).point
    price = mt5.symbol_info_tick(symbol).ask

    request = {
                "action": mt5.TRADE_ACTION_PENDING,
                "symbol": symbol,
                "volume": 1.0,
                "type": mt5.ORDER_TYPE_BUY_LIMIT,
                "price": price,
                "sl": price + 40 * point,
                "tp": price - 80 * point,
                "deviation": 20,
                "magic": 234000,
                "comment": "st_1_min_mod_3",
                "type_time": mt5.ORDER_TIME_GTC,
                "type_filling": mt5.ORDER_FILLING_RETURN,
            }


    condition_buy_1 = (
        (rates_frame.close.iloc[-2] > rates_frame.open.iloc[-2])& 
        (rates_frame.close.iloc[-2] > rates_frame.close.iloc[-3])
    )

    if condition_buy_1:
        #result = mt5.order_send(request)
        print('Sending Order!')


# Im using AMPGlobalUSA-Demo Server
# starting mt5
if not mt5.initialize(login=server_num, server=server_name, password=password):
    print("initialize() failed, error code =",mt5.last_error())
    quit()          
#------------------------------------------------------------------------------
#                   S T A R T I N G   M T 5 
#------------------------------------------------------------------------------
authorized=mt5.login(server_num, password=password)
if authorized:
    account_info=mt5.account_info()
    if account_info!=None:       
        account_info_dict = mt5.account_info()._asdict()
        df=pd.DataFrame(list(account_info_dict.items()),columns=['property','value'])
        print("account_info() as dataframe:")
        print(df)
else:
    print(f"failed to connect to trade account {server_num} with password={password}, error code =",mt5.last_error())

mt5.shutdown()
#------------------------------------------------------------------------------
def trading_bot():
    symbol_1 = 'EURUSD'
    symbol_2 = 'EURCAD'
    while True:
        program(symbol_1)
        program(symbol_2)
        time.sleep(59.8) # it depends on your computer and ping

sync_60sec(trading_bot)

在這里,您將了解如何連接和操作 Python 和 MT5。 您可以將其保存為 py 文件。 您有第一個腳本在 1 分鍾圖表中為您的交易品種尋找信號。 您可以使用兩個不同的腳本來尋找 5 分鍾和 15 分鍾圖表中的信號(program_5min.py 和 program_15min.py)。 然后,您應該添加一個新的同步 function。 例如,對於 5 分鍾,您必須等待 1 小時和 0、5、10、15 分鍾等等。

希望它對你有用,玩得開心!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM