PluginInstance.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  1. #include "pch.h"
  2. #include "PluginInstance.h"
  3. #define REDIS_TIMER_ID (1)
  4. CPluginInstance::CPluginInstance()
  5. : m_enable(false)
  6. , m_redis_error_notified(false)
  7. {
  8. }
  9. CPluginInstance::~CPluginInstance()
  10. {
  11. Stop();
  12. }
  13. void CPluginInstance::Release()
  14. {
  15. delete this;
  16. }
  17. MTAPIRES CPluginInstance::Start(IMTServerAPI * server)
  18. {
  19. MTAPIRES ret = MT_RET_OK;
  20. if (!server) return MT_RET_ERR_PARAMS;
  21. m_api = server;
  22. if ((m_config = m_api->PluginCreate()) == nullptr)
  23. return MT_RET_ERR_MEM;
  24. ret = m_api->About(m_info);
  25. if (ret != MT_RET_OK)
  26. m_api->LoggerOut(MTLogOK, L"Server info failed [%d]", ret);
  27. if ((ret = m_api->PluginSubscribe(this)) != MT_RET_OK)
  28. {
  29. m_api->LoggerOut(MTLogAtt, L"Plugin subscribe failed [%d]", ret);
  30. return ret;
  31. }
  32. if (ret = m_api->OrderSubscribe(this) != MT_RET_OK)
  33. {
  34. m_api->LoggerOut(MTLogAtt, L"Order subscribe failed [%d]", ret);
  35. return ret;
  36. }
  37. if (ret = m_api->DealSubscribe(this) != MT_RET_OK)
  38. {
  39. m_api->LoggerOut(MTLogAtt, L"Deal subscribe failed [%d]", ret);
  40. return ret;
  41. }
  42. if ((ret = LoadParam()) != MT_RET_OK)
  43. {
  44. m_api->LoggerOut(MTLogAtt, L"Load param failed [%d]", ret);
  45. return ret;
  46. }
  47. return MT_RET_OK;
  48. }
  49. MTAPIRES CPluginInstance::Stop()
  50. {
  51. MTAPIRES ret = MT_RET_OK;
  52. std::lock_guard<decltype(m_lock)> lk(m_lock);
  53. m_followers.clear();
  54. if (m_api == nullptr)
  55. return MT_RET_OK;
  56. if (m_config != nullptr)
  57. {
  58. m_config->Release();
  59. m_config = nullptr;
  60. }
  61. if ((ret = m_api->PluginUnsubscribe(this)) != MT_RET_OK && ret != MT_RET_ERR_NOTFOUND)
  62. m_api->LoggerOut(MTLogErr, L"failed to unsubscribe from plugin config updates [%s (%u)]",
  63. SMTFormat::FormatError(ret), ret);
  64. if ((ret = m_api->OrderUnsubscribe(this)) != MT_RET_OK && ret != MT_RET_ERR_NOTFOUND)
  65. m_api->LoggerOut(MTLogErr, L"failed to unsubscribe order [%s (%u)]",
  66. SMTFormat::FormatError(ret), ret);
  67. if ((ret = m_api->DealUnsubscribe(this)) != MT_RET_OK && ret != MT_RET_ERR_NOTFOUND)
  68. m_api->LoggerOut(MTLogErr, L"failed to unsubscribe deal [%s (%u)]",
  69. SMTFormat::FormatError(ret), ret);
  70. m_api = nullptr;
  71. m_enable = false;
  72. if (m_work_thread.joinable())
  73. m_work_thread.join();
  74. return MT_RET_OK;
  75. }
  76. void CPluginInstance::OnPluginUpdate(const IMTConPlugin * plugin)
  77. {
  78. int ret = MT_RET_OK;
  79. if ((ret = LoadParam()) != MT_RET_OK)
  80. {
  81. m_api->LoggerOut(MTLogAtt, L"Load param failed [%d]", ret);
  82. }
  83. }
  84. //void CPluginInstance::OnOrderAdd(const IMTOrder * order)
  85. //{
  86. // if (order == nullptr) return;
  87. //
  88. // std::lock_guard<decltype(m_lock)> lk(m_lock);
  89. // if (!m_enable) return;
  90. // if (order->Login() != m_trader) return;
  91. //
  92. // m_api->LoggerOut(MTLogOK, L"OnOrderAdd, login: %lld, ord: %lld, pos: %lld, state: %lld, vol_init: %lld, vol_cur: %lld",
  93. // order->Login(), order->Order(), order->PositionID(), order->State(), order->VolumeInitial(), order->VolumeCurrent());
  94. //}
  95. //void CPluginInstance::OnOrderUpdate(const IMTOrder * order)
  96. //{
  97. // if (order == nullptr) return;
  98. //
  99. // std::lock_guard<decltype(m_lock)> lk(m_lock);
  100. // if (!m_enable) return;
  101. // if (order->Login() != m_trader) return;
  102. //
  103. // m_api->LoggerOut(MTLogOK, L"OnOrderAdd, login: %lld, ord: %lld, pos: %lld, state: %lld, vol_init: %lld, vol_cur: %lld",
  104. // order->Login(), order->Order(), order->PositionID(), order->State(), order->VolumeInitial(), order->VolumeCurrent());
  105. //}
  106. void CPluginInstance::OnOrderDelete(const IMTOrder * order)
  107. {
  108. if (order == nullptr) return;
  109. std::lock_guard<decltype(m_lock)> lk(m_lock);
  110. if (!m_enable) return;
  111. if (order->Login() != m_trader) return;
  112. //m_api->LoggerOut(MTLogOK, L"OnOrderDelete, login: %lld, ord: %lld, pos: %lld, state: %d, vol_init: %lld, vol_cur: %lld",
  113. // order->Login(), order->Order(), order->PositionID(), order->State(), order->VolumeInitial(), order->VolumeCurrent());
  114. // 订单在进入filled状态时,也会产生一个order delete回调
  115. for (auto login : m_followers)
  116. {
  117. if (order->Order() == order->PositionID())
  118. {
  119. // 如果是新建订单,那么写入新纪录
  120. }
  121. else
  122. {
  123. // 如果不是新建订单,先使用position id先检查记录是否存在
  124. // 如果存在,则继续操作
  125. // 如果不存在,忽略
  126. }
  127. }
  128. }
  129. //void CPluginInstance::OnOrderClean(const UINT64 login)
  130. //{
  131. // std::lock_guard<decltype(m_lock)> lk(m_lock);
  132. // if (!m_enable) return;
  133. // if (login != m_trader) return;
  134. //
  135. // m_api->LoggerOut(MTLogOK, L"OnOrderClean, Login: %d", login);
  136. //}
  137. //void CPluginInstance::OnDealAdd(const IMTDeal * deal)
  138. //{
  139. // if (deal == nullptr) return;
  140. //
  141. // std::lock_guard<decltype(m_lock)> lk(m_lock);
  142. // if (!m_enable) return;
  143. // if (deal->Login() != m_trader) return;
  144. //
  145. // m_api->LoggerOut(MTLogOK, L"OnDealAdd, login: %lld, deal: %lld, ord: %lld, pos: %lld, vol: %lld, volc: %lld",
  146. // deal->Login(), deal->Deal(), deal->Order(), deal->PositionID(), deal->Volume(), deal->VolumeClosed());
  147. //}
  148. //void CPluginInstance::OnDealUpdate(const IMTDeal * deal)
  149. //{
  150. // if (deal == nullptr) return;
  151. //
  152. // std::lock_guard<decltype(m_lock)> lk(m_lock);
  153. // if (!m_enable) return;
  154. // if (deal->Login() != m_trader) return;
  155. //
  156. // m_api->LoggerOut(MTLogOK, L"OnDealUpdate, login: %lld, deal: %lld, ord: %lld, pos: %lld, vol: %lld, volc: %lld",
  157. // deal->Login(), deal->Deal(), deal->Order(), deal->PositionID(), deal->Volume(), deal->VolumeClosed());
  158. //}
  159. //void CPluginInstance::OnDealDelete(const IMTDeal * deal)
  160. //{
  161. // if (deal == nullptr) return;
  162. //
  163. // std::lock_guard<decltype(m_lock)> lk(m_lock);
  164. // if (!m_enable) return;
  165. // if (deal->Login() != m_trader) return;
  166. //
  167. // m_api->LoggerOut(MTLogOK, L"OnDealDelete, login: %lld, deal: %lld, ord: %lld, pos: %lld, vol: %lld, volc: %lld",
  168. // deal->Login(), deal->Deal(), deal->Order(), deal->PositionID(), deal->Volume(), deal->VolumeClosed());
  169. //}
  170. //void CPluginInstance::OnDealClean(const UINT64 login)
  171. //{
  172. // std::lock_guard<decltype(m_lock)> lk(m_lock);
  173. // if (!m_enable) return;
  174. // if (login != m_trader) return;
  175. //
  176. // m_api->LoggerOut(MTLogOK, L"OndealClean, Login: %d", login);
  177. //}
  178. void CPluginInstance::OnDealPerform(const IMTDeal * deal, IMTAccount * account, IMTPosition * position)
  179. {
  180. // position为nullptr时,说明该deal不是由交易本身触发
  181. // account是deal完成后的用户状况
  182. // position是交易完成后的持仓状况
  183. // 对于deal是关闭一个持仓的情况,该position的volume会是0
  184. if (position == nullptr
  185. || deal == nullptr
  186. || account == nullptr)
  187. return;
  188. std::lock_guard<decltype(m_lock)> lk(m_lock);
  189. if (!m_enable) return;
  190. if (deal->Login() != m_trader) return;
  191. //m_api->LoggerOut(MTLogOK, L"OnDealPerform, login: %lld, deal: %lld, ord: %lld, pos: %lld, vol: %lld, volc: %lld",
  192. // deal->Login(), deal->Deal(), deal->Order(), deal->PositionID(), deal->Volume(), deal->VolumeClosed());
  193. // FIXME: 需要检查现在的deal是否和之前的order对应。如果没有记录到,则没法根本无法正常跟单以及平仓
  194. }
  195. MTAPIRES CPluginInstance::LoadParam()
  196. {
  197. MTAPIRES res = MT_RET_OK;
  198. IMTConParam* param = NULL;
  199. CMTStr128 tmp;
  200. if (!m_api || !m_config) return MT_RET_ERR_PARAMS;
  201. if ((res = m_api->PluginCurrent(m_config)) != MT_RET_OK)
  202. {
  203. m_api->LoggerOut(MTLogErr, L"failed to get current plugin configuration [%s (%u)]",
  204. SMTFormat::FormatError(res), res);
  205. return res;
  206. }
  207. if ((param = m_api->PluginParamCreate()) == NULL)
  208. {
  209. m_api->LoggerOut(MTLogErr, L"failed to create plugin parameter object");
  210. return MT_RET_ERR_MEM;
  211. }
  212. ScopeGuard param_release([param]()
  213. {
  214. param->Release();
  215. });
  216. std::lock_guard<decltype(m_lock)> lk(m_lock);
  217. if ((res = m_config->ParameterGet(L"Redis Server", param)) != MT_RET_OK || param->Type() != IMTConParam::TYPE_STRING)
  218. {
  219. return(MT_RET_ERR_PARAMS);
  220. }
  221. std::string redis_server = ws2s(param->ValueString());
  222. if ((res = m_config->ParameterGet(L"Redis Port", param)) != MT_RET_OK || param->Type() != IMTConParam::TYPE_INT)
  223. {
  224. return(MT_RET_ERR_PARAMS);
  225. }
  226. int redis_port = param->ValueInt();
  227. if ((res = m_config->ParameterGet(L"Redis User", param)) != MT_RET_OK || param->Type() != IMTConParam::TYPE_STRING)
  228. {
  229. return(MT_RET_ERR_PARAMS);
  230. }
  231. std::string redis_user = ws2s(param->ValueString());
  232. if ((res = m_config->ParameterGet(L"Redis Password", param)) != MT_RET_OK || param->Type() != IMTConParam::TYPE_STRING)
  233. {
  234. return(MT_RET_ERR_PARAMS);
  235. }
  236. std::string redis_password = ws2s(param->ValueString());
  237. if (m_redis_server != redis_server
  238. || m_redis_port != redis_port
  239. || m_redis_user != redis_user
  240. || m_redis_password != redis_password)
  241. {
  242. m_redis_server = redis_server;
  243. m_redis_port = redis_port;
  244. m_redis_user = redis_user;
  245. m_redis_password = redis_password;
  246. stop_redis();
  247. if (start_redis())
  248. {
  249. if (!m_work_thread.joinable())
  250. {
  251. m_work_thread = std::thread(&CPluginInstance::keep_alive, this);
  252. }
  253. }
  254. else
  255. {
  256. m_api->LoggerOut(MTLogErr, L"failed to connect to redis server");
  257. return MT_RET_ERR_CONNECTION;
  258. }
  259. }
  260. if ((res = m_config->ParameterGet(L"Trader", param)) != MT_RET_OK || param->Type() != IMTConParam::TYPE_INT)
  261. {
  262. return(MT_RET_ERR_PARAMS);
  263. }
  264. m_trader = param->ValueInt();
  265. if ((res = m_config->ParameterGet(L"Step", param)) != MT_RET_OK || param->Type() != IMTConParam::TYPE_INT)
  266. {
  267. return(MT_RET_ERR_PARAMS);
  268. }
  269. m_step = param->ValueInt();
  270. if ((res = m_config->ParameterGet(L"Tolerance", param)) != MT_RET_OK || param->Type() != IMTConParam::TYPE_INT)
  271. {
  272. return(MT_RET_ERR_PARAMS);
  273. }
  274. m_tolerance = param->ValueInt();
  275. if ((res = m_config->ParameterGet(L"Groups", param)) != MT_RET_OK || param->Type() != IMTConParam::TYPE_STRING)
  276. {
  277. return(MT_RET_ERR_PARAMS);
  278. }
  279. m_groups = param->ValueString();
  280. //if ((res = m_config->ParameterGet(L"Logins", param)) != MT_RET_OK || param->Type() != IMTConParam::TYPE_STRING)
  281. //{
  282. // return(MT_RET_ERR_PARAMS);
  283. //}
  284. //m_logins = param->ValueString();
  285. res = LoadLogins();
  286. if (res != MT_RET_OK)
  287. return res;
  288. m_enable = true;
  289. return MT_RET_OK;
  290. }
  291. MTAPIRES CPluginInstance::LoadLogins()
  292. {
  293. m_followers.clear();
  294. IMTConGroup* group = m_api->GroupCreate();
  295. ScopeGuard group_guard([&]()
  296. {
  297. group->Release();
  298. });
  299. if (group == nullptr) return MT_RET_ERR_MEM;
  300. UINT total = m_api->GroupTotal();
  301. MTAPIRES ret = MT_RET_OK;
  302. std::vector<std::wstring> groups;
  303. for (int i = 0; i < total; i++)
  304. {
  305. ret = m_api->GroupNext(i, group);
  306. if (ret != MT_RET_OK) break;
  307. groups.push_back(group->Group());
  308. }
  309. for (auto& group : groups)
  310. {
  311. UINT64* logins = nullptr;
  312. UINT total_users = 0;
  313. ret = m_api->UserLogins(group.c_str(), logins, total_users);
  314. if (ret = MT_RET_OK)
  315. {
  316. for (int i = 0; i < total_users; ++i)
  317. {
  318. m_followers.push_back(logins[i]);
  319. }
  320. }
  321. if (logins)
  322. {
  323. m_api->Free(logins);
  324. }
  325. }
  326. }
  327. bool CPluginInstance::start_redis()
  328. {
  329. try
  330. {
  331. m_redis_error_notified = false;
  332. if (m_redis_client)
  333. {
  334. if (m_redis_client->is_connected())
  335. return true;
  336. }
  337. m_redis_client.reset(new cpp_redis::client);
  338. m_redis_client->connect
  339. (
  340. m_redis_server,
  341. m_redis_port,
  342. [this](const std::string& host, std::size_t port, cpp_redis::connect_state status)
  343. {
  344. if (status == cpp_redis::connect_state::ok)
  345. {
  346. m_api->LoggerOut(MTLogErr, L"redis server connected");
  347. }
  348. },
  349. 500,
  350. 10000000,
  351. 1000
  352. );
  353. }
  354. catch (tacopie::tacopie_error& e)
  355. {
  356. m_api->LoggerOut(MTLogErr, L"redis conn: %s", e.what());
  357. return false;
  358. }
  359. catch (std::exception& e)
  360. {
  361. m_api->LoggerOut(MTLogErr, L"redis conn: %s", e.what());
  362. return false;
  363. }
  364. catch (...)
  365. {
  366. m_api->LoggerOut(MTLogErr, L"failed to connect to server");
  367. return false;
  368. }
  369. return true;
  370. }
  371. void CPluginInstance::stop_redis()
  372. {
  373. try
  374. {
  375. if (m_redis_client)
  376. {
  377. m_redis_client->sync_commit();
  378. m_redis_client->disconnect();
  379. m_redis_client.reset();
  380. }
  381. }
  382. catch (tacopie::tacopie_error& e)
  383. {
  384. m_api->LoggerOut(MTLogErr, L"stop redis: %s", e.what());
  385. }
  386. catch (std::exception& e)
  387. {
  388. m_api->LoggerOut(MTLogErr, L"stop redis: %s", e.what());
  389. }
  390. catch (...)
  391. {
  392. m_api->LoggerOut(MTLogErr, L"stop redis: unknown error");
  393. }
  394. }
  395. void CPluginInstance::keep_alive()
  396. {
  397. using namespace std::chrono_literals;
  398. int counter = 500;
  399. while (m_enable)
  400. {
  401. if (counter-- <= 0)
  402. {
  403. counter = 500;
  404. std::lock_guard<decltype(m_lock)> lk(m_lock);
  405. if (m_redis_client)
  406. {
  407. if (m_redis_client->is_connected())
  408. {
  409. m_redis_client->ping([this](cpp_redis::reply& r)
  410. {
  411. if (r.ko())
  412. {
  413. m_redis_error_notified = true;
  414. if (!m_redis_error_notified)
  415. {
  416. m_api->LoggerOut(MTLogErr, L"redis: %s", r.error().c_str());
  417. }
  418. }
  419. });
  420. }
  421. else
  422. {
  423. m_redis_error_notified = true;
  424. if (!m_redis_error_notified)
  425. {
  426. m_api->LoggerOut(MTLogErr, L"redis server not connected");
  427. }
  428. stop_redis();
  429. start_redis();
  430. }
  431. }
  432. }
  433. std::this_thread::sleep_for(16ms);
  434. }
  435. }