PluginInstance.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791
  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. stop_redis();
  73. if (m_work_thread.joinable())
  74. m_work_thread.join();
  75. return MT_RET_OK;
  76. }
  77. void CPluginInstance::OnPluginUpdate(const IMTConPlugin * plugin)
  78. {
  79. int ret = MT_RET_OK;
  80. if ((ret = LoadParam()) != MT_RET_OK)
  81. {
  82. m_api->LoggerOut(MTLogAtt, L"Load param failed [%d]", ret);
  83. }
  84. }
  85. //void CPluginInstance::OnOrderAdd(const IMTOrder * order)
  86. //{
  87. // if (order == nullptr) return;
  88. //
  89. // std::lock_guard<decltype(m_lock)> lk(m_lock);
  90. // if (!m_enable) return;
  91. // if (order->Login() != m_trader) return;
  92. //
  93. // m_api->LoggerOut(MTLogOK, L"OnOrderAdd, login: %lld, ord: %lld, pos: %lld, state: %lld, vol_init: %lld, vol_cur: %lld",
  94. // order->Login(), order->Order(), order->PositionID(), order->State(), order->VolumeInitial(), order->VolumeCurrent());
  95. //}
  96. //void CPluginInstance::OnOrderUpdate(const IMTOrder * order)
  97. //{
  98. // if (order == nullptr) return;
  99. //
  100. // std::lock_guard<decltype(m_lock)> lk(m_lock);
  101. // if (!m_enable) return;
  102. // if (order->Login() != m_trader) return;
  103. //
  104. // m_api->LoggerOut(MTLogOK, L"OnOrderAdd, login: %lld, ord: %lld, pos: %lld, state: %lld, vol_init: %lld, vol_cur: %lld",
  105. // order->Login(), order->Order(), order->PositionID(), order->State(), order->VolumeInitial(), order->VolumeCurrent());
  106. //}
  107. void CPluginInstance::OnOrderDelete(const IMTOrder * order)
  108. {
  109. if (order == nullptr) return;
  110. std::lock_guard<decltype(m_lock)> lk(m_lock);
  111. if (!m_enable) return;
  112. if (order->Login() != m_trader) return;
  113. m_api->LoggerOut(MTLogOK, L"OnOrderDelete, login: %lld, ord: %lld, pos: %lld, state: %d, vol_init: %lld, vol_cur: %lld",
  114. order->Login(), order->Order(), order->PositionID(), order->State(), order->VolumeInitial(), order->VolumeCurrent());
  115. if (order->Type() != IMTOrder::OP_BUY
  116. && order->Type() != IMTOrder::OP_SELL)
  117. {
  118. // 不是buy或者sell,不跟,直接退出
  119. return;
  120. }
  121. char order_buf[128];
  122. sprintf(order_buf, "%lld", order->Order());
  123. IMTAccount* account = m_api->UserCreateAccount();
  124. IMTOrder* new_order = m_api->OrderCreate();
  125. ScopeGuard guard([account, new_order]
  126. {
  127. account->Release();
  128. new_order->Release();
  129. });
  130. // 订单在进入filled状态时,也会产生一个order delete回调
  131. if (order->Order() == order->PositionID())
  132. {
  133. // 如果是新建订单,那么写入新纪录
  134. char login_buf[128];
  135. for (auto login : m_followers)
  136. {
  137. if (m_api->UserAccountGet(login, account) != MT_RET_OK)
  138. {
  139. // TODO: 这里失败直接跳过没有做其他处理,下一次进来可能依然会遇到一样的问题
  140. continue;
  141. }
  142. sprintf(login_buf, "%lld", login);
  143. UINT level = (UINT)(account->Balance() / m_step);
  144. UINT volume = round((double)level * order->VolumeCurrent() / 10000) * 100;
  145. UINT volume_ext = round((double)level * order->VolumeCurrentExt() / 10000) * 100;
  146. UINT init_volume = round((double)level * order->VolumeInitial() / 10000) * 100;
  147. UINT init_volume_ext = round((double)level * order->VolumeInitialExt() / 10000) * 100;
  148. UINT64 new_order_id = 0;
  149. // 尚未完成建仓,目前position id不填,仅完成订单后记录
  150. new_order->Clear();
  151. new_order->VolumeInitial(init_volume);
  152. new_order->VolumeCurrent(volume);
  153. new_order->Login(login);
  154. new_order->Symbol(order->Symbol());
  155. new_order->Type(order->Type());
  156. new_order->Digits(order->Digits());
  157. new_order->DigitsCurrency(order->DigitsCurrency());
  158. //new_order->ContractSize(order->ContractSize());
  159. new_order->PriceOrder(order->PriceOrder());
  160. //new_order->PriceCurrent(order->PriceCurrent());
  161. // State不能填PARTIAL FILLED REJECTED EXPIRED
  162. new_order->StateSet(IMTOrder::ORDER_STATE_STARTED);
  163. new_order->TimeSetup(m_api->TimeCurrent());
  164. new_order->TimeSetupMsc(m_api->TimeCurrentMsc());
  165. // 一定不能填入time done
  166. //new_order->TimeDone(order->TimeDone());
  167. //new_order->TimeDoneMsc(order->TimeDoneMsc());
  168. // --
  169. //new_order->PriceSL(order->PriceSL());
  170. //new_order->PriceTP(order->PriceTP());
  171. //new_order->Comment(order->Comment());
  172. //new_order->ActivationFlags(order->ActivationFlags());
  173. //new_order->ActivationMode(order->ActivationMode());
  174. //new_order->ActivationPrice(order->ActivationPrice());
  175. //new_order->ActivationTime(order->ActivationTime());
  176. //new_order->PriceTrigger(order->PriceTrigger());
  177. //new_order->RateMargin(order->RateMargin()); //
  178. //new_order->ReasonSet(order->Reason()); //
  179. //new_order->TypeFill(order->TypeFill()); //
  180. //new_order->TypeTime(order->TypeTime()); //
  181. MTAPIRES ret = m_api->OrderAdd(new_order);
  182. if (ret != MT_RET_OK)
  183. {
  184. m_api->LoggerOut(MTLogErr, L"%lld failed to add order, original order #%lld [%d]", login, order->Login(), ret);
  185. }
  186. else
  187. {
  188. new_order_id = new_order->Order();
  189. }
  190. // TODO: 现在做法是,如果level为0,后面都不管
  191. // 如果跟单失败,那么position id也为0,所以后面也不应该处理
  192. position_context context;
  193. context.level = level;
  194. context.cur_ord = new_order_id;
  195. context.position_id = new_order_id; // 建仓,order id = position id
  196. int direction = 1;
  197. if (order->Type() == IMTOrder::OP_SELL)
  198. direction = -1;
  199. context.volume = direction * order->VolumeInitial();
  200. auto fut = m_redis_client->hset(order_buf, login_buf, std::string((char*)&context, sizeof(context)));
  201. m_redis_client->sync_commit();
  202. auto rep = fut.get();
  203. if (rep.ko())
  204. {
  205. // FIXME: 错误处理
  206. }
  207. }
  208. }
  209. else
  210. {
  211. // 如果不是新建订单,先使用position id先检查记录是否存在
  212. char login_buf[128];
  213. for (auto login : m_followers)
  214. {
  215. sprintf(login_buf, "%lld", login);
  216. auto fut = m_redis_client->hget(order_buf, login_buf);
  217. m_redis_client->sync_commit();
  218. auto reply = fut.get();
  219. // 如果不存在,忽略
  220. if (reply.ko()) continue;
  221. if (reply.is_null()) continue;
  222. // 获取context
  223. position_context context;
  224. memcpy(&context, reply.as_string().c_str(), sizeof(position_context));
  225. // 按建仓时的叙述,如果level或者position为0,亦忽略该记录
  226. if (context.level == 0) continue;
  227. if (context.position_id == 0) continue;
  228. // 如果存在,则继续操作
  229. UINT volume = round((double)context.level * order->VolumeCurrent() / 10000) * 100;
  230. UINT volume_ext = round((double)context.level * order->VolumeCurrentExt() / 10000) * 100;
  231. UINT init_volume = round((double)context.level * order->VolumeInitial() / 10000) * 100;
  232. UINT init_volume_ext = round((double)context.level * order->VolumeInitialExt() / 10000) * 100;
  233. UINT64 new_order_id = 0;
  234. new_order->Clear();
  235. new_order->VolumeInitial(init_volume);
  236. new_order->VolumeCurrent(volume);
  237. new_order->Login(login);
  238. new_order->Symbol(order->Symbol());
  239. new_order->Type(order->Type());
  240. new_order->Digits(order->Digits());
  241. new_order->DigitsCurrency(order->DigitsCurrency());
  242. //new_order->ContractSize(order->ContractSize());
  243. new_order->PriceOrder(order->PriceOrder());
  244. //new_order->PriceCurrent(order->PriceCurrent());
  245. // State不能填PARTIAL FILLED REJECTED EXPIRED
  246. new_order->StateSet(IMTOrder::ORDER_STATE_STARTED);
  247. new_order->TimeSetup(m_api->TimeCurrent());
  248. new_order->TimeSetupMsc(m_api->TimeCurrentMsc());
  249. new_order->PositionID(context.position_id);
  250. MTAPIRES ret = m_api->OrderAdd(new_order);
  251. if (ret != MT_RET_OK)
  252. {
  253. m_api->LoggerOut(MTLogErr, L"%lld failed to add order, original order #%lld [%d]", login, order->Order(), ret);
  254. // FIXME: 如果做单失败该怎么办
  255. continue;
  256. }
  257. new_order_id = new_order->Order();
  258. m_api->LoggerOut(MTLogOK, L"%lld add order #%lld, original order #%lld [%d]", login, new_order_id, order->Order());
  259. // 完成之后,写入新纪录
  260. context.cur_ord = new_order_id;
  261. int direction = 1;
  262. if (order->Type() == IMTOrder::OP_SELL)
  263. direction = -1;
  264. context.volume += direction * order->VolumeInitial();
  265. auto wfut = m_redis_client->hset(order_buf, login_buf, std::string((char*)&context, sizeof(context)));
  266. m_redis_client->sync_commit();
  267. auto wrep = fut.get();
  268. if (wrep.ko())
  269. {
  270. // FIXME: 错误处理
  271. }
  272. }
  273. }
  274. }
  275. //void CPluginInstance::OnOrderClean(const UINT64 login)
  276. //{
  277. // std::lock_guard<decltype(m_lock)> lk(m_lock);
  278. // if (!m_enable) return;
  279. // if (login != m_trader) return;
  280. //
  281. // m_api->LoggerOut(MTLogOK, L"OnOrderClean, Login: %d", login);
  282. //}
  283. //void CPluginInstance::OnDealAdd(const IMTDeal * deal)
  284. //{
  285. // if (deal == nullptr) return;
  286. //
  287. // std::lock_guard<decltype(m_lock)> lk(m_lock);
  288. // if (!m_enable) return;
  289. // if (deal->Login() != m_trader) return;
  290. //
  291. // m_api->LoggerOut(MTLogOK, L"OnDealAdd, login: %lld, deal: %lld, ord: %lld, pos: %lld, vol: %lld, volc: %lld",
  292. // deal->Login(), deal->Deal(), deal->Order(), deal->PositionID(), deal->Volume(), deal->VolumeClosed());
  293. //}
  294. //void CPluginInstance::OnDealUpdate(const IMTDeal * deal)
  295. //{
  296. // if (deal == nullptr) return;
  297. //
  298. // std::lock_guard<decltype(m_lock)> lk(m_lock);
  299. // if (!m_enable) return;
  300. // if (deal->Login() != m_trader) return;
  301. //
  302. // m_api->LoggerOut(MTLogOK, L"OnDealUpdate, login: %lld, deal: %lld, ord: %lld, pos: %lld, vol: %lld, volc: %lld",
  303. // deal->Login(), deal->Deal(), deal->Order(), deal->PositionID(), deal->Volume(), deal->VolumeClosed());
  304. //}
  305. //void CPluginInstance::OnDealDelete(const IMTDeal * deal)
  306. //{
  307. // if (deal == nullptr) return;
  308. //
  309. // std::lock_guard<decltype(m_lock)> lk(m_lock);
  310. // if (!m_enable) return;
  311. // if (deal->Login() != m_trader) return;
  312. //
  313. // m_api->LoggerOut(MTLogOK, L"OnDealDelete, login: %lld, deal: %lld, ord: %lld, pos: %lld, vol: %lld, volc: %lld",
  314. // deal->Login(), deal->Deal(), deal->Order(), deal->PositionID(), deal->Volume(), deal->VolumeClosed());
  315. //}
  316. //void CPluginInstance::OnDealClean(const UINT64 login)
  317. //{
  318. // std::lock_guard<decltype(m_lock)> lk(m_lock);
  319. // if (!m_enable) return;
  320. // if (login != m_trader) return;
  321. //
  322. // m_api->LoggerOut(MTLogOK, L"OndealClean, Login: %d", login);
  323. //}
  324. void CPluginInstance::OnDealPerform(const IMTDeal * deal, IMTAccount * account, IMTPosition * position)
  325. {
  326. // position为nullptr时,说明该deal不是由交易本身触发
  327. // account是deal完成后的用户状况
  328. // position是交易完成后的持仓状况
  329. // 对于deal是关闭一个持仓的情况,该position的volume会是0
  330. if (position == nullptr
  331. || deal == nullptr
  332. || account == nullptr)
  333. return;
  334. std::lock_guard<decltype(m_lock)> lk(m_lock);
  335. if (!m_enable) return;
  336. if (deal->Login() != m_trader) return;
  337. //m_api->LoggerOut(MTLogOK, L"OnDealPerform, login: %lld, deal: %lld, ord: %lld, pos: %lld, vol: %lld, volc: %lld",
  338. // deal->Login(), deal->Deal(), deal->Order(), deal->PositionID(), deal->Volume(), deal->VolumeClosed());
  339. // FIXME: 需要检查现在的deal是否和之前的order对应。如果没有记录到,则没法根本无法正常跟单以及平仓
  340. char order_buf[128];
  341. sprintf(order_buf, "%lld", deal->Order());
  342. IMTDeal* new_deal = m_api->DealCreate();
  343. std::vector<std::string>* fields = nullptr;
  344. ScopeGuard guard([new_deal, fields]
  345. {
  346. new_deal->Release();
  347. if (fields)
  348. {
  349. fields->clear();
  350. delete fields;
  351. }
  352. });
  353. char login_buf[128];
  354. for (auto login : m_followers)
  355. {
  356. sprintf(login_buf, "%lld", login);
  357. auto fut = m_redis_client->hget(order_buf, login_buf);
  358. m_redis_client->sync_commit();
  359. auto reply = fut.get();
  360. m_api->LoggerOut(MTLogOK, L"%lld add deal, original deal #%lld", login, deal->Deal());
  361. // 如果不存在,忽略
  362. if (reply.ko()) continue;
  363. if (reply.is_null()) continue;
  364. // 获取context
  365. position_context context;
  366. memcpy(&context, reply.as_string().c_str(), sizeof(position_context));
  367. // 按建仓时的叙述,如果level或者position为0,亦忽略该记录
  368. if (context.level == 0) continue;
  369. if (context.position_id == 0) continue;
  370. uint64_t volume = context.level * deal->Volume() / 100;
  371. uint64_t volume_ext = context.level * deal->VolumeExt() / 100;
  372. uint64_t volume_closed = context.level * deal->VolumeClosed() / 100;
  373. uint64_t volume_closed_ext = context.level * deal->VolumeClosed() / 100;
  374. double prop = (double)volume / deal->Volume();
  375. double profit = deal->Profit() * prop;
  376. double commission = deal->Commission() * prop;
  377. double storage = deal->Storage() * prop;
  378. double raw_profit = deal->ProfitRaw() * prop;
  379. new_deal->Clear();
  380. new_deal->DealSet(0);
  381. new_deal->Volume(volume);
  382. new_deal->VolumeExt(volume_ext);
  383. new_deal->VolumeClosed(volume_closed);
  384. new_deal->VolumeClosedExt();
  385. new_deal->ProfitRaw(raw_profit);
  386. new_deal->Profit(profit);
  387. new_deal->Commission(commission);
  388. new_deal->Storage(storage);
  389. new_deal->Order(context.cur_ord);
  390. new_deal->PositionID(context.position_id);
  391. MTAPIRES ret = m_api->DealAdd(new_deal);
  392. if (ret != MT_RET_OK)
  393. {
  394. // TODO: 有没有更多的错误处理?
  395. m_api->LoggerOut(MTLogErr, L"%lld cannot add deal [%d], original deal: #%lld", login, ret, deal->Deal());
  396. continue;
  397. }
  398. m_api->LoggerOut(MTLogOK, L"add deal #%lld, original deal #%lld [%d]", new_deal->Deal(), deal->Deal());
  399. if (position->Volume() == 0)
  400. {
  401. if (fields == nullptr)
  402. fields = new(std::vector<std::string>);
  403. fields->push_back(login_buf);
  404. }
  405. }
  406. if (position->Volume() == 0)
  407. {
  408. // 如果平仓,则删除hash值
  409. if (position->Volume() == 0)
  410. {
  411. auto fut = m_redis_client->hdel(order_buf, *fields);
  412. m_redis_client->sync_commit();
  413. auto rep = fut.get();
  414. if (rep.ko())
  415. {
  416. // TODO 错误处理
  417. }
  418. }
  419. // TODO 当position中的volume为0时,持仓被彻底平调,被跟订单是否也该检查
  420. }
  421. }
  422. MTAPIRES CPluginInstance::LoadParam()
  423. {
  424. MTAPIRES res = MT_RET_OK;
  425. IMTConParam* param = NULL;
  426. CMTStr128 tmp;
  427. if (!m_api || !m_config) return MT_RET_ERR_PARAMS;
  428. if ((res = m_api->PluginCurrent(m_config)) != MT_RET_OK)
  429. {
  430. m_api->LoggerOut(MTLogErr, L"failed to get current plugin configuration [%s (%u)]",
  431. SMTFormat::FormatError(res), res);
  432. return res;
  433. }
  434. if ((param = m_api->PluginParamCreate()) == NULL)
  435. {
  436. m_api->LoggerOut(MTLogErr, L"failed to create plugin parameter object");
  437. return MT_RET_ERR_MEM;
  438. }
  439. ScopeGuard param_release([param]()
  440. {
  441. param->Release();
  442. });
  443. std::lock_guard<decltype(m_lock)> lk(m_lock);
  444. //m_api->LoggerOut(MTLogOK, L"Load redis server params");
  445. if ((res = m_config->ParameterGet(L"Redis Server", param)) != MT_RET_OK || param->Type() != IMTConParam::TYPE_STRING)
  446. {
  447. return(MT_RET_ERR_PARAMS);
  448. }
  449. std::string redis_server = ws2s(param->ValueString());
  450. if ((res = m_config->ParameterGet(L"Redis Port", param)) != MT_RET_OK || param->Type() != IMTConParam::TYPE_INT)
  451. {
  452. return(MT_RET_ERR_PARAMS);
  453. }
  454. int redis_port = param->ValueInt();
  455. //if ((res = m_config->ParameterGet(L"Redis User", param)) != MT_RET_OK || param->Type() != IMTConParam::TYPE_STRING)
  456. //{
  457. // return(MT_RET_ERR_PARAMS);
  458. //}
  459. //std::string redis_user = ws2s(param->ValueString());
  460. if ((res = m_config->ParameterGet(L"Redis Password", param)) != MT_RET_OK || param->Type() != IMTConParam::TYPE_STRING)
  461. {
  462. return(MT_RET_ERR_PARAMS);
  463. }
  464. std::string redis_password = ws2s(param->ValueString());
  465. if (m_redis_server != redis_server
  466. || m_redis_port != redis_port
  467. //|| m_redis_user != redis_user
  468. || m_redis_password != redis_password)
  469. {
  470. m_redis_server = redis_server;
  471. m_redis_port = redis_port;
  472. //m_redis_user = redis_user;
  473. m_redis_password = redis_password;
  474. stop_redis();
  475. if (start_redis())
  476. {
  477. if (!m_work_thread.joinable())
  478. {
  479. m_work_thread = std::thread(&CPluginInstance::keep_alive, this);
  480. }
  481. }
  482. else
  483. {
  484. m_api->LoggerOut(MTLogErr, L"failed to connect to redis server");
  485. return MT_RET_ERR_CONNECTION;
  486. }
  487. }
  488. //m_api->LoggerOut(MTLogOK, L"Load trade params");
  489. if ((res = m_config->ParameterGet(L"Trader", param)) != MT_RET_OK || param->Type() != IMTConParam::TYPE_INT)
  490. {
  491. return(MT_RET_ERR_PARAMS);
  492. }
  493. m_trader = param->ValueInt();
  494. if ((res = m_config->ParameterGet(L"Step", param)) != MT_RET_OK || param->Type() != IMTConParam::TYPE_INT)
  495. {
  496. return(MT_RET_ERR_PARAMS);
  497. }
  498. m_step = param->ValueInt();
  499. if ((res = m_config->ParameterGet(L"Tolerance", param)) != MT_RET_OK || param->Type() != IMTConParam::TYPE_INT)
  500. {
  501. return(MT_RET_ERR_PARAMS);
  502. }
  503. m_tolerance = param->ValueInt();
  504. if ((res = m_config->ParameterGet(L"Groups", param)) != MT_RET_OK || param->Type() != IMTConParam::TYPE_STRING)
  505. {
  506. return(MT_RET_ERR_PARAMS);
  507. }
  508. wcsncpy(m_groups, param->ValueString(), 1024);
  509. //if ((res = m_config->ParameterGet(L"Logins", param)) != MT_RET_OK || param->Type() != IMTConParam::TYPE_STRING)
  510. //{
  511. // return(MT_RET_ERR_PARAMS);
  512. //}
  513. //m_logins = param->ValueString();
  514. res = LoadLogins();
  515. if (res != MT_RET_OK)
  516. {
  517. m_api->LoggerOut(MTLogErr, L"failed to load clients [%d]", res);
  518. return res;
  519. }
  520. //m_api->LoggerOut(MTLogOK, L"Load param success");
  521. m_enable = true;
  522. return MT_RET_OK;
  523. }
  524. MTAPIRES CPluginInstance::LoadLogins()
  525. {
  526. m_followers.clear();
  527. IMTConGroup* group = m_api->GroupCreate();
  528. ScopeGuard group_guard([&]()
  529. {
  530. group->Release();
  531. });
  532. if (group == nullptr) return MT_RET_ERR_MEM;
  533. UINT total = m_api->GroupTotal();
  534. MTAPIRES ret = MT_RET_OK;
  535. std::vector<std::wstring> groups;
  536. for (int i = 0; i < total; i++)
  537. {
  538. ret = m_api->GroupNext(i, group);
  539. if (ret != MT_RET_OK) break;
  540. if (CheckGroup(m_groups, group->Group()) == FALSE) continue;
  541. m_api->LoggerOut(MTLogOK, L"group %s matched config", group->Group());
  542. groups.push_back(group->Group());
  543. }
  544. for (auto& group : groups)
  545. {
  546. UINT64* logins = nullptr;
  547. UINT total_users = 0;
  548. ret = m_api->UserLogins(group.c_str(), logins, total_users);
  549. m_api->LoggerOut(MTLogOK, L"add group %s, total users: %d", group.c_str(), total_users);
  550. if (ret == MT_RET_OK && logins != nullptr)
  551. {
  552. for (int i = 0; i < total_users; ++i)
  553. {
  554. m_api->LoggerOut(MTLogOK, L"add %d to list", logins[i]);
  555. m_followers.push_back(logins[i]);
  556. }
  557. }
  558. if (logins)
  559. {
  560. m_api->Free(logins);
  561. }
  562. }
  563. return ret;
  564. }
  565. bool CPluginInstance::start_redis()
  566. {
  567. try
  568. {
  569. m_redis_error_notified = false;
  570. if (m_redis_client)
  571. {
  572. if (m_redis_client->is_connected())
  573. return true;
  574. }
  575. m_redis_client.reset(new cpp_redis::client);
  576. m_redis_client->connect
  577. (
  578. m_redis_server,
  579. m_redis_port,
  580. [this](const std::string& host, std::size_t port, cpp_redis::connect_state status)
  581. {
  582. if (status == cpp_redis::connect_state::ok)
  583. {
  584. m_api->LoggerOut(MTLogOK, L"redis server connected");
  585. }
  586. },
  587. 500,
  588. 10000000,
  589. 1000
  590. );
  591. if (m_redis_password != "")
  592. {
  593. auto fut = m_redis_client->auth(m_redis_password);
  594. m_redis_client->sync_commit();
  595. auto reply = fut.get();
  596. if (reply.is_error())
  597. {
  598. m_api->LoggerOut(MTLogErr, L"connect: authentication failed");
  599. return false;
  600. }
  601. }
  602. }
  603. catch (tacopie::tacopie_error& e)
  604. {
  605. m_api->LoggerOut(MTLogErr, L"redis conn: %s", e.what());
  606. return false;
  607. }
  608. catch (std::exception& e)
  609. {
  610. m_api->LoggerOut(MTLogErr, L"redis conn: %s", e.what());
  611. return false;
  612. }
  613. catch (...)
  614. {
  615. m_api->LoggerOut(MTLogErr, L"failed to connect to server");
  616. return false;
  617. }
  618. return true;
  619. }
  620. void CPluginInstance::stop_redis()
  621. {
  622. try
  623. {
  624. if (m_redis_client)
  625. {
  626. m_redis_client->sync_commit();
  627. m_redis_client->disconnect();
  628. m_redis_client.reset();
  629. }
  630. }
  631. catch (tacopie::tacopie_error& e)
  632. {
  633. m_api->LoggerOut(MTLogErr, L"stop redis: %s", e.what());
  634. }
  635. catch (std::exception& e)
  636. {
  637. m_api->LoggerOut(MTLogErr, L"stop redis: %s", e.what());
  638. }
  639. catch (...)
  640. {
  641. m_api->LoggerOut(MTLogErr, L"stop redis: unknown error");
  642. }
  643. }
  644. void CPluginInstance::keep_alive()
  645. {
  646. using namespace std::chrono_literals;
  647. int counter = 500;
  648. while (m_enable)
  649. {
  650. if (counter-- <= 0)
  651. {
  652. counter = 500;
  653. std::lock_guard<decltype(m_lock)> lk(m_lock);
  654. if (m_redis_client)
  655. {
  656. if (m_redis_client->is_connected())
  657. {
  658. m_redis_client->ping([this](cpp_redis::reply& r)
  659. {
  660. if (r.ko())
  661. {
  662. m_redis_error_notified = true;
  663. if (!m_redis_error_notified)
  664. {
  665. m_api->LoggerOut(MTLogErr, L"redis: %s", r.error().c_str());
  666. }
  667. }
  668. });
  669. }
  670. else
  671. {
  672. m_redis_error_notified = true;
  673. if (!m_redis_error_notified)
  674. {
  675. m_api->LoggerOut(MTLogErr, L"redis server not connected");
  676. }
  677. stop_redis();
  678. start_redis();
  679. }
  680. }
  681. }
  682. std::this_thread::sleep_for(16ms);
  683. }
  684. }